【问题标题】:Update ListView.builder itemCount when firestore document is added添加 Firestore 文档时更新 ListView.builder itemCount
【发布时间】:2019-08-23 07:21:14
【问题描述】:

我有一个颤振应用程序,其中使用 ListView.Builder 生成列表,其中 itemCount 是 firestore 集合中的文档数。在添加新文档之前,这可以正常工作。发生这种情况时,我会收到错误消息(17 和 18 只是示例)。

无效值:不在 0..17 范围内,含:18

我假设我需要在创建新文档时更新状态,但我不知道如何在发生这种情况时调用 setState

以下是代码的相关部分:

child: StreamBuilder(
                stream: Firestore.instance.collection('contact').orderBy(sortby, descending: decending).snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) return Container();
                  return ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (context, index) =>
                        _personer(context, snapshot.data.documents[index], index),
                  );
                },
              ),

【问题讨论】:

    标签: flutter dart google-cloud-firestore


    【解决方案1】:

    使用 setState?

     StreamBuilder(builder: (context, snapshot) {
       return snapshot.hasData == null ? Container() : _getListView(snapshot);
     } , )
    
    _getListView(snapshot) {
    setState(() {
      return ListView.builder(
        itemCount: snapshot.data.documents.length,
        itemBuilder: (context, index) =>
            _personer(context, snapshot.data.documents[index], index),
      );
    });
    

    }

    【讨论】:

    • 原来这行不通。 snapshot.data.documents.length 的值确实在我的代码中更新,但 itemCount 出于某种原因没有更新。但是,当我在数据库中进行更改时,列表中的其他所有内容都会发生变化
    【解决方案2】:

    StreamBuilder 使用 QuerySnapshot,所以列表数据可以改变

    示例代码:

     StreamBuilder<QuerySnapshot>(
              builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                if (snapshot.hasError)
                  return new Text('Error: ${snapshot.error}');
                switch (snapshot.connectionState) {
                  case ConnectionState.waiting: return new Text('Loading...');
                  default:
                    return new ListView(
                      children: snapshot.data.documents.map((DocumentSnapshot document) {
                        return ;
                      }).toList(),
                    );
                }
              },
            )
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2022-01-20
      • 2021-04-24
      • 2019-09-01
      • 2022-01-07
      • 2022-01-02
      相关资源
      最近更新 更多