Flutter / Firebase_Auth:生成函数返回null [英] Flutter/Firebase_Auth: a build function returned null

查看:91
本文介绍了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();
}

这篇关于Flutter / Firebase_Auth:生成函数返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆