【问题标题】:The getter 'length' was called on null. The relevant error-causing widget was StreamBuilder<List<DocumentSnapshot<Object?>>>在 null 上调用了 getter \'length\'。相关的导致错误的小部件是 StreamBuilder<List<DocumentSnapshot<Object?>>>
【发布时间】:2022-11-14 05:41:07
【问题描述】:

我学习 Flutter 已经有一段时间了,试图从现有的 Flutter 项目中理解,所以后面的代码不是我的。

目前我正在测试一个项目,但我面临一个我从未见过的错误。

The getter 'length' was called on null.
Receiver: null
Tried calling: length

我认为它来自这部分代码。

StreamBuilder<List<DocumentSnapshot>>(
                    stream: postListBloc.postStream,
                    builder: (context, snapshot) {
                      if (snapshot.connectionState == ConnectionState.waiting)
                        return Center(
                          child: CircularProgressIndicator(),
                        );
                      else {
                        int presentLength = snapshot.data.length;
                        return ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            itemCount: snapshot.data.length,
                            itemBuilder: (context, index) {
                              DocumentSnapshot documentSnapshot =
                                  snapshot.data[index];
                              String id = documentSnapshot.id;
                              debugPrint('${snapshot.data.length}');
                              return Column(children: [
                                Padding(
                                    padding: EdgeInsets.only(bottom: 10),
                                    child: PostCardView(
                                        documentSnapshot.get('community'),
                                        id,
                                        true)),
                                (index != snapshot.data.length - 1)
                                    ? Container()
                                    : buildProgressIndicator(presentLength)
                              ]);
                            });
                      }
                    },
                  ),

我在这里搜索了不同的解决方案,但到目前为止没有任何效果。

如果有人知道如何解决这个问题。

【问题讨论】:

  • 试试else if(snapshot.hasData){ int presentLength = snapshot.data.length;

标签: flutter


【解决方案1】:

基本上错误说您的快照中没有数据。数据为空,如果它为空,则首先检查它是否不为空,如果它不为空,则显示没有可用数据显示数据

【讨论】:

    【解决方案2】:

    您可以通过两种方式做到这一点:

    1-将流构建器中的初始数据设置为一个空列表,如下所示:

    initialData : []
    

    2-另一种方法是检查快照是否有数据:

    snapshot.hasData
    

    【讨论】:

      【解决方案3】:

      这就是所谓的零安全既然你说的语言你试图从现有的 Flutter 项目中理解,问题是这个项目是内置在flutter版本中的,不支持零安全. 将flutter版本降级为项目版本。 我建议您了解 null 安全性,因为它非常重要。

      【讨论】:

        猜你喜欢
        • 2021-11-16
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        • 2021-07-21
        • 2021-08-11
        • 2021-02-23
        相关资源
        最近更新 更多