Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use onGenerateRoute() vs ModalRoute.of() in Flutter?

Tags:

flutter

Is there any reason to use one over the other in any given circumstance? I'm trying to figure out why there are two ways of doing this. I'm referring to the "navigate with arguments" cookbook recipe:

https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments

like image 613
aris Avatar asked Jul 09 '19 22:07

aris


People also ask

What is the use of onGenerateRoute in flutter?

As a result, on opening the app, the route takes the user to a certain page. Good news is, Flutter has a built-in feature for achieving such a feat. Moreover, we can control the navigation at the very beginning of our Flutter app. To do this, in flutter MaterialApp widget, we use onGenerateRoute property.

What is ModalRoute in flutter?

A route that blocks interaction with previous routes. ModalRoutes cover the entire Navigator. They are not necessarily opaque, however; for example, a pop-up menu uses a ModalRoute but only shows the menu in a small box overlapping the previous route. The T type argument is the return value of the route.

What is RouteSettings in flutter?

RouteSettings class Null safetyData that might be useful in constructing a Route.


1 Answers

ModalRoute.of is used to build the route after it has been pushed in the navigation history.

onGenerateRoute does the same, but before that route is pushed in the navigation history.

ModalRoute.of is enough for most use-cases. But onGenerateRoute is more flexible. It allows building the route conditionally based on what the argument is, or type checking that the argument is valid:

onGenerateRoute: (RouteSettings settings) {
  if (settings.name == '/custom-route') {
    assert(settings.arguments is MyCustomArgument);
  }
}

or:

onGenerateRoute: (RouteSettings settings) {
  if (settings.name == '/users') {
    if (settings.arguments != null) {
      return UserDetailsRoute(id: settings.arguments);
    }
    else {
      return UserListRoute();
    }
  }
}
like image 189
Rémi Rousselet Avatar answered Nov 15 '22 06:11

Rémi Rousselet