Flutter / Firebase_Auth:生成函数返回null
问题描述:
当我尝试运行该应用程序时,它会引发错误:一个构建函数返回null
并崩溃。这是已镶嵌的小部件。它怎么可能返回null?以及我该如何解决?
When i try to run the app it throws an error: A build function returned null
and crashes. Here is the insterested widget. How is it possible that it returns null ? and how can i fix it ?
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();
}
});
}
}
答
如果您的渲染输出取决于异步加载的内容(例如身份验证状态),应将其存储在对象的状态中:
If your render output depends on something that is loaded asynchronously (such as the authentication state), you should store that in the state of the object:
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
:
I typically prefer writing the build
like this:
@override
Widget build(BuildContext context) {
return (user != null) ? HomeScreen() : LoginScreen();
}