Reputation: 21
I have a firestore database with a 'users' collection, the document ids are the user's account uid. The documents contain information like: name, email, and address. currently I have a stream provider that streams the user's document but when I logout and login to a different account, the document information is still the previous user's document.
class that my streamprovider uses to create the stream.
class UserModel {
final FirebaseFirestore _db = FirebaseFirestore.instance;
final FirebaseAuth _auth = FirebaseAuth.instance;
//Stream the current user's information.
Stream<Map<String, dynamic>> getCurrentUserMap() {
User? currUser = _auth.currentUser;
return _db
.collection('users')
.doc(currUser!.uid)
.snapshots()
.map((docSnap) {
return docSnap.data()!;
});
}
}
For example, I will login to [email protected] and it will grab bigfella's document as a map and I will print it out to the console. Then I will logout and login with [email protected], but it will still print out bigfella's document. I made a manual change to bigfella's document on firestore and my code reacts to that. So my problem is idk how to make the stream change to listen to the new user's document after they login.
StreamProvider<Map<String, dynamic>>(
create: (context) => UserModel().getCurrentUserMap(),
initialData: const {},
),
I tried reading the documentation and saw that authStateChanges, idTokenChanges and userChanges streams would return the current user to their listeners and I tried using authStateChanges as such:
Stream<Map<String, dynamic>> getCurrentUserMap() {
Stream<User?> currUserStream =
_auth.authStateChanges().map((user) => (user != null) ? user : null);
User? currUser;
StreamSubscription<User?> currUserSub = currUserStream.listen((event) {
User? currUser = event;
});
return _db
.collection('users')
.doc(currUser!.uid)
.snapshots()
.map((docSnap) {
return docSnap.data()!;
});
}
considering it didn't work and I wasn't really sure what I was doing, I probably did it wrong.
I was also thinking maybe after the provider creates the stream, thats it? it cant change that stream to a different one? im not sure.
Any tips would be helpful.
I attempted to try using another streamprovider with authstatechanges to stream the currentuser to the function that will return a stream of the current user's document, but I didn't have a context in that class to listen to.
I attempted to use authStateChanges/userChanges directly in the class as shown in the last picture above. I probably did it wrong and my approach to solving this problem may be wrong as well?
I was expecting the stream to change the streamed document whenever someone new logged in.
Upvotes: 2
Views: 895
Reputation: 682
As you can see from your code,
return _db
.collection('users')
.doc(currUser!.uid)
.snapshots()
you are particularly listening to the doc with uid
.
You need to close the existing listening stream and then start listen with new user's uid
.
Upvotes: 0