如何在flutter中从firebase获取数据 [英] how to get data from firebase in flutter

查看:43
本文介绍了如何在flutter中从firebase获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Flutter 应用程序并使用 cloud-firestore,这就是我的数据库的样子

I am building a flutter app and using cloud-firestore, this is how my database looks like

我想要一个函数,它在一个字符串数组中检索名为Driver List"的集合中的所有文档那是我已经使用过的,但它使它们返回到新屏幕的列表视图中

I want a function that retrieves all documents in the collection called "Driver List" in an array of strings that what I had already used but it gets them back in a listview in a new screen

class DriverList extends StatelessWidget {@overrideWidget build(BuildContext context) {
return new StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('DriverList').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return new Text('Loading...');
    return new ListView(
      children: snapshot.data.documents.map((DocumentSnapshot document) {
        return new ListTile(
          title: new Text(document['name']),
          subtitle: new Text(document['phone']),
        );
      }).toList(),
    );
  },
);

}}

推荐答案

这有一些额外的逻辑来删除潜在的重复记录,但您可以使用类似以下内容从 Firestore 检索数据.

This has some additional logic to remove potentially duplicate records, but you can use something like the following to retrieve data from Firestore.

我们可以访问集合引用,然后列出查询结果,然后为 Firestore 返回的数据创建本地模型对象,然后返回这些模型对象的列表.

We get access to a collection reference, then list the results of the query, then create local model objects for the data returned by Firestore, and then we return the a list of those model objects.

  static Future<List<AustinFeedsMeEvent>> _getEventsFromFirestore() async {
CollectionReference ref = Firestore.instance.collection('events');
QuerySnapshot eventsQuery = await ref
    .where("time", isGreaterThan: new DateTime.now().millisecondsSinceEpoch)
    .where("food", isEqualTo: true)
    .getDocuments();

HashMap<String, AustinFeedsMeEvent> eventsHashMap = new HashMap<String, AustinFeedsMeEvent>();

eventsQuery.documents.forEach((document) {
  eventsHashMap.putIfAbsent(document['id'], () => new AustinFeedsMeEvent(
      name: document['name'],
      time: document['time'],
      description: document['description'],
      url: document['event_url'],
      photoUrl: _getEventPhotoUrl(document['group']),
      latLng: _getLatLng(document)));
});

return eventsHashMap.values.toList();
}

来源:https://github.com/dazza5000/austin-feeds-me-flutter/blob/master/lib/data/events_repository.dart#L33

这篇关于如何在flutter中从firebase获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆