Flutter - non-null 值必须 returned 因为 return 类型 'Widget' 不允许 null

Flutter - A non-null value must be returned since the return type 'Widget' doesn't allow null

我尝试 运行 这段代码,但它给了我标题中提供的错误,它还说(body 可能正常完成,导致 'null' 是 returned,但 return 类型 'Widget' 可能是 non-nullable 类型。),将不胜感激解决此问题的任何帮助!

    Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance.collection("chats").snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
        if(snapshot.hasError) {
          return Center (
            child: Text("There is a problem"),
          );
        }

        if(snapshot.connectionState == ConnectionState.waiting) {
          return Center (
            child: Text("Loading"),
          );
        }

        if(snapshot.hasData) {
          return CustomScrollView(
            slivers: [
              CupertinoSliverNavigationBar(
                largeTitle: Text("Chats"),
              ),

              SliverList(
                delegate: (
                    SliverChildListDelegate(
                      snapshot.data!.docs.map((DocumentSnapshot document) {
                        Map<String, dynamic> data = document.data()!as Map<String, dynamic>;
                        return CupertinoListTile(title: Text(data['title']),
                        );
                      }).toList())))
            ],
          );
      }
  });
  }

您需要在 if(snapshot.hasData) 之后 return 一个小部件。我想您可以简单地删除 if(snapshot.hasData) 并且您的代码就可以了。但为了保证,您可以在之后 return 一个错误小部件。

您正在通过检查条件重新调整小部件的构建器,这是一个很好的做法。您可以 return 最后添加一个默认小部件。另外,您可以使用其他状态。编辑器显示的错误是因为它认为我们可能会面临其他状态,而这可能不符合论文 if。它需要一个带有或不带有 else 条件的默认 return 小部件。

builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
 
if(...)

if(...)


else return Text(...); // with or without else condition it will retrun by default. 
}