Flutter

How to pass data from one screen to another using named routes in Flutter?

In this tutorial we will learn how to pass data from one screen to another screen using named routing in flutter. As you know there are two ways to move from one screen to other screen is flutter. First one is Navigator.push and Second in Navigator.pushNamed. Here we will use Navigator.pushNamed and learn how to pass data from one screen to next screen using this method.

Why we need this?

When mobile developers develop apps, they have to do a lot of tricks, one of these is to pass data from one screen to another. I don’t think that there is any App that has more than one screens but there is no need to transfer data from one screen to another. Every screen contains data which is somehow related to previous screen. For example if you have a products list screen and a product detail screen. On click on product you have to move to the next screen which is product detail screen. And there you will show the product detail. For this you need the id of that product on which you click on previous screen. So we have to pass this id form products list screen to product detail screen.

Another example of this is, you have to fill a form in multiple steps. For example you want to fill a user profile form in three screens. First you fill the first form and click on next button. The info that you gained form first form now will be passed to second form. Now you will fill the second form and on click on next button the whole data of first form and second form will be passed to third form. Here you will fill the third form and on submit button the data of all three forms will be processed to save.  So here we will learn how to pass data from one screen to another screen using named routing in flutter.

These are two basic examples of this. There would be several cases that you will face in actual development phase.

Example

Here we will do a very simple example. We will create a form with two fields, First name and Last name. On button press we will navigate to next screen using named routed and will print name on next screen.

Code

We will start form routes class. Create routes.dart file and create Routes class in it with these two static variables.

routes.dart

class Routes{
static const firstScreen='/first-screen';
static const secondScreen='/second-screen';
}

Here we created two variables, first one is firstScreen and second one is secondScreen which we will use to navigate to next screen.

Now modify main.dart like this

main.dart

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        initialRoute: Routes.firstScreen,
        routes: {
          Routes.firstScreen: (context) => const FirstScreen(),
          Routes.secondScreen: (context) => const SecondScreen(),
        });
  }
}

In MyApp class we define the initial route and routed of whole App.

Now create a user model class. We are going to collect user data as first name and second name, and display this info in next screen. So first create a model class.

user.dart

class User{
  String firstName;
  String secondName;
  
  User({required this.firstName, required this.secondName});
}

Now create first_screen.dart and create statefull FirstScreen widget in it.

First_screen.dart

class FirstScreen extends StatefulWidget {
  const FirstScreen({Key? key}) : super(key: key);

  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  List<Product> products = [];
  TextEditingController firstNameController = TextEditingController();
  TextEditingController lastNameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('First Screen'),
        ),
        body: Center(
          child: Container(
            padding: const EdgeInsets.all(8),
            child: Column(
              children: [
                TextFormField(
                  controller: firstNameController,
                  decoration: const InputDecoration(hintText: 'Fist Name'),
                ),
                const SizedBox(
                  height: 20,
                ),
                TextFormField(
                  controller: lastNameController,
                  decoration: const InputDecoration(hintText: 'Last Name'),
                ),
                const SizedBox(
                  height: 20,
                ),
                ElevatedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, Routes.secondScreen,
                        arguments: User(
                            firstName: firstNameController.text.toString(),
                            secondName: lastNameController.text.toString()));
                  },
                  child: const Text('Next'),
                ),
              ],
            ),
          ),
        ));
  }


}

In the above code there are two text fields of first name and second name, and an elevated button. The focused part of this code is onPressed() method of elevated button. We passed an argument in Navigator.pushNamed method. We will receive this argument in second screen.

Now create second_screen.dart and create SeconScreen Stateful widget in it. Here receive the argument and display on screen.

Second_screen.dart

class SecondScreen extends StatefulWidget {
  const SecondScreen({Key? key}) : super(key: key);

  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {

  @override
  Widget build(BuildContext context) {
    User user= ModalRoute.of(context)!.settings.arguments as User;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Screen'),
      ),
      body: Center(
        child: Column(
          children: [
            Text('Fist Name  : '+ user.firstName),
            Text('Second Name  : '+ user.secondName),
          ],
        ),

      ),
    );
  }
}

Here we just receive the argument using this code.

User user= ModalRoute.of(context)!.settings.arguments as User;

And print the first name and second name on screen.

Leave a Reply

Your email address will not be published. Required fields are marked *