I am having an issue with go_router and can't seem to figure it out. I have used go_router successfully on previous Flutter mobile apps, but on my latest app, I am getting a weird issue in the redirect. The app starts to recurse when I use a "router.go('/launch')".
In the redirect, I am listening for changes in auth state, and if the user is null (i.e. not signed in), I want to redirect the user to the launch page. The code below is not redirecting to the launch page, it just starts looping. Please help, thank you.
Here is my router code:
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
name: 'home',
builder: (BuildContext context, GoRouterState state) =>
const NavBarPage(initialPage: 'Home'),
),
GoRoute(
path: '/menu',
name: 'menu',
builder: (context, state) => const MainMenuPage(),
),
GoRoute(
path: "/createPost",
name: 'createPost',
builder: (context, state) => const CreatePostPage(),
),
GoRoute(
path: "/launch",
name: 'launch',
builder: (context, state) => const LaunchPage(),
),
],
redirect: (BuildContext context, GoRouterState state) {
FirebaseAuth.instance.authStateChanges().listen((User? user) {
if (user == null) {
print('User is NOT signed in!');
print('User: $user');
router.go('/launch');
} else {
print('User is signed in!');
print('User: $user');
}
});
});
Here is what the run console in Android Studio displays:
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
flutter: User is NOT signed in!
flutter: User: null
The problem is that you're building the
authStateChanges()stream inside theredirectcallback and also adding a listener right after it. This will get called every timeredirectis called.Move your stream out from the
redirectcallback and store theuservariable somewhere. You can build the stream and listen to it in theinitStateof the widget, for example; and store theuservariable in the widget's state. Then, insideredirectyou just need to check thatuservariable.