Pass Data Between Screens-Flutter
A tutorial about passing data between screens.(For beginners)
There are basically 2 methods to pass data between two screens.
- Passing Data with Constructor
- Passing Data with Route Settings
Passing Data with Constructor
We need to design two screens. Let’s code the first screen.
I used a textfield and an ElevatedButton to send data. I made a Text Editing Controller to read data written to textfield. When you press the ElevatedButton, we send our data with ‘data:’ argument when going to the second screen with navigation.
And this is the second view. This widget is waiting String data from the firstView as you see. $data that passed from firstView is inside the Text widget.
Result :
Passing Data with Route Settings
It is similar to pass data with constructor. This time we can pass any type of data with route settings unlike constructor. Here we have passed the data inside the arguments of RouteSettings.
To get data on the second screen we use ModalRoute. You will get the data as Object?. So you need to cast it to what data type you have sent from the first screen.
Result :
That’s all for this article.
Subscribe for upcoming posts. Thanks for reading, and have a wonderful day!