Search code examples
flutterflutter-navigation

How to ignore invalid named routes in flutter?


I have a MateriallApp with few routes and onGenerateRoute callback. When I push an invalid route in Navigator.pushNamed, it throws me an error saying

Unhandled Exception: Could not find a generator for route RouteSettings("/path", null) in the _WidgetsAppState.
E/flutter ( 2342): Make sure your root app widget has provided a way to generate
E/flutter ( 2342): this route.
E/flutter ( 2342): Generators for routes are searched for in the following order:
E/flutter ( 2342):  1. For the "/" route, the "home" property, if non-null, is used.
E/flutter ( 2342):  2. Otherwise, the "routes" table is used, if it has an entry for the route.
E/flutter ( 2342):  3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
E/flutter ( 2342):  4. Finally if all else fails onUnknownRoute is called.
E/flutter ( 2342): Unfortunately, onUnknownRoute was not set.

After I set onUnknownRoute callback, it says:

When the _WidgetsAppState requested the route RouteSettings("/path", null) from its onUnknownRoute callback, the callback returned null. Such callbacks must never return null.

But I do not want to navigate anywhere if the route is invalid (so the user stays on the same screen).

Here's the question: how can I ignore broken routes? Is there any way to set this up on MaterialApp level?


Solution

  • This is wild, but what if you simply did the following:

    onUnknownRoute: (settings) {
      return MaterialPageRoute<void>(
        settings: settings,
        builder: (BuildContext context) {
            Navigator.pop(context);
            return Scaffold(body: Center(child: Text('Not Found'))); // This should never really be seen.
        },
      );
    },
    

    You'll be left with an ugly screen transition effect, but unless we simply prevent navigation when calling pushNamed (definitely what I'd recommend over this, but I guess you've got your reasons), this seems like an alternative.