0

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);
}
Brandon
  • 2,034
  • 20
  • 25

1 Answers1

2

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();
    }
  );
}
Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
  • Thanks Colin. Do you think firebase auth would work with the stream builder? That's nifty. – Brandon Jun 19 '17 at 12:28
  • We don't currently expose the Firebase Auth current user as a stream, but we probably could. Feel free to open a new issue. https://github.com/flutter/flutter/issues/new – Collin Jackson Jun 19 '17 at 15:37