简体   繁体   English

Flutter Firebase:使用流生成器时如何删除Firebase侦听器?

[英]Flutter Firebase: How to remove firebase listener when using stream builder?

Every example about StreamBuilder starts with a StatelessWidget even in flutter example but how do you cancel the subscription in a StatelessWidget widget? 大约每例如StreamBuilder有开始StatelessWidget即使在flutter的例子,但你怎么取消在订阅StatelessWidget小部件? For example, I was going through firestore example . 例如,我正在研究firestore 示例

class MessageList extends StatelessWidget {
 MessageList({this.firestore});

 final Firestore firestore;

 @override
 Widget build(BuildContext context) {
 return StreamBuilder<QuerySnapshot>(
  stream: firestore.collection('messages').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return const Text('Loading...');
    final int messageCount = snapshot.data.documents.length;
    return ListView.builder(
      itemCount: messageCount,
      itemBuilder: (_, int index) {
        final DocumentSnapshot document = snapshot.data.documents[index];
        return ListTile(
          title: Text(document['message'] ?? '<No message retrieved>'),
          subtitle: Text('Message ${index + 1} of $messageCount'),
        );
      },
    );
  },
 );
 }
}

Now how do I cancel listening to firestore.collection('messages').snapshots() stream? 现在如何取消收听firestore.collection('messages').snapshots()流?

I use realtime database in my app and this is how I do it 我在应用程序中使用实时数据库,这就是我的方法

class MessgaeView extends StatefulWidget {
 final String _chatId;
 MessgaeView(this._chatId);

 @override
 _MessgaeViewState createState() => _MessgaeViewState();
}

class _MessgaeViewState extends State<MessgaeView> {
 Stream<Event> _messageStream;
 @override
 void initState() {
  _messageStream = _database
    .reference()
    .child("message/${widget._chatId}")
    .limitToLast(1)
    .onChildAdded;
  super.initState();
 }

 @override
 void dispose() {
  _messageStream.drain();
  super.dispose();
 }
@override
Widget build(BuildContext context) {
return StreamBuilder(
    stream: _messageStream,
    builder: (context, snapshot) {
      if (!snapshot.hasData) return CupertinoActivityIndicator();
      final message =
          (snapshot.data.snapshot as DataSnapshot).value['message'];
      return Text(message);
    });
 }
}

Simply replace the previous stream instance with null . 只需将前一个流实例替换为null

This will require a code similar to the following somewhere: 这将需要类似于以下内容的代码:

setState(() {
  _messageStream = null;
});

Doing so will stop listening to the stream. 这样做将停止收听流。 But StreamBuilder will still hold the previous value. 但是StreamBuilder仍将保留以前的值。

I hava same problem and solved by StreamSubscription 我遇到了同样的问题,并通过StreamSubscription解决了

For example define StreamSubscription as global 例如,将StreamSubscription定义为全局

StreamSubscription<Event> _counterSubscription;

then in your place you want to listen to data register your Subscription like this 然后在您要收听的地方,像这样注册您的订阅

_counterSubscription = _counterRef.onValue.listen((Event event) {
      setState(() {
        _counter = event.snapshot.value ?? 0;
      });
 });

and when you want to remove listener just make this code 而当您想删除监听器时,只需编写以下代码

if(_counterSubscription !=null)
     _counterSubscription .cancel();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用提供程序进行 DI 时,如何根据 Firebase Auth 流修改 Flutter Firebase Stream 侦听器? - How to modify Flutter Firebase Stream listener based on Firebase Auth stream when using Provider for DI? 需要使用 Flutter 中的 Stream 构建器从 Firebase 获取图像 - Need to get images from Firebase by using Stream builder in Flutter 如何监听stream和更新Flutter GridView builder访问Firebase - How to listen to stream and update Flutter GridView builder accessing Firebase 如何使用 Stream 生成器在具有数据更新的小部件上显示 Flutter firebase 实时数据库? - How to show Flutter firebase realtime database on widgets with data updates using Stream builder? Flutter/Firebase 应用程序 stream 构建器加载数据 - Flutter/Firebase application stream builder load data 如何使用流构建器检查 firebase 文档的长度 - How can I check the length of a firebase document using stream builder 如何使用 Stream 生成器从多个 firebase collections 获取数据 - How to get data from multiple firebase collections using a Stream Builder 使用 Firebase Stream 作为 Flutter 中另一个 Stream 的输入? - Using a Firebase Stream as an input for another Stream in Flutter? 当引用路径不再可用时如何删除 firebase 数据库侦听器 - How to remove firebase database listener when ref path is no longer available 如何在流中生成Firebase侦听器 - How to yield inside firebase listener inside stream
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM