aris
aris

Reputation: 24365

Why use onGenerateRoute() vs ModalRoute.of() in 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

Upvotes: 6

Views: 5248

Answers (1)

Rémi Rousselet
Rémi Rousselet

Reputation: 277527

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();
    }
  }
}

Upvotes: 12

Related Questions