【问题标题】:How to store data of collection from firestore into a list?如何将来自firestore的收集数据存储到列表中?
【发布时间】:2020-05-01 17:23:12
【问题描述】:

我希望将从 firestore 获取的数据存储到一个列表中,该列表将包含来自其所有文档的数据。

我将列表定义为:

List retrievedData = List();

接下来,按下按钮时,我想打印特定集合的所有文档中的数据。所以,我这样做了:

RaisedButton(
        onPressed: () async {

          var collectionReferece = await Firestore.instance.collection('insults');
          collectionReferece.getDocuments().then((collectionSnapshot){
            retrievedData = collectionSnapshot.documents.toList();
          });

          print(retrievedData);
        },

我在控制台中期待这个:

I/flutter (11351): [{index: 200, title: This is a test 1},{index: 100, title: This is a test 2}]

但我明白了:

I/flutter (11351): [Instance of 'DocumentSnapshot', Instance of 'DocumentSnapshot']

另外,我只想将此数据存储在列表或任何其他变量中。帮帮我。谢谢。

编辑:

我尝试使用forEach,但每次按下按钮都会不断添加。

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    如果你想:

    1. 从 Firestore 中检索数据
    2. 添加到列表
    3. 创建 listview.builder

    然后你可以做如下,首先在你的State类下声明如下变量:

    class _MyHomePageState extends State<MyHomePage> {
      bool isFirstTime = false;
      List<DocumentSnapshot> datas = List<DocumentSnapshot>();
    

    接下来,创建一个名为getData() 的方法,该方法将在onPressed 中引用:

          floatingActionButton: FloatingActionButton(
            onPressed: getData,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ), 
    
      getData() async {
        if (!isFirstTime) {
          QuerySnapshot snap =
              await Firestore.instance.collection("insults").getDocuments();
          isFirstTime = true;
          setState(() {
            datas.addAll(snap.documents);
          });
        }
      }
    

    点击FAB,您将获得insults 集合中的数据。我们使用布尔值每次点击只检索一次。在您覆盖的方法 dispose 内部:

      @override
      void dispose() {
        super.dispose();
        this.isFirstTime = false;
      }
    }
    

    您可以再次将isFirstTime 分配给false。然后显示数据,您可以使用AppBar 的属性body,将其分配给Center 小部件,Center 小部件将包含listview

          body: Center(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: ListView.builder(
              itemCount: datas.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text('${datas[index]["index"]}'),
                  subtitle: Text('${datas[index]["title"]}'),
                );
              },
            ),
    

    使用listview.builder,您将在屏幕中显示一个列表,而您不必使用forEach 来迭代列表。您只需使用get 运算符[] 即可获取列表中的数据。

    【讨论】:

      【解决方案2】:

      任何需要从 Firestore 访问数据的代码都需要在 then 中。所以:

        var collectionReferece = await Firestore.instance.collection('insults');
        collectionReferece.getDocuments().then((collectionSnapshot){
          retrievedData = collectionSnapshot.documents.toList();
          print(retrievedData);
        });
      

      但您通常希望将数据加载与 build() 方法分开,并使用 state 或 FutureBuilder 将数据从数据库获取到呈现的输出中。一些例子:

      【讨论】:

      • 你也可以争辩说,既然方法已经定义为async,那为什么还要在这里使用then()方法而不是await来自getDocuments()的结果并设置结果从这个到retrievedData变量。
      • @julemand101 实际上我不确定您是否可以在build() 中使用异步属性/方法。 stackoverflow.com/questions/53800662/…
      【解决方案3】:

      我认为这是因为 .toList() 方法将这 2 个文档的数据类型与列表中的“DocumentSnapshot”相同。尝试打印以确保。

      print(retrievedData[0]['title']);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 2017-06-27
        • 1970-01-01
        • 1970-01-01
        • 2021-06-30
        • 2018-06-11
        • 1970-01-01
        相关资源
        最近更新 更多