我如何关闭数据重新加载从firebase而使用FlutterFire_ui?



我正在使用google的flutter fire ui库,在大多数情况下它工作得很好,唯一的问题是似乎无论如何都没有列出以阻止快照在数据更改时刷新。

这是我的查询:

final restaurantsQuery =
FirebaseFirestore.instance.collection('restaurants').orderBy('name');

,下面是代码:

class RestrauntSliver extends StatelessWidget {
const RestrauntSliver({
Key? key,
required this.restaurantsQuery,
}) : super(key: key);
final Query<Map<String, dynamic>> restaurantsQuery;
@override
Widget build(BuildContext context) {
return FirestoreQueryBuilder<Map<String, dynamic>>(
query: restaurantsQuery,
builder: (context, snapshot, _) {
if (snapshot.isFetching) {
return SliverToBoxAdapter(child: const CircularProgressIndicator());
}
if (snapshot.hasError) {
return Text('Something went wrong! ${snapshot.error}');
}
// ...
return SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
// obtain more items
if (snapshot.hasMore && index + 1 == snapshot.docs.length) {
// Tell FirestoreQueryBuilder to try to obtain more items.
// It is safe to call this function from within the build method.
snapshot.fetchMore();
}
final restaurant = snapshot.docs[index].data();
final restaurantId = snapshot.docs[index].id;
// print(restaurant);
return RestaurantItem(
restaurant: restaurant,
id: restaurantId,
);
},
childCount: snapshot.docs.length,
),
);
},
);
}
}

如果小部件被销毁,FirestoreQueryBuilder将自动取消订阅实时侦听器。

如果您需要更多的控制何时取消,暂停或恢复侦听器,我建议使用StreamSubscription代替。

你可以通过调用它的cancel()方法来取消你的StreamSubscription(即你对从流接收任何更多的数据更新不感兴趣)。文档中的示例代码,调整为按字母顺序查询前10个城市:

final query = db.collection("cities").orderBy("name").limit(10);
final listener = query.snapshots().listen((event) {
// ...
});
listener.cancel();

链接到文档的相关部分:https://firebase.google.com/docs/firestore/query-data/listen?hl=en

相关内容

最新更新