Generating Flutter route after action?

3.8k Views Asked by At

I'm trying to automatically route back to my menu screen after a successful login and I'm having trouble generating a Widget build and/or context. I'm doing this in a Stateless Widget. Here is my code. I would like to call route after the last print statement...

Future<Null> _handleSignIn() async {
    try {
      await _googleSignIn.disconnect();
      GoogleSignInAccount googleUser = await _googleSignIn.signIn();
      GoogleSignInAuthentication googleAuth = await googleUser.authentication;

      print(googleAuth.idToken);

      await FirebaseAuth.instance.signInWithGoogle(idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);


    } catch (error) {
      print(error);
    }
    print("Let's Do This");
    print(_googleSignIn.currentUser.displayName);
    print(FirebaseAuth.instance.currentUser);
  }
2

There are 2 best solutions below

1
On BEST ANSWER

From what I understand from your question you basically need to setup your sign in button to redirect the users to wherever you want them to be after a successful sign in.

You can setup your onPressed call as follows, and you should be fine from here:

onPressed: () {_handleSignIn().whenComplete( ()=>Navigator.of(context).pushNamed("/MyHome"));
                      }

Note that you can not use Navigator outside your build method, hence you always need to handle the navigation parts within your widgets. Check the comment on this answer.

0
On

There is another way to do it without user interaction.

class SplashScreen extends StatelessWidget {

  Future<bool> _checkSignIn(BuildContext context) async {
    await globals.checkSignIn();
    globals.intialRoute = '/';
    if (globals.signInMode == SignInMode.SignedIn) {
      Navigator.of(context).pushNamedAndRemoveUntil('/', ModalRoute.withName('/splash'));
    } else {
      Navigator.pushReplacementNamed(context, '/login');
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    _checkSignIn(context);
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: const <Widget>[
          CircularProgressIndicator(),
        ],
      ),
    );
  }
}

The globals.checkSignIn() methods checks if the user is already signed in. It returns globals.signInMode based on the signin status. Based on the status, the navigator is called to navigate to the next page.

The _checkSignIn() method is called in the build method without an "await". This is because our intention is to just build a screen while waiting for the signin check. Once the check is done, the navigator takes care of the rest.