Skip to main content

How to Pass Data To Previous Screen Using Navigator in Flutter

One of the most frustrating things about developing mobile apps is handling navigation between screens. It is the same with Flutter. There are a number of methods for passing data between screens, but the most common one is to use the Navigator.

The Navigator is a widget that allows us to navigate to different screens. It takes an optional argument, which is the “context” in which the new screen will be displayed. In our case, we’ll use the MaterialApp widget, which provides us with a default context.

In this post, we’ll show you how to use the Navigator object to pass data between screens so that you can keep your users moving through your app with ease.

Data on 2nd screen can be returned on closing with Navigator.pop(context, 'any success message here').

import 'package:flutter/material.dart';

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

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

class _ListPageState extends State<ListPage> {
  

  

  @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) => DetailPage()),
              );
              if(result == 'OK'){
                print(result);
              }
            }),
          ),
        ),
      ),
    );
  }
}

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

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

class _DetailPageState extends State<DetailPage> {
  @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, 'OK');
        },
        child: Text('Return'), )),
      ),
    );
  }
}

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