How to Pass Data To Previous Screen Using Navigator

Data on 2nd screen can be returned on closing with

Navigator.pop(context, 'SUCCESS');

We only need to check for ‘SUCCESS’ in previous screen to determine what to do next.

String result = await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => SecondPage()),
              );
              if(result == 'SUCCESS'){
                print(result);
              }
import 'package:flutter/material.dart';

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

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

class _ExamplePageState extends State<ExamplePage> {
  

  

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Center(
            child: TextButton(child: Text('Go to 2nd page'), onPressed: () async{
              String result = await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => SecondPage()),
              );
              if(result == 'SUCCESS'){
                print(result);
              }
            }),
          ),
        ),
      ),
    );
  }
}

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

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

class _SecondPageState extends State<SecondPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: Center(child: TextButton(onPressed: () {
          Navigator.pop(context, 'SUCCESS');
        },
        child: Text('Return'), )),
      ),
    );
  }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close