skip to Main Content

I’ve implemented an app on Flutter framework. I’m new to flutter and I don’t know how to pass the data to new screen. Someone said me that you should use Named routes in your app so I tried it. But now I don’t know how to pass the data from one screen to another screen.

These are the routes in my MaterialApp:



routes: {
    '/': (context) => FirstPage(),
    '/second': (context) => SecondPage(),
    '/third': (context) => ThirdPage(),
},

And this is how I navigate to new screen normally:



onPressed: () { 
    Navigator.pushNamed(context, '/second');
},

I want to pass the data to new screen when navigate to new screen.

2

Answers


  1. You just need to pass the arguments. First in the file where you want your pass the data extract the argument like this:

    final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    final data = args['data'];
    return Scaffold(
         body: Center(
           child: Column(
             mainAxisAlignment: MainAxisAlignment.center,
             children: [
               Text('$data'),
             ],
          ),
       ),
    );
    

    Now where you navigate the page just pass the arguments like this:

    Navigator.pushNamed(context, '/second',
             arguments: {'data': 'Data from previous screen'});
    

    All set. I hope this helps you. Happy Coding…

    Login or Signup to reply.
  2. There are different ways to pass data from one screen to another but to pass data between screens using named routes in Flutter, you can utilise the arguments parameter in Navigator.pushNamed. Here’s how you can do it:

    First, define your routes with arguments in your MaterialApp:

    routes: {
      '/': (context) => FirstPage(),
      '/second': (context) => SecondPage(),
      '/third': (context) => ThirdPage(),
    },
    

    Now, when navigating to the second screen (SecondPage), you can pass data along with the route:

    onPressed: () { 
      Navigator.pushNamed(
        context,
        '/second',
        arguments: {/* Your data here */},
      );
    },
    

    In the SecondPage widget, you can retrieve the data using ModalRoute.of(context).settings.arguments:

    class SecondPage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final dynamic data = ModalRoute.of(context).settings.arguments;
        // Now you can use 'data' to access the passed data
        return Container();
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search