Alex
Alex

Reputation: 37

How to use .currentUser method in flutter

i have some code:

  getFavSalons(AsyncSnapshot<QuerySnapshot> snapshot) {
return snapshot.data.documents
    .map((doc) => SalonBlock(
          salonName: doc["salonName"],
          location: doc["location"],
          workTime: doc["workTime"],
          rating: doc["rating"],
        ))
    .toList();

}

and part of code where I building list:

             StreamBuilder(
                  stream: Firestore.instance
                      .collection("customers")
                      .document("HAQaVqCPRfM7h6yf2liZlLlzuLu2")
                      .collection("favSalons")
                      .snapshots(),
                  builder:
                      (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasData) {
                      return Container(
                        margin:
                            EdgeInsets.only(bottom: screenHeight * 0.33),
                        child: new ListView(
                          children: getFavSalons(snapshot),
                        ),
                      );
                    }
                    return LoadingSalon();
                  }),

and here I use uid:

.document("HAQaVqCPRfM7h6yf2liZlLlzuLu2")

here I have to use currentUser instead of filling myself. How to do this?

Upvotes: 0

Views: 3573

Answers (3)

Chichebe
Chichebe

Reputation: 598

Make sure you have firebase_auth imported to your class

Create instances of FirebaseAuth and User like so:

final auth = FirebaseAuth.instance;
User currentUser;

/// Function to get the currently logged in user
  void getCurrentUser() {
      currentUser = auth.currentUser;
      if(currentUser) {
         // User is signed in
      } else {
         // User is not signed in
      }
  }

You can call the getCurrentUser function in the initState of a Stateful Class to get the current as the Widget is loaded like so:

@override
  void initState() {
    getCurrentUser();

    super.initState();
  }

You can now change your previous code to this:

StreamBuilder(
    stream: Firestore.instance
      .collection("customers")
      .document(currentUser.uid)
      .collection("favSalons")
      .snapshots(),
    builder:
      (context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasData && snapshot.connectionState == ConnectionState.active) {
          return Container(
            margin:
                EdgeInsets.only(bottom: screenHeight * 0.33),
            child: new ListView(
              children: getFavSalons(snapshot),
            ),
          );
        }
    return LoadingSalon();
}),

This should work for you now :)

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

The current user in you application can change at any moment. For example:

  • When the user starts the application, Firebase automatically restores their previous authentication state. But this requires it to call out to the server, so the user is briefly not signed in (currentUser is null) before it is signed in.
  • While the user is signed in, Firebase refreshes their authentication state every hour to ensure their sign-in is still valid (and for example their account hasn't been disabled). This means that their sign-in state can change even when you don't explicitly call the API.

For these reasons you can't simply call currentUser and expect it to remain valid. Instead you should attach an auth state change listener, which gives you a stream of authentication states.

In your code that builds the UI, you can use this stream of user data inside another stream builder. So you'll have two nested stream builders:

  1. For the user authentication state.
  2. For the database, based on the current user.

So something like (untested for now):

 StreamBuilder(
     stream: FirebaseAuth.instance.authStateChanges(),
     builder: (context, AsyncSnapshot<User> snapshot) {
        if (snapshot.hasData) {
          return StreamBuilder(
              stream: Firestore.instance
                  .collection("customers")
                  .document(snapshot.data.uid)
                  .collection("favSalons")
                  .snapshots(),
              builder:
                  (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                if (snapshot.hasData) {
                  return Container(
                    margin:
                        EdgeInsets.only(bottom: screenHeight * 0.33),
                    child: new ListView(
                      children: getFavSalons(snapshot),
                    ),
                  );
                }
                return LoadingSalon();
              }),
        }
        return Text("Loading user...");
      }),
         

Upvotes: 1

SLendeR
SLendeR

Reputation: 947

FirebaseUser is currently deprecated, you can get the CurrentUser like shown below;

FirebaseAuth.instance.currentUser;

If you want to know more about what arguments you can use with it check out their documentation;

https://firebase.flutter.dev/docs/auth/usage

Upvotes: 1

Related Questions