Advantage from static routing to dynamic routing on Flutter


I can see that MaterialApp app can receive routes.

1. Static routing

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/page1': (context) => Page1(title: "Main page"),

And show them from the widgets like:


There are other parameters like onGenerateRoute and initialRoute which confuse me more.

2. Dynamic Pages

onPressed: () {
    MaterialPageRoute(builder: (context) => SecondRoute()),


Im wondering what is the implication of this parameters and letting this "responsibility" to the MaterialApp, and why we should do it, maybe something related to memory management or how the Widget lifecycle works, or what?

What are the differences between 1. and 2.?


The answer lies more in your architecture than anything.

1. Static Routing is the better of the two in terms of managing a projects complexity. Routes are clearly defined for multiple developers to understand, and the navigation code is much easier, Navigator.of(context).pushNamed('your-route'); vs

   MaterialPageRoute(builder: (context) => SecondRoute()),

2. Dynamic Pages is commonly in tutorials and such to reduce boilerplate code. It is merely a shortcut to navigate. The downside of this is it becomes hard to manage routes, and so should be limited to short tutorials.

3. Generated Routes There is a third option though, that in my opinion is the best of the two, and that is a Generated Routes. This is the cleanest and easiest to mantain structure. There is a great tutorial here about it. Here is the rundown:

  1. Declare Routes:
class RoutePaths {
  static const Start = '/';
  static const SecondScreen = 'second'
  1. Declare your router:
class Router {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch ( {
      case RoutePaths.Start:
        return MaterialPageRoute(builder: (_) => YourFirstScreenWidget());

      case RoutePaths.SecondScreen:
        // you can do things like pass arguments to screens
        final event = settings.arguments as Event;
        return MaterialPageRoute(
            builder: (_) => YourSecondScreenWidget(event: event));

        return MaterialPageRoute(
            builder: (_) => Scaffold(
                  body: Center(
                    child: Text('No route defined for ${}'),

  1. Declare it in main.dart
initialRoute: RoutePaths.Start,
onGenerateRoute: Router.generateRoute,
  1. Navigate
// arguments: event is an optional parameter to send to secondScreen
Navigator.of(context).pushNamed(RoutePaths.SecondScreen, arguments: event);

Answered By – Gabe

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

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