'onGenerateRoute not redirecting with unauthenticated user

I am trying to redirect users to my login page if they visit my site without being logged in. I'm trying to use onGenerateRoute to do this. My code in main is this:

void main() async {
  
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseAuth auth = FirebaseAuth.instance;
  bool isAuth = auth.currentUser!=null ? true : false;
  
  runApp(MaterialApp(
    initialRoute: '/initial',
    title: 'Repeater Delivery',
    theme: ThemeData(...),
    onGenerateRoute: (settings) {
      if (!isAuth){
        print(settings);
          return MaterialPageRoute(
                      builder: (context) => Login(),
                      settings: RouteSettings(name: '/login'),
                  );
        }
    },
    routes: {
      '/initial': (context) => Home(),
      '/home': (context) => Home(),
      '/login': (context) => Login(),
      '/signup': (context) => Signup(),
      '/how_it_works': (context) => HowItWorks(),
      '/profile': (context) => UserProfile(),
    },
  ));
}

The page enters the if statement, so I know that that's working correctly, but I'm not sure how to then redirect to my login page. Also, when I go to a page on my site like www.site.com/#/profile and print out the settings from onGenerateRoute, it just prints a setting name of '/' instead of '/profile'. What am I doing wrong?



Solution 1:[1]

According to documentation MaterialApp.onGenerateRoute :

The route generator callback used when the app is navigated to a named route.

If this returns null when building the routes to handle the specified initialRoute, then all the routes are discarded and Navigator.defaultRouteName is used instead (/). See initialRoute.

During normal app operation, the onGenerateRoute callback will only be applied to route names pushed by the application, and so should never return null.

This is used if routes does not contain the requested route.

The Navigator is only built if routes are provided (either via home, routes, onGenerateRoute, or onUnknownRoute); if they are not, builder must not be null.

Here, your initialRoute is passed to onGenerateRoute, which is not always returning a route (because of the Auth condition). So Navigator is giving another route (the "/") as the initial one. onGenerateRoute must never return null on the App launch task.

Your routes property is only used when you're using pushNamed Navigator's method

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gbnfr