Search code examples
androidfluttergoogle-chromenavigation

onGenerateRoute gets called multiple times but the navigator only builds once flutter


I am currently building an app where I need to have nested Navigation. Therefore I have a Widget that consists of a Navigator widget. I contains 3 named routes it can go. The initial route leads to the AuthoverviewPage. It is also possible to push a ForgotPasswordPage or the VerificationPage in terms a user has registered but needs to verify his email.

The issue I have is that the NavigatorAuthSate class initializes once and so does the build do as well. However the onGenerateRoute gets called three times of which 2 times the default gets called (see the output).

I've checked if subwidgets or parents effect anything but I did not find out anything new. In the end it builds just fine and in the web everything works fine. However as I'am currently trying to get the android back button to work and am facing issues with it. I thought about this being a potential reason.
There has been another issue on StackOverflow but to me it seems something differnt, correct me if I am wrong: onGenerateRoute called multiple times

class _NavigatorAuthState extends State<NavigatorAuth> {
  @override
  void initState() {
    print("init");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return Navigator(
        key: NavigatorAuth._navKeyAuth,   // returns a global key of type navigatorstate
        initialRoute: '/auth/overview',
        onGenerateRoute: (settings) {
          switch (settings.name) {
            case '/auth/overview':
              print("overview");
              return MaterialPageRoute(builder: (_) => const AuthOverviewPage());
            case '/auth/verification':
              print("verification");
              return MaterialPageRoute(builder: (_) => const VerifyEmailPage());
            case '/auth/forgotPassword':
              print("forgotpassword");
              return MaterialPageRoute(builder: (_) => const ForgotPasswordPage());
            default:
              print("default");
              return MaterialPageRoute(builder: (_) => const AuthOverviewPage());
          }
        } ,
    );
  }

Output:

init
build
default
default
overview

Solution

  • So after further investigation the multiple calls of the rautes are due to the / notation. So basically I removed the /auth from all the routes to prevent the multiple calls. Also I set the initial route and the one that leads to AuthOverviewPage to "/" (so they are default routes). Now the routes and its Widgets are only called once. However I decided to switch to go_router as it fits my usecases and also seems to be a "newer" pattern.