Pass Arguments in Flutter’s Named Routes

Navigator is the class behind navigating between the various routes of an application in Flutter. Navigator.pushNamed() method is used to navigate to a route with pre-defined name, hence named routes.

The following approach is what I use in this quiz web app.

Define a data class aka argument

We create a category data class. When we click a button represents a category, we pass it to next screen.

class Category {
  final String name;
  final String description;

  Category(this.name, this.description);
}

Define routes

In main.dart, we defines home page (first screen) and quiz page which receives the category parameter.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: AppConfig.APP_NAME,      
      initialRoute: '/',
      routes: {
        '/': (context) => CategoryPage(),
        '/quiz': (context) =>
            QuizPage(category: ModalRoute.of(context).settings.arguments),
      },
    );
  }
}

Our home “/” is CategoryPage screen, and the “/quiz” page is QuizPage with category parameter as ModalRoute.of(context).settings.arguments.

ScreenPage

This page loads category data and pass it to QuizPage when a respective action is performed.

I only post the code of a button in CategoryPage here.

ElevatedButton(
    child: Text('Next page'),
    onPressed: () {
      Navigator.pushNamed(context, QuizPage.routeName,
          arguments: Category('technology', 'This category consists of technology-related articles.'));
    },
)

QuizPage

On this page, we define the Category as a field then use the argument as a class field normally.

class QuizPage extends StatefulWidget {
  static const routeName = '/quiz';
  final Category category;

  const QuizPage({Key key, this.category}) : super(key: key);

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

class _QuizPageState extends State<QuizPage> {
	@override
	Widget build(BuildContext context) {
		return Scaffold(
		    appBar: AppBar(title: Quiz),
		    body: SafeArea(
		      child: Text(widget.category.name),
		    ),
		);
	}
}

Leave a Comment

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

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close