[英]How to keep user signed in Flutter Firebase app?
I am creating a chat app that uses Firebase for the backend.我正在创建一个使用 Firebase 作为后端的聊天应用程序。 Whenever I restart the app, it goes to the welcome screen where users have to login/register, every single time.
每当我重新启动应用程序时,它都会进入欢迎屏幕,用户必须每次登录/注册。 If you log in, then close the app without logging out, it still goes back to the login screen.
如果您登录,然后在不注销的情况下关闭应用程序,它仍会返回登录屏幕。 I have added a method in the main method to check:
我在 main 方法中添加了一个方法来检查:
void getCurrentUser() async {
FirebaseAuth.instance.onAuthStateChanged.listen((firebaseUser) {
print(firebaseUser);
_user = firebaseUser;
});
}
So, if _user is null, then go to welcome page, otherwise go straight into the chat screen of the app:因此,如果 _user 是 null,则 go 到欢迎页面,否则 go 直接进入应用程序的聊天屏幕:
Widget build(BuildContext context) {
getCurrentUser();
return MaterialApp(
initialRoute: _user == null ? '/' : '/chat',
routes: {
'/': (context) => WelcomeScreen(),
'/login': (context) => LoginScreen(),
'/registration': (context) => RegistrationScreen(),
'/chat': (context) => ChatScreen(),
},
);
}
Why doesn't it work?为什么它不起作用? I have Googled this problem for a while and earlier I was using auth.currentUser(), which could have been the problem, but now I'm using a listener and it still doesn't work.
我已经用谷歌搜索了这个问题一段时间,之前我使用的是 auth.currentUser(),这可能是问题所在,但现在我使用了一个监听器,但它仍然不起作用。
var user await FirebaseAuth.instance.currentUser();
if (user != null) {
Navigator.of(context).pushNamed("routeName");
}
Wrap the above code in an async function that takes BuildContext and call in the build method before the return statement.将上面的代码包装在一个异步 function 中,它接受 BuildContext 并在 return 语句之前调用 build 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.