Why I should use named routes?
12:32 11 Mar 2022

I searched a lot about "what are benefits of using named route to navigate between screens". And I can't find any actual benefits, actually it has many disadvantages and annoying.

1. In flutter document, it said that named routes use to avoid code duplication.

For example, if I want to navigate to SecondRoute with String one argument, it change from this

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => SecondRoute('Some text')),
);

to this

Navigator.pushNamed(context, SecondRoute.routeName, arguments: 'Some text');

and I need to register it in main file

MaterialApp(
  onGenerateRoute: (settings) {
    if (settings.name == SecondRoute.routeName) {
      final String text = settings.arguments as String;
      return MaterialPageRoute(
        builder: (context) => SecondRoute(text),
      );
    }
  },
);

And if I have more routes, I need to handle and assign arguments for every routes. Isn't that more duplication and complexity?

Also setting.arguments has no-type, isn't that very bad?

2. You can't select which constructor to use when using pushNamed.

For example, I have two constructor default and otherConstructor

class SecondRoute extends StatelessWidget {
  static const String routeName = '/second';
  String? text;

  SecondRoute(this.text);

  SecondRoute.otherConstructor(String text) {
    this.text = 'Other Constructor: ' + text;
  }
}

How can I tell pushNamed which one I want to use.

I have an idea to pass constructor name as an argument and check it like this

Navigator.pushNamed(context, SecondRoute.routeName, arguments: ['default' or 'otherConstructor','Some text']);

In main file

MaterialApp(
  onGenerateRoute: (settings) {
    if (settings.name == SecondRoute.routeName) {
      final args = settings.arguments as List;
      if (args[0] == 'otherConstructor') {
        return MaterialPageRoute(
          builder: (context) => SecondRoute.otherConstructor(text),
        );
      } else if (args[0] == 'default') {
        return MaterialPageRoute(
          builder: (context) => SecondRoute(text),
        );
      }
    }
  },
);

But this is very very complicate and obviously not a good way to do.

3. Some anwsers in reddit and stackoverflow said that named route make code more centralize by keep every route in main file.

Surely centralization is good, but why not do it others way?

For example, keep all dart files that contain routes in new folder

enter image description here

Can someone enlighten me why most people use named route? Thanks for any help.

flutter