0
0
Fluttermobile~5 mins

Passing data between screens in Flutter

Choose your learning style9 modes available
Introduction

Sometimes you want to send information from one screen to another in your app. Passing data between screens helps you share details like user choices or messages.

You want to show details about a selected item on a new screen.
You need to send user input from one page to another for confirmation.
You want to pass settings or preferences between screens.
You want to navigate to a screen that depends on some data from the previous screen.
Syntax
Flutter
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => SecondScreen(data: yourData),
  ),
);

Use MaterialPageRoute to create a route to the new screen.

Pass data as parameters to the new screen's constructor.

Examples
Passes a selected item object to the DetailScreen.
Flutter
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => DetailScreen(item: selectedItem),
  ),
);
Passes a simple text message to the MessageScreen.
Flutter
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => MessageScreen(message: 'Hello!'),
  ),
);
Sample App

This app has two screens. The first screen has a button. When you tap it, it goes to the second screen and sends a message. The second screen shows that message in big text.

Flutter
import 'package:flutter/material.dart';

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

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

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Screen')),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to Second Screen'),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondScreen(data: 'Hello from First Screen!'),
              ),
            );
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  final String data;
  SecondScreen({required this.data});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Screen')),
      body: Center(
        child: Text(data, style: TextStyle(fontSize: 24)),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always pass data through the constructor of the new screen for clarity.

You can pass any type of data: strings, numbers, objects, or lists.

Remember to mark constructor parameters as required if they must be provided.

Summary

Passing data between screens lets you share information as you move through your app.

Use Navigator.push with a route that builds the new screen and passes data via constructor.

This keeps your app interactive and connected across screens.