【问题标题】:Flutter and Firestore, handle data from StreamBuilderFlutter 和 Firestore,处理来自 StreamBuilder 的数据
【发布时间】:2019-04-09 01:02:18
【问题描述】:

我现在正在尝试在 Flutter 中制作一个类似测验的应用程序来学习这个框架。

我已实施 Firebase Firestore 来管理应用数据。 从这个flutter plugin 文档中,我读到了关于将 CollectionReference 绑定到 ListView 的内容,这很容易。

我的问题如下。 我有一些类别要显示在主页中,我希望用户能够选择他想要的类别,然后将这些信息存储在列表中。

使用此代码,我可以显示列表:

@override


Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('Categorie').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return new Center(
              child: Column(
                children: <Widget>[
                  SizedBox(
                    child: CircularProgressIndicator(),
                    height: 50.0,
                    width: 50.0,
                  ),
                  Text('Dowload delle categorie...')
                ],
              ),
            );
          default:
            _loadListOfCategories(snapshot);
            return new ListView(
              children:
                  snapshot.data.documents.map((DocumentSnapshot document) {
                var nome = document['Nome'];
                print('doc: $nome');
                return new CategoryWidget(
                  id: document.documentID,
                  tap: onCategoryTap,
                  nome: document['Nome'],
                  count: document['Count'],
                  checked: false,
                );
              }).toList(),
            );
        }
      },
    );
  }

CategoryWidget 只是一个简单的无状态小部件,它充当 ListTile。

结果如下:

现在,我如何保存一个包含 Category 模型的列表,其中一个实现了“已选中/未选中”属性,以及如何使该列表保持更新?

我尝试在构建器中完全使用“_loadListOfCategories()”方法:

  void _loadListOfCategories(AsyncSnapshot<QuerySnapshot> snapshot) {
    var temporalList = new List<CategoryModel>();
    for (DocumentSnapshot doc in snapshot.data.documents) {
      temporalList.add(new CategoryModel(
          id: doc.documentID,
          count: doc['Count'],
          nome: doc['Nome']));
    }
    setState(() {
      _listOfCategories = temporalList;
    });
  }

但我不能在这里调用 setState(),因为我实际上是在构建方法中。

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    使用地图,您的键是“document.documentID”,值是布尔值。

    Map map = Map() // 假设这是一个字符串 document.documentID

    检查:map.get(document.documentID), 在您调用的复选框中 设置状态()=> map.put(document.documentID, !map.get(document.documentID));

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 1970-01-01
      • 2021-07-26
      • 2022-11-17
      • 2021-02-07
      • 2020-05-28
      • 2020-06-07
      • 2019-10-28
      • 2020-07-30
      相关资源
      最近更新 更多