1
<https://stackoverflow.com/a/32254702/10026969>  I am not getting this.

@override
void initState()  async{
// TODO: implement initState
super.initState();

FirebaseUser user = await _auth.currentUser();
if(user!=null){
  print('Already logged in with email  '+ user.email);
  // go to welcome screen
 }
}

I am unable to keep use onAuthStateChange,How to keep the user logged in until he log out, if anyone has any idea how to implement this , please help.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134

2 Answers2

1

If you want to use onAuthStateChange in flutter, then try the following:

var auth = FirebaseAuth.instance;
auth.onAuthStateChanged.listen((user) {
if (user != null) {
  print("user is logged in");
} else {
  print("user is not logged in");
   }
});

onAuthStateChanged returns a Stream therefore you can use listen() to keep listening for any changes.

https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_auth/firebase_auth/lib/src/firebase_auth.dart#L23

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
0

So onAuthStateChanged() returns a Stream. https://pub.dev/documentation/firebase_auth/latest/firebase_auth/FirebaseAuth/onAuthStateChanged.html

You can listen in to this stream for all of the events using a StreamBuilder. Based off the AsyncSnapshot returned from the builder function you can check if it hasData.

  1. Create your FirebaseAuth object. This object has the property of onAuthStateChanged().
  2. Pass the property _auth.onAuthStateChanged() to your StreamBuilder.

Pseudo Example Code:

final FirebaseAuth _auth = FirebaseAuth.instance;

Center(
  child: StreamBuilder(
    stream: _auth.onAuthStateChange(),
    builder: (context, asyncSnap) {
      //no available data yet
      if(!asyncSnap.hasData) {
        return Text("No data available yet.");
      } else if(asyncSnap.hasError) {
        return Text("Error");
      } else {
        //Use a switch here over all of the types of state coming back.
        return Text("Data from Snapshot: ${asyncSnap.data}");
      }
    }
  )
)
Bret Hagen
  • 123
  • 6