【发布时间】:2021-05-11 11:41:32
【问题描述】:
我正在使用 Flutter 设计一个应用,并使用 Firestore 作为我的数据库。
我有这个页面,它基本上从 Firestore 中的特定集合中获取所有内容并为用户列出。
我还不太熟悉 Firestore 方面的工作原理,并希望尽可能对其进行优化,以避免不必要的数据库读取。在这种情况下我的问题是:每次用户打开此屏幕时,Firestore 会在此集合中执行读取吗?还是仅当此集合中的某些内容发生更改时?
假设用户打开了这个列表,然后转到他的个人资料,然后又回到了这个列表。如果同时集合没有任何变化,那么数据库中会有 1 次还是 2 次读取?
我需要使用 Stream 来实现吗?
这个列表在 Flutter 中的实现
FutureBuilder<List<Store>>(
future: DatabaseService().storeList,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Loading();
} else {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (context, index) => StoreTile(store: snapshot.data[index]),
itemCount: snapshot.data.length,
);
}
},
);
数据库东西的实现
class DatabaseService {
// Collection reference
final CollectionReference storeCollection = FirebaseFirestore.instance.collection('stores');
// Make a store list from snapshot object
List<Store> storeListfromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc){
return Store(
name: doc.data()['name'] ?? '',
description: doc.data()['description'] ?? '',
image: doc.data()['image'] ?? ''
);
}).toList();
}
// Get instantaneous stores list
Future<List<Store>> get storeList async {
return storeListfromSnapshot(await storeCollection.get());
}
}
【问题讨论】:
标签: firebase flutter google-cloud-firestore