I'm trying to build a funtion who return Widget for persiting state but I am getting this error.
Future<Widget?> persiting () async {
await FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
return SignUpScreen() ;
} else {
return HomeScreen() ;
}
});
}
CodePudding user response:
try this:
Future<Widget?> persiting () async {
late bool hasUsers;
await FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user == null) {
hasUsers = true;
} else {
hasUsers = false;
}
});
return hasUsers ? SignUpScreen() : HomeScreen();
}
CodePudding user response:
The exception showed because you are returning onject to the .listen()
function instead of the persiting()
function.
What you need to do is await to listen the stream inside the presiting()
function.
Future<Widget?> persiting () async {
try{
Stream<User?> stream = await FirebaseAuth.instance
.authStateChanges();
bool hasUser = false;
await stream.forEach((user){
hasUser = user != null;
});
return hasUser? HomeScreen() : SignUpScreen();
}catch(e){
/// better do some handling if any network or unexpected error here
}
}