In Flutter, you can pass data between screens using Navigator
and the MaterialPageRoute
class. The Navigator
widget is used to manage the navigation stack, while the MaterialPageRoute
class defines the transition between two pages (screens).
Here’s an example of how to pass data from one screen to another in 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: RaisedButton(
child: Text('Go to Second Screen'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(data: 'Hello World'),
),
);
},
),
),
);
}
}
class SecondScreen extends StatelessWidget {
final String data;
SecondScreen({Key key, @required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: Text(data),
),
);
}
}
In this example, the FirstScreen
has a RaisedButton
that, when pressed, uses the Navigator
to navigate to the SecondScreen
. The data
property is passed as an argument to the SecondScreen
constructor when it is created. The SecondScreen
then displays the data
using a Text
widget.
Note that this is just one way to pass data between screens in Flutter, and there are other ways to do this, such as using a StatefulWidget
or Bloc
pattern. The method you choose will depend on your specific use case and requirements.