Flutter – Arguments in Named Routes

Navigating between the various routes(ie, pages) of an application in Flutter is done with the use of Navigator. The Navigator uses a common identifier to transition between routes. One can pass arguments to these routes using the arguments parameter of Navigator.pushNamed() method. Arguments can be extracted using the ModalRoute.of() method or using the onGenerateRoute() function.

In this article, we will explore the approaches of argument extraction using the ModalRoute.of() method. We will do so by implementing both of them in a simple application. To do so follow the below steps:

  • Design the arguments that are to be passed
  • Create a widget that extracts the argument
  • Add the widget to the route table
  • Transition to the widget

Let’s discuss the above steps in detail:

Design the argument:

Here we will pass a single piece of data as an argument by designing an Argument class as follows:

Dart



filter_none

edit
close

play_arrow

link
brightness_4
code

class Arguments {
  final String title_bar;
  final String text_message;
  
  Arguments(this.title_bar, this.text_message);
}

chevron_right


Creating a widget:

Now make a widget the extract and displays the title_bar and text_message of the Argument Class and use the ModelRouteof() method to extract the argument as shown below:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';
  
  @override
  Widget build(BuildContext context) {
  
    final Arguments args = ModalRoute.of(context).settings.arguments;
  
    return Scaffold(
      appBar: AppBar(
        title: Text(args.title_bar),
      ),
      body: Center(
        child: Text(args.text_message),
      ),
    );
  }
}

chevron_right


Registering the widget:

To register the newly created widget to the routes table using the following:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

MaterialApp(
  routes: {
    ExtractArgumentsScreen.routeName: (context) => ExtractArgumentsScreen(),
  },
);

chevron_right


Transition:

On tap of the elevated button that we will add on the screen, it should transition to another screen and display the extracted text_message and the title_bar. To do so use the following:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

ElevatedButton(
  child: Text("Extracted through modelRouteof() method"),
  onPressed: () {
  
    Navigator.pushNamed(
      context,
      ExtractArgumentsScreen.routeName,
      arguments: ScreenArguments(
        'Extract Arguments Screen',
        'Extracted through modelRouteof() method',
      ),
    );
  },
),

chevron_right


Complete Source Code:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        onGenerateRoute: (settings) {
          if (settings.name == PassArgumentsScreen.routeName) {
            final ScreenArguments args = settings.arguments;
            return MaterialPageRoute(
              builder: (context) {
                return PassArgumentsScreen(
                  title: args.title,
                  message: args.message,
                );
              },
            );
          }
          assert(false, 'Implemntation ${settings.name}');
          return null;
        },
        title: 'Arguments in named routes',
        home: HomeScreen(),
        routes: {
          ExtractArgumentsScreen.routeName: (context) =>
              ExtractArgumentsScreen(),
        });
  }
}
  
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeekForGeeks'),
        backgroundColor: Colors.green,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              child: Text("Extracts arguments"),
              style: ButtonStyle(
                backgroundColor:MaterialStateProperty.all<Color>(Colors.green),
              ),
              onPressed: () {
                Navigator.pushNamed(
                  context,
                  ExtractArgumentsScreen.routeName,
                  arguments: ScreenArguments(
                    'Extract Arguments Screen',
                    'Extracted in the build method.',
                  ),
                );
              },
            ),
            // on tap navigate to named route
            ElevatedButton(
              child: Text("Accepts arguments"),
              style: ButtonStyle(
                backgroundColor:MaterialStateProperty.all<Color>(Colors.green),
              ),
              onPressed: () {
                // on tab change route
                Navigator.pushNamed(
                  context,
                  PassArgumentsScreen.routeName,
                  arguments: ScreenArguments(
                    'Accept Arguments Screen',
                    'Extracted in the onGenerateRoute function.',
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
  
class ExtractArgumentsScreen extends StatelessWidget {
  static const routeName = '/extractArguments';
  
  @override
  Widget build(BuildContext context) {
  
    final Arguments args = ModalRoute.of(context).settings.arguments;
  
    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}
  
//Widget to accept argumnets
class PassArgumentsScreen extends StatelessWidget {
  static const routeName = '/passArguments';
  
  final String title;
  final String message;
  
  
  const PassArgumentsScreen({
    Key key,
    @required this.title,
    @required this.message,
  }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Text(message),
      ),
    );
  }
}
  
  
class Arguments {
  final String title_bar;
  final String text_message;
  
  ScreenArguments(this.title_bar, this.text_message);
}

chevron_right


Output:




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.