Flutter - Stateful Widget Doesn't Save Counter State When Switching Tabs Flutter - Stateful Widget Doesn't Save Counter State When Switching Tabs dart dart

Flutter - Stateful Widget Doesn't Save Counter State When Switching Tabs


As _CounterState widget is built everytime you go to the given TabView you'll need to put _counter variable in the state configuration class (Counter).

class Counter extends StatefulWidget {  int _counter = 0;  @override  _CounterState createState() => new _CounterState();}class _CounterState extends State<Counter> {  void _increment() {    setState(() {      widget._counter++;    });  }  @override  Widget build(BuildContext context) {    return new Row(      children: <Widget>[        new RaisedButton(          onPressed: _increment,          child: new Text('Increment'),        ),        new Text('Count: ${widget._counter}'),      ],    );  }}


As I used one solution AutomaticKeepAliveClientMixin

You need to use this mixin with your state class of StateFullWidget.

you need to pass true to wantKeepAlive getter method.

class SampleWidget extends StatefulWidget {  @override  _SampleWidgetState createState() => _SampleWidgetState();}class _SampleWidgetState extends State<SampleWidget> with AutomaticKeepAliveClientMixin{  @override  Widget build(BuildContext context) {    return Container();  }  @override  // TODO: implement wantKeepAlive  bool get wantKeepAlive => true;}

This will save your state and stop your widget to recreate again. I have used it with Tabbar and PageView and it's working fine.


put the variable in that statefulwidget and then call it every time as "widget.variable_name"