Nicolas
Nicolas

Reputation: 3

Flutter, Firebase Auth How to access uid everywhere in the app?

it's my first app I try to code.

I am using Firebase Auth and Cloud Firestore in my app. How can I make the uid of the logged-in User available on every screen without using await?

I know I can get it that way:

final FirebaseUser user = await _auth.currentUser();
String id = user.uid;

but I need to access the uid without awaiting it, for example here:

Stream<QuerySnapshot> get groups {
    return Firestore.instance.collection("userGroups")
    .where("userId", isEqualTo: " uid ").snapshots();
}

As I am using the provider package I thought I can make it available through it. But how is the best way to do it? Thank You!

Upvotes: 0

Views: 752

Answers (1)

Nolence
Nolence

Reputation: 2274

You can provide the firebase auth stream above your app:

StreamProvider<FirebaseUser>.value(
  value: FirebaseAuth.instance.onAuthStateChanged,
  lazy: false,
  child: YourApp(),
)

and when want to get the user you can:

final user = Provider.of<FirebaseUser>(context);

Note, this will not listen to changes to the user object beyond signins and sign outs. To listen to actual user changes on the user (such as isVerified or photoUrl changes) you'll want to use a package like firebase_user_stream and replace the previous stream with something like:

StreamProvider<FirebaseUser>.value(
  value: FirebaseUserReloader.onAuthStateChangedOrReloaded.asBroadcastStream(),
  lazy: false,
),

Upvotes: 1

Related Questions