如何从firebase中获取数据

问题描述 投票:1回答:1

我正在构建一个扑动的应用程序并使用cloud-firestore,这就是我的数据库看起来像enter image description here的方式

我想要一个函数来检索一个名为“Driver List”的集合中的所有文档,这些文档在我已经使用过的字符串数组中,但是它会在新的屏幕中将它们返回到listview中

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(),
    );
  },
);

} }

firebase dart flutter google-cloud-firestore
1个回答
2
投票

这有一些额外的逻辑可以删除可能重复的记录,但您可以使用以下内容从Firestore中检索数据。

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

  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

© www.soinside.com 2019 - 2024. All rights reserved.