gpt4 book ai didi

firebase - Flutter/Firebase_Auth:生成函数返回null

转载 作者:行者123 更新时间:2023-12-03 03:35:20 25 4
gpt4 key购买 nike

当我尝试运行该应用程序时,它将引发错误:A build function returned null并崩溃。这是已镶嵌的小部件。它怎么可能返回null?我该如何解决?

class Wrapper extends StatefulWidget {
@override
_WrapperState createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {

@override
Widget build(BuildContext context) {
var auth = FirebaseAuth.instance;
auth.onAuthStateChanged.listen((user) {
if (user != null) {
print("user is logged in");
return HomeScreen();

} else {
print("user is not logged in");
return LoginScreen();
}
});

}
}

最佳答案

如果渲染输出依赖于异步加载的内容(例如身份验证状态),则应将其存储在对象的状态中:

class _WrapperState extends State<Wrapper> {

public _WrapperState() {
FirebaseAuth.instance.onAuthStateChanged.listen((user) {
setState(() {
this.user = user
});
}

@override
Widget build(BuildContext context) {
if (user != null) {
return HomeScreen();
} else {
return LoginScreen();
}
}
}

我通常更喜欢这样编写 build:
@override
Widget build(BuildContext context) {
return (user != null) ? HomeScreen() : LoginScreen();
}

关于firebase - Flutter/Firebase_Auth:生成函数返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com