更新时间:2023-09-10 19:32:04
那么您可以使用另一种方法解决此类问题。而是检查您的loginScreen类中是否有用户登录,您可以在此之前执行此步骤,然后决定是否有用户登录时是否显示loginScreen或显示另一个屏幕(我假设是MainScreen)(如果用户已经登录) 。
Well you can solve this kind of problem using another approach. Instead check if there is user logged inside your loginScreen class you can do this a step before and then decide if you will show the loginScreen if there is no user logged or show another screen, MainScreen I' am supposing, if the user is already logged.
我将简要介绍如何完成此操作。希望对您有所帮助。但是在我向您解释源代码中出什么问题之前。
I will put some snipet showing how to accomplish this. I hope it helps. But before I will explain you what is wrong in your source code.
if(FirebaseAuth.instance.currentUser() != null){
// wrong call in wrong place!
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => HomeScreen()
));
}
您的代码已损坏,因为 currentUser()
是一个异步函数,当您进行调用时,此函数将返回一个不完整的Future对象,该对象是一个非null的对象。因此,导航器 pushReplacement
总是被调用,并且由于小部件的状态尚未准备好而崩溃。
Your code is broken because currentUser()
is a async function and when you make the call this function is returning a incomplete Future object which is a non null object. So the navigator pushReplacement
is always been called and it's crashing because the state of your widget is not ready yet.
作为解决方案,您可以使用FutureBuilder并确定要打开的屏幕。
Well as solution you can user FutureBuilder and decide which screen you will open.
int main(){
runApp( YourApp() )
}
class YourApp extends StatelessWidget{
@override
Widget build(BuildContext context){
return FutureBuilder<FirebaseUser>(
future: FirebaseAuth.instance.currentUser(),
builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot){
if (snapshot.hasData){
FirebaseUser user = snapshot.data; // this is your user instance
/// is because there is user already logged
return MainScreen();
}
/// other way there is no user logged.
return LoginScreen();
}
);
}
}
使用这种方法可以避免使用LoginScreen类来验证是否
Using this approach you avoid your LoginScreen class to verify if there is a user logged!
建议您可以将 snapshot.connectionState
属性与切换情况
以实现更精细的控制。
As advise you can make use of snapshot.connectionState
property with a switch case
to implement a more refined control.