Home > Blockchain >  How to Maintain State of Drawer's Child Widget
How to Maintain State of Drawer's Child Widget

Time:11-28

I have a stateful widget, Counter, with a button and a counter that keeps track of how many times the button was pressed. This widget is in the drawer. When I close and open the drawer again, the counter is reset. How do I make it so that the counter is not reset upon closing and opening the drawer?

Here is the code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        drawer: Drawer(
          child: Counter(),
        ),
        appBar: AppBar(),
        body: Container(),
      ),
    );
  }
}

class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(_count.toString()),
        ElevatedButton(
          onPressed: () {
            setState(() {
              _count = _count   1;
            });
          },
          child: Text('Increment Counter'),
        )
      ],
    );
  }
}

CodePudding user response:

To keep state of a variable within the Drawer(), the real solution would be to use a State Management library.

However, what you can do is create a global variable and pass it down the tree to Drawer():

import 'package:flutter/material.dart';

void main() {
  runApp( MyApp());
}

class MyApp extends StatelessWidget {
  var counter = 0;
  MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(

        drawer: Drawer(
          child: Counter(counter: counter,),
        ),
        appBar: AppBar(),
        body: Container(),
      ),
    );
  }
}



class Counter extends StatefulWidget {
  int counter;
  Counter({required this.counter,super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(widget.counter.toString()),
        ElevatedButton(
          onPressed: () {
            setState(() {
              widget.counter = widget.counter   1;
            });
          },
          child: Text('Increment Counter'),
        )
      ],
    );
  }
}
  • Related