Flutter refresh previous page on pop

Flutter: Refresh Previous Page on Pop

When navigating between screens (pages) in a Flutter app, you might encounter cases where you want to refresh the previous page after popping from the current page. In order to achieve this, you can use a combination of Navigator and setState method.

Let’s say you have two pages: Page A and Page B. You want to refresh Page A after popping from Page B. Here’s an example:

Page A:

    
import 'package:flutter/material.dart';

class PageA extends StatefulWidget {
  const PageA({Key key}) : super(key: key);

  @override
  _PageAState createState() => _PageAState();
}

class _PageAState extends State {
  String data = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Page A'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Page A'),
            Text('Data: $data'),
            RaisedButton(
              child: const Text('Go to Page B'),
              onPressed: () async {
                final result = await Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const PageB()),
                );
                setState(() {
                  data = result;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}
    
  

Page B:

    
import 'package:flutter/material.dart';

class PageB extends StatelessWidget {
  const PageB({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Page B'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('Page B'),
            RaisedButton(
              child: const Text('Go back to Page A'),
              onPressed: () {
                Navigator.pop(context, 'Updated data');
              },
            ),
          ],
        ),
      ),
    );
  }
}
    
  

In the above example, Page A has a string variable ‘data’ which is initially empty. When the user presses the button to go to Page B, the ‘await Navigator.push’ line opens Page B. After the user performs some action on Page B and presses the button to go back to Page A, the onPressed method of the RaisedButton in Page B is executed.

The line ‘Navigator.pop(context, ‘Updated data’)’ sends the result (in this case, the updated data) back to Page A. On popping from Page B, the await statement in Page A receives the result and assigns it to the ‘data’ variable using the setState method. This triggers a rebuild of Page A, updating the UI with the new data.

Leave a comment