How to pass data between screens in Flutter?

· 6 min read
Pass data between screens in Flutter
Pass data between screens in Flutter

While Developing Flutter Mobile Application you might have seen almost every screen require to pass data from one screen and receiving data on another screen. Today we will learn about pass data between screens in Flutter.

Are you ready for the same?

Let’s get started with the same.

How to pass data between screens in Flutter?

Today we will go through both passing data forward and passing data back. Unlike Android Activities and iOS ViewControllers, different screens in Flutter are just widgets. Navigating between them involves creating something called a route and using the Navigator to push and pop the routes on and off the stack.

Consider the below image to understand it in a proper way.

pass data from one screen to another screen in Flutter

Follow the below steps to send data from one screen to other screens.

  • Make the SecondScreen constructor take a parameter for the type of data that you want to send to it. In this particular example, the data is defined to be a String value and is set here with this.text.
class SecondScreen extends StatelessWidget {
  final String text;
  SecondScreen({Key key, @required this.text}) : super(key: key);

  ...
}

Then use the Navigator in the FirstScreen Widget to push a route to the SecondScreen Widget. You put the data that you want to send as a parameter in its constructor.

Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => SecondScreen(text: 'Hello',),
    ));

When passing data back you need to do the following things:

  • In the FirstScreen, use the Navigator to push (start) the SecondScreen in an async method and wait for the result that it will return when it finishes.
final result = await Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => SecondScreen(),
    ));
  • In the SecondScreen, include the data that you want to pass back as a parameter when you pop the Navigator.
Navigator.pop(context, 'Hello');
  • Then in the FirstScreen the await will finish and you can use the result.
setState(() {
  text = result;
});

Here is the complete code for main.dart for your reference.

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'Flutter',
    home: FirstScreen(),
  ));
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() {
    return _FirstScreenState();
  }
}

class _FirstScreenState extends State<FirstScreen> {

  String text = 'Text';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Padding(
              padding: const EdgeInsets.all(32.0),
              child: Text(
                text,
                style: TextStyle(fontSize: 24),
              ),
            ),

            RaisedButton(
              child: Text(
                'Go to second screen',
                style: TextStyle(fontSize: 24),
              ),
              onPressed: () {
                _awaitReturnValueFromSecondScreen(context);
              },
            )

          ],
        ),
      ),
    );
  }

  void _awaitReturnValueFromSecondScreen(BuildContext context) async {

    // start the SecondScreen and wait for it to finish with a result
    final result = await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SecondScreen(),
        ));

    // after the SecondScreen result comes back update the Text widget with it
    setState(() {
      text = result;
    });
  }
}

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() {
    return _SecondScreenState();
  }
}

class _SecondScreenState extends State<SecondScreen> {
  // this allows us to access the TextField text
  TextEditingController textFieldController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second screen')),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [

          Padding(
            padding: const EdgeInsets.all(32.0),
            child: TextField(
              controller: textFieldController,
              style: TextStyle(
                fontSize: 24,
                color: Colors.black,
              ),
            ),
          ),

          RaisedButton(
            child: Text(
              'Send text back',
              style: TextStyle(fontSize: 24),
            ),
            onPressed: () {
              _sendDataBack(context);
            },
          )

        ],
      ),
    );
  }

  // get the text in the TextField and send it back to the FirstScreen
  void _sendDataBack(BuildContext context) {
    String textToSendBack = textFieldController.text;
    Navigator.pop(context, textToSendBack);
  }
}

The perfect solution will look like below:

Navigator.pushNamed(context, "second",arguments: {"name" : 
  "Bijendra", "rollNo": 65210});
},

On Second Screen in build method get as :

@override
Widget build(BuildContext context) {
    final  Map<String, Object>rcvdData = ModalRoute.of(context).settings.arguments;
    print("rcvd fdata ${rcvdData['name']}");
    print("rcvd fdata ${rcvdData}");

    return Scaffold(appBar: AppBar(title: Text("Second")),
      body: Container(child: Column(children: <Widget>[
      Text("Second"),
    ],),),);

}
  • From where you want to push :
onPressed: () async {
                        await Navigator.pushNamed(context, '/edit',
                            arguments: userData);
                        setState(() {
                          userData = userData;
                        });}
  • Where you want to pop :
  void updateData() async{
  WorldTime instance = locations;
  await instance.getData();
  Navigator.pop(context, userData);
}

Conclusion:

In this article, we have been through how to pass data between screens in Flutter?

Thanks for Reading!!!
Keep Learning.

Do let us know if you need any assistance with Flutter Development?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply