Skip to main content

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 {
  

  

  @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 {
  @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.