13. Flutter Tutorial for Beginners – Passing data between Screens

0
482

In this tutorial we are going to pass data between screens. First we pass the data to a stateless widget class.

To StatelessWidget:

First create a dart file into lib directory and named it secondPage.

Then write the following code to create a stateless widget and declare the class variable to receive the data from main.dart screen.

import 'package:flutter/material.dart';

class SecondPage extends StatelessWidget {
  final String data;
  SecondPage(this.data); // Receiving the data from First Page

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: Text(this.data), // Display the data
      ),
    );
  }
}

Then go back to main.dart file and import the secondPage.

import 'package:flutter_tutorial/secondpage.dart'; // import the Second Page

Write the following code to create a RaisedButton which is performed the routing to the second page with data.

RaisedButton(
  child: Text('Goto Second Page'),
  onPressed: (){
    String secondPageData = 'hello World!!!'; // Passing this variable to the Second Page
    Route route = MaterialPageRoute(builder: (context) => SecondPage(secondPageData));
    Navigator.push(context, route);
  },
)

That’s it…

Full code of First Screen:

import 'package:flutter/material.dart';
import 'package:flutter_tutorial/secondpage.dart'; // import the Second Page

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Goto Second Page'),
          onPressed: (){
            String secondPageData = 'hello World!!!'; // Passing this variable to the Second Page
            Route route = MaterialPageRoute(builder: (context) => SecondPage(secondPageData));
            Navigator.push(context, route);
          },
        ),
      ),
    );
  }
}

Full code of Second Screen:

import 'package:flutter/material.dart';

class SecondPage extends StatelessWidget {
  final String data;
  SecondPage(this.data); // Receiving the data from First Page

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: Text(this.data), // Display the data
      ),
    );
  }
}

To StatefulWidget:

And now we are going to pass data to Stateful Widget.

To do that create a file into lib directory as we mention before. And named it secondscreen.

Write the following code to create a stateful widget and declare the class variable to receive the data from the main.dart screen.

import 'package:flutter/material.dart';

class SecondScreen extends StatefulWidget {
  final String data;

  SecondScreen(this.data);//Receiving data from first screen

  @override
  _SecondScreenState createState() => _SecondScreenState(this.data);//Pass the data to the class
}

class _SecondScreenState extends State {
  String data;
  _SecondScreenState(this.data);//receive the data

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: Text(data),//Display the data
      ),
    );
  }
}

Then go back to main.dart file and import the secondscreen.

import 'package:flutter_tutorial/secondscreen.dart'; // import the Second Screen

That’s it…

Full code of First Screen:

import 'package:flutter/material.dart';
import 'package:flutter_tutorial/secondscreen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Goto Second Page'),
          onPressed: (){
            String data = 'hello World!!!';
            Route route = MaterialPageRoute(builder: (context) => SecondScreen(data));
            Navigator.push(context, route);
          },
        ),
      ),
    );
  }
}

Full code of Second Screen:

import 'package:flutter/material.dart';

class SecondScreen extends StatefulWidget {
  final String data;

  SecondScreen(this.data);//Receiving data from first screen

  @override
  _SecondScreenState createState() => _SecondScreenState(this.data);//Pass the data to the class
}

class _SecondScreenState extends State {
  String data;
  _SecondScreenState(this.data);//receive the data

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: Text(data),//Display the data
      ),
    );
  }
}

Passing data back to the previous screen

We will be showing you how to pass data when popping a view to a previous page.

In the FirstScreen, use the Navigator to push the SecondScreen in an async method and wait for the result that it will return when it finishes. And also declare a variable to store the result.

RaisedButton(
  child: Text('Goto Second Page'),
  onPressed: () async{
    String data = 'hello World!!!';
    Route route = MaterialPageRoute(builder: (context) => SecondScreen(data));
    final datafromSecondPage = await Navigator.push(context, route);
    _setData(datafromSecondPage);
  },
)

After that pass the variable to a method in order to show the result.

Then create the method to display the result.

_setData(String data)
{
  setState(() {
    _displayData = data;
  });
}

Then open the second screen. In the SecondScreen, include the data that you want to pass back as a parameter when you pop the Navigator.

Navigator.pop(context, "Text from Seceond Page");

Then in the Main Screen the await will finish and you can use the result.

Full code of First Page:

import 'package:flutter/material.dart';
import 'package:flutter_tutorial/secondscreen.dart';
import 'dart:async';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  String _displayData = "No Data";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Column(
        children: [
          Center(
            child: Text(_displayData),
          ),
          Center(
            child: RaisedButton(
              child: Text('Goto Second Page'),
              onPressed: () async{
                String data = 'hello World!!!';
                Route route = MaterialPageRoute(builder: (context) => SecondScreen(data));
                final datafromSecondPage = await Navigator.push(context, route);
                _setData(datafromSecondPage);
              },
            ),
          ),
        ],
      ),
    );
  }
  _setData(String data)
  {
    setState(() {
      _displayData = data;
    });
  }
}

Full code of Second Page:

import 'package:flutter/material.dart';

class SecondScreen extends StatefulWidget {
  final String data;

  SecondScreen(this.data);

  @override
  _SecondScreenState createState() => _SecondScreenState(this.data);
}

class _SecondScreenState extends State {
  String data;
  _SecondScreenState(this.data);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Screen'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(data),
            RaisedButton(
              child: Text('Go Back'),
              onPressed: (){
                Navigator.pop(context, "Text from Seceond Page");
              },
            ),
          ],
        ),
      ),
    );
  }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here