繁体   English   中英

Flutter和Firestore,处理StreamBuilder中的数据

[英]Flutter and Firestore, handle data from StreamBuilder

我现在正试图编写一个类似于Quiz的应用程序以学习此框架。

我已经实现了Firebase Firestore来管理应用程序数据。 从这个flutter插件文档中,我了解了将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。

结果如下:

主页

现在,如何保存完整的类别模型列表,其中一个实现了“选中/未选中”属性,如何使该列表保持更新?

我尝试在构建器中完全使用“ _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(),因为我实际上在build方法中。

使用地图,您的密钥将为'document.documentID',其值为布尔值。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM