Brandon
Brandon

Reputation: 2094

How can I test if the user is signed in and if not route to another page in my Flutter app?

I want to navigate to another page if the user is not signed in. I've tried to add this code to the initState but I can't use navigation at this stage of the lifecycle. Is there another option?

This won't work in the constructors of the StatefulWidget or State either. From what it looks like I have to control the routing.

// Where can I apply this code.
if (auth.currentUser == null) {
  Navigator.of(context).pushNamed(SignInPage.routeName);
}

Upvotes: 0

Views: 692

Answers (1)

Collin Jackson
Collin Jackson

Reputation: 116828

A similar question was asked here.

While it's technically possible to do what you want with a post-frame callback, you probably don't want to push a new route onto the Navigator here, because you don't want the user to be able to press the back button on the sign in page and go back to the home page. Also, you probably want to handle the case of the user logging out by taking them back to the sign in screen.

Consider having something like this in your main screen's build function.

Widget build() {
  return auth.currentUser == null ? new SignInPage() : new HomePage();
}

If you are using Google Sign In

Widget build() {
  return new StreamBuilder(
    stream: googleSignIn.onCurrentUserChanged,
    builder: (context, user) {
      return user.data != null ? new HomePage() : new SignInPage();
    }
  );
}

Upvotes: 3

Related Questions