Ahm*_*yed 8 dart firebase flutter google-cloud-firestore
我正在构建一个 flutter 应用程序并使用 cloud-firestore,这就是我的数据库的样子

我想要一个函数,它在一个字符串数组中检索名为“驱动程序列表”的集合中的所有文档,这些文档是我已经使用过的,但它会将它们返回到新屏幕的列表视图中
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(),
);
},
);
Run Code Online (Sandbox Code Playgroud)
} }
这有一些额外的逻辑来删除潜在的重复记录,但您可以使用类似以下内容从 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();
}
Run Code Online (Sandbox Code Playgroud)
来源:https : //github.com/dazza5000/austin-feeds-me-flutter/blob/master/lib/data/events_repository.dart#L33
获取一次性数据:
var collection = FirebaseFirestore.instance.collection('DriverList');
var querySnapshot = await collection.get();
for (var queryDocumentSnapshot in querySnapshot.docs) {
Map<String, dynamic> data = queryDocumentSnapshot.data();
var name = data['name'];
var phone = data['phone'];
}
Run Code Online (Sandbox Code Playgroud)
每次更改时获取数据,使用StreamBuilder:
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance.collection('DriverList').snapshots(),
builder: (_, snapshot) {
if (snapshot.hasError) return Text('Error = ${snapshot.error}');
if (snapshot.hasData) {
final docs = snapshot.data!.docs;
return ListView.builder(
itemCount: docs.length,
itemBuilder: (_, i) {
final data = docs[i].data();
return ListTile(
title: Text(data['name']),
subtitle: Text(data['phone']),
);
},
);
}
return Center(child: CircularProgressIndicator());
},
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31444 次 |
| 最近记录: |