I am trying to create a stream of my user modal based on the authenticate services of fire base.
create user object base on FirebaseUser:
UnicoUser? _userFromFirebaseUser(User? user){
if (user != null) {
UnicoUser? _unicoUser;
DatabaseService(uid: user.uid).getUserFromUserId().then((value){ _unicoUser = value; print("user id: " value.uid);});
return _unicoUser;
}
return null;
}
create the auth change user stream:
Stream<UnicoUser?> get unicoUser {
return _auth.authStateChanges().map(_userFromFirebaseUser);
}
the implement in the widget:
StreamBuilder(
stream: AuthServices().unicoUser,
builder: (context, AsyncSnapshot<UnicoUser?> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting){
return const Loading();}
else if(snapshot.hasData ){
return LoggedInWrapper(currentUser: snapshot.data!,);}
else if (snapshot.hasError){
return const Center(child: Text("Something went wrong"),);}
else {
print("snapshot is: " snapshot.data.toString());return const Authenticate();}
},
)
even if the user is authenticated and the unicouser object is not null the snapshot data is null.. output:
Performing hot reload...
Syncing files to device AOSP on IA Emulator...
Reloaded 0 libraries in 111ms.
I/flutter (22920): snapshot is: null
I/flutter (22920): user id: fnWyLWrCznQDSmZGr6kShpXSsK52
CodePudding user response:
The problem is your _userFromFirebaseUser
function. Unfortunately, you cannot handle async
values this way. The function returns before your _unicouser
is set by then
. You need to use an async
function and await
the result like this:
Future<UnicoUser?> _userFromFirebaseUser(User? user) async {
if (user != null) {
return await DatabaseService(uid: user.uid).getUserFromUserId();
}
return null;
}
Then you should be able to use it like this:
Stream<UnicoUser?> get unicoUser {
return _auth.authStateChanges().asyncMap(_userFromFirebaseUser);
}