I have authenticated into firebase for the futter Web App as well as mobile platform App. but whenever rebuild or re-run the Web App it takes me to the login screen but I have implemented code for the user logged in or not but is not working. it should navigate to home screen.
piece of Code:
class LandingScreen extends StatefulWidget {
@override
_LandingScreenState createState() => _LandingScreenState();
}
class _LandingScreenState extends State<LandingScreen> {
bool isLoggedIn = false;
FirebaseUser _user;
@override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then((user) {
if(user!=null){
print("user:${user.uid}");
setState(() {
_user = user;
isLoggedIn=true;
});
// Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(
// builder: (context)=>HomeScreen(user: user)), (route) => false);
}else{
setState(() {
isLoggedIn = false;
});
// Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(
// builder: (context)=>LoginScreen()), (route) => false);
}
});
}
@override
Widget build(BuildContext context){
return isLoggedIn?HomeScreen(user: _user):LoginScreen();
}
}
Try removing setState. SetState tells the widget to rebuild but InitState runs before the widget is built in the first place so it's not having an effect here. It might not fix the issue though.
Try the following:
@override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then((res) {
print(res);
if (res != null) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Home(user: res)),
);
}
else
{
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
}
});
}
currentUser()
is asynchronous therefore inside the then()
navigate to the different pages according to the result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.