Force Flutter navigator to reload state when popping

CodeWithFlutter
3 Min Read

To force Flutter’s Navigator to reload the state of a route when it’s popped and then re-pushed, you can use the maintainsState property of the Route widget.

By default, maintainsState is set to true, which means that the state of a route will be preserved when it’s popped and then re-pushed. To force a reload, set maintainsState to false.

Here’s an example:

class MyPage extends StatefulWidget {
  @override
  _MyPageState createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Counter: $_counter'),
            RaisedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('Go back'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        child: Icon(Icons.add),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: RaisedButton(
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => MyPage(),
                  maintainState: false,
                ),
              );
            },
            child: Text('Go to page'),
          ),
        ),
      ),
    );
  }
}

In this example, the MyPage widget is stateful and has a counter that increments every time the floatingActionButton is pressed. When the “Go back” button is pressed, the Navigator will pop the MyPage route. Because maintainState is set to false, the MyPage state will be reset and the counter will be set back to zero when the route is re-pushed.

Share this Article
Leave a comment