Flutter / Firebase_Auth:生成函数返回null

时间:2020-04-24 20:21:34

标签: firebase flutter dart firebase-authentication

当我尝试运行该应用程序时,它引发错误: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();
      }
    });

  }
}

3 个答案:

答案 0 :(得分:1)

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

class Data{ 
  $service_id; 
  $service_name; 
} 

$obj = new Array(); 
while ($row2 = mysqli_fetch_assoc($check2)){ 
  $data = new Data(); 
  $data->service_id = $row2['service_id']; 
  $data->service_name = $row2['service_name']; 
  array_push($obj, $data); 
} 
echo json_encode($obj);

我通常更喜欢这样写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

答案 1 :(得分:0)

由于onAuthStateChanged返回流,因此您可以使用流生成器并使Wrapper小部件成为StatelessWidget。

class Wrapper extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.active) {
          return Center(child: CircularProgressIndicator());
        }
        final user = snapshot.data;
        if (user != null) {
          print("user is logged in");
          return HomeScreen();
        } else {
          print("user is not logged in");
          return LoginScreen();
        }
      },
    );
  }
}

答案 2 :(得分:0)

可能用户已更改,但您没有看到它,因为:

仅当您使用SetState()时,才会调用

“ build”方法

这意味着:“刷新小部件”


SetState在这里有很好的解释: Flutter Tutorial for Beginners #16 - Stateful Widgets

对于FirebaseAuth,我发现本课程很有用 Flutter & Firebase App Build