0
votes

I have a small flutter application with several stateful and stateless widgets. My drawer widget looks like follows:

class AppDrawer extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          _createDrawerHeader(),
          ListTile(
            title: Text('Scenario'),
            onTap: () {
              Navigator.pop(context);
              Navigator.pushReplacementNamed(context, Routes.scenario);
            },
          ),
...

This works fine for switche between my widgets. I now have a simple counter widget that stores a counter variable in its state.

class Counter extends StatefulWidget {
  static const String routeName = '/Counter';

  int _counter = 0;
  @override
  _CounterState createState() => new _CounterState();
}

class _CounterState extends State<Counter> {
  void _increment() {
    setState(() {
      widget._counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: <Widget>[
          new RaisedButton(
            onPressed: _increment,
            child: new Text('Increment'),
          ),
          new Text('Count: ${widget._counter}'),
        ],
      ),
      drawer: AppDrawer(),
    );
  }
}

If I switch between this and my other widgets with the drawer and go back to the counter widgets the counter is always 0. Looks like the state is initialized everytime. I am a beginner using flutter and I thougt I can save a variable within this state. I think I am wrong. As my search didn't get my some usable results maybe you can give me an idea how to solve this or just provide some links with information. Thanks for your help :)

1
How are you maintaining the state in your application? Are you using bloc, provider or any other approach?Sanjay Sharma
No, I just wanted to store the counter so far. So it seems I need something more than just the state class of a stateful widget?tanktoo
Try replacing pushReplacementNamed with pushNamed. the replacement basically removes the current removes the route associated with this context hence the Counter widget. While just push will place the new route on top of navigator stack saving the previous one's stateFardeen Khan
You can store the state and pass it back to the widget when it's created. For e.g. you can store the counter using some state management way and then reuse the stored value.Sanjay Sharma
Replacing pushReplacementNamed with pushNamed did not change anything.tanktoo

1 Answers

0
votes

I suggest learning some sort of State Management practice's. You will eventually need to learn this because this is an essential step.Try provider its easy and simple to use.