In my Flutter Firebase App with Provider for state management, I have a stream for reacting to FirebaseAuth.instance.authStateChanges()
and a separate stream for listening to the my app related metadata for the logged in uid
provided by FirebaseAuth
.
return MultiProvider(
providers: [
// This returns a stream of firebase user auth events so my app can react to
// login, force logout, etc.
StreamProvider<fireauth.User>.value(
value: FirebaseAuth.instance.authStateChanges(),
),
// conditional on non-null FirebaseAuth User, I would like to register a Firestore listener
// for the provided userId.
// For security purposes, if the authenticated uid changes, the listener should be dereigstered.
// After logout, if a different user is logged in, the this stream should listen to that uid's doc.
StreamProvider<MyUser>.value(
value: FirebaseFirestore.instance.collection('users')
.doc(/* use the userId from firebaseAuth here! */)
.snapshots()
.map((ds) => MyUser.fromJson(ds.data()))
),
],
);
I think I can use ProxyProvider
to allow the MyUser
stream to take a dependency on the FirebaseAuth.User
stream, but once the MyUser
stream is registered for this uid
, it seems to be immutable. How can I "reload" the Firestore stream based on the result from the FirebaseAuth.User
?
Ran into the same problem but with Firebase Realtime Database. Using the async package I created a
StreamGroup
. A StreamGroup.Create StreamGroup:
StreamGroup group = StreamGroup();
Create a stream Variable:
Stream streamvar;
created function with this scheme:
Created an initializer:
where I listened to:
FirebaseAuth.instance.authStateChanges()
and added it to group bygroup.add()
, also set the stream variable and added it to the group:streamvar = functionName(FirebaseAuth.instance.currentUser);
group.add(streamvar)
then created:
Now
streamVar
always holds a reference to the last firestore stream input togroup
. Swap stream from Firestore and you can listen to both kind of changes Firestore and Auth.Incase I missed something: