Issue
The code for the model class is as shown below:
class UserAuthModel {
String? uid;
String? email;
String? displayName;
String? profilePic;
UserAuthModel(this.uid, this.email, this.displayName, this.profilePic);
UserAuthModel.fromFirebaseUser({User? user}) {
this.uid = user!.uid;
this.email = user.email;
this.displayName = user.displayName;
this.profilePic = user.photoURL;
}
}
The code for the service class is shown below:
class AuthService {
final FirebaseAuth authInstance = FirebaseAuth.instance;
final FirebaseFirestore firestoreInstance = FirebaseFirestore.instance;
Stream<UserAuthModel?> get currentUser => authInstance.authStateChanges().map(
(User? firebaseUser) => (firebaseUser != null) ? UserAuthModel.fromFirebaseUser(user: firebaseUser) : null,
);
}
The provider is defined as shown below:
return MultiProvider(
providers: [
Provider<AuthService>(
create: (_) => AuthService(),
),
],
This is how I’m trying to consume the provider within the code:
final authService = Provider.of<AuthService>(context);
final loggedInUser = authService.currentUser;
But when I try to access the user details using the currentUser
as shown below, I’m unable to do so, not sure why?
print(loggedInUser.uid);
print(loggedInUser.email);
print(loggedInUser.displayName);
print(loggedInUser.profilePic);
How can I access these details?
I don’t see either the uid, email, displayName or profilePic
to select as shown in the pic below:
Solution
The properties you are looking for are defined on UserAuthModel
. But your loggedInUser
is declared as this as far as I can see:
Stream<UserAuthModel?> get currentUser
So the properties you can read from loggedInUser
are properties of Stream
and not of UserAuthModel
.
Reading the user model once
To get the properties of the actual UserAuthModel
, you can use the methods of the Stream
. For example you can await the first UserAuthModel
with:
var user = await loggedInUser.first
print(user.uid);
Listening/observing the user model
You can also listen for changes to the logged in user, so that you don’t just get their initial state, but also any changes with:
loggedInUser.listen((user) {
print(user.uid);
}
Showing the user model in your UI
And if you want to use the user in your UI, you’ll typically wrap it in a StreamBuilder
, which then handles the asynchronous behavior of the stream for you and gives you a UserAuthModel
to work with.
I highly recommend reading the Flutter documentation on asynchronous programming and on StreamBuilder
to learn more about these concepts, as they’re fundamental to working with cloud-hosted data in Flutter.
Answered By – Frank van Puffelen
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0