简体   繁体   中英

Navigate to another page in StreamBiulder on Flutter

I'm Trying to know if the user is logged in or not using firebase google Auth and send him to different pages depending the case. If the user is Logged in, Streambuilder returns profile() and if not, signUp() is returned. So far, so good. But what I need is to Navigate to another page using Navigator instead of returning widgets.

I need to do this:

Navigator.push( context, MaterialPageRoute(builder: (context) => profile()),

Instead of:

return profile();

The code I'm working on is:

 body: StreamBuilder(
              stream: FirebaseAuth.instance.authStateChanges(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                } else if (snapshot.hasData) {
                  return profile();
                } else if (snapshot.hasError) {
                  return Center(child: Text("Something went wrong"));
                } else {
                  return signUp();
                }
              },
            ),

Any idea on how to do this? Should I use other approach instead of a Streambuilder? Thanks in advance!

the FirebaseAuth.instance.authStateChanges() returns a Stream , so you can listen to it inside your app and make acts based on it, instead of using it in a StreamBuilder , you can listen to it like this:

FirebaseAuth.instance.authStateChanges().listen((user) {
 if(user != null) {
   Navigator.push( context, MaterialPageRoute(builder: (context) => profile()),
 } else {
   Navigator.push( context, MaterialPageRoute(builder: (context) => Login()),
 }
});

you need just to find a place where you're going to call it, once it listens to the authStateChanges() , by authenticating a new user or logging him out, this stream will trigger the change and execute the code inside of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM