Reputation: 95
Im trying to get the User Id of the current user signed in. This is how I;m trying to get the UserID as String, where the functions are printing the $userId and also $uid.
String userId;
Future<String> getUser() async {
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
final String uid = user.uid.toString();
print("uid in getuser function $uid");
userId = uid;
return uid;
}
And this is the Stream in which im trying to get the UserID(uid) into (both the Futures and Stream are in the same class)(the return statement in the Stream can be ignored)
// get hotel stream
Stream<List<Hotel>> get userHotels {
print("This is the uid ${getUser().toString()} in Stream");
return ownerCollection.document(uid).collection("hotels").snapshots()
.map(_hotelListFromSnapshot);
}
Printing $getUser().toString() gives this in the console : "This is the uid Instance of 'Future' in Stream" and not printing the actual UserID.
And printing $userId gives this in the console : " This is the uid null in Stream"
Please help, I want to get the UserId of the current user signed in the Stream
Upvotes: 2
Views: 3973
Reputation: 14435
As defined above getUser()
returns a Future<String>
. So toString()
on that will return Instance of 'Future'
.
What you probably want to do is wait for getUser()
to finish first.
You can do that by using async generators, with async*
and yield*
.
// get hotel stream
Stream<List<Hotel>> get userHotels async* {
final uid = await getUser();
print("This is the uid $uid in Stream");
yield* ownerCollection.document(uid).collection("hotels").snapshots()
.map(_hotelListFromSnapshot);
}
Using async*
means you'll return a Stream
. Then after waiting for getUser()
to finish, you can put values on that stream with yield
. yield*
specifically means you are putting the values of another Stream
on the one you are returning.
Upvotes: 2
Reputation: 1
Your function getUser()
will work the the same as the FirebaseAuth.instance.currentUser()
function you are using, and will return a future. If you want to print it, you need to either use await
as you did before, or the then
function.
When it comes to using it in your function, you need to use the result of the future to create the stream. Take a look at this answer for how to do that.
Upvotes: 0