我已经实现了逻辑,但是当侦听器在仅更新一个文档或添加或删除它后触发时,整个文档都会获取给我,但他们有什么方法可以仅获取更新的文档。
class OfferProvider with ChangeNotifier {
final OffersService _offerService = OffersService();
List<Offer> _offers = [];
List<Offer> get offers => _offers;
OfferProvider() {
_listenToOffers();
}
void _listenToOffers() {
_offerService.getOffers().listen((offersData) {
_offers = offersData;
notifyListeners();
});
}
}
class OffersService {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
/// Retrieves a stream of offers from the Firestore database.
///
/// Returns a stream of lists of `Offer` objects, where each list represents a snapshot of the 'offers' collection.
///
/// The stream is updated in real-time as the data in the Firestore database changes.
Stream<List<Offer>> getOffers() {
return _firestore.collection('offers').snapshots().map((snapshot) {
return snapshot.docs.map((doc) => Offer.fromFirestore(doc)).toList();
});
}
}
提前致谢
我尝试添加以下代码并获取更新的快照,但使用从 firestore 收到的数据,所有文档都会再次获取:
void _listenToOffers() {
_offerService.getOffers().listen((snapshot) {
for (var change in snapshot.docChanges) {
switch (change.type) {
case DocumentChangeType.added:
// Handle added documents
_offers.add(Offer.fromFirestore(change.doc));
break;
case DocumentChangeType.modified:
// Handle modified documents
int index =
_offers.indexWhere((offer) => offer.id == change.doc.id);
if (index != -1) {
_offers[index] = Offer.fromFirestore(change.doc);
}
break;
case DocumentChangeType.removed:
// Handle removed documents
_offers.removeWhere((offer) => offer.id == change.doc.id);
break;
}
}
notifyListeners();
});
}
class OfferService {
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
Stream<QuerySnapshot> getOffers() {
return _firestore
.collection('offers')
.where('activated', isEqualTo: true)
.snapshots();
}
}
整个文档都给我了
...
所有文档都用它再次获取
Firestore客户端实际上只从数据库服务器获取修改后的文档。但 API 会生成包含已修改和未修改文档的查询快照。如果您想区分它们,查看
docChanges
数组中的更改类型(正如 Doug 评论的那样)。