如何取消监听器?

问题描述 投票:0回答:1

我在项目中使用https://pub.dev/packages/flutter_uploader

try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        final taskId = await uploader.enqueue(
            url:
                'https://xxxx',
            files: files,
            data: {
             ....
            },
            method: UploadMethod.POST,
            showNotification: true,
            tag: title);

        final subscription = uploader.result.listen((result) async {
          print("response " + result.response);
        }, onError: (ex, stacktrace) {
          print(ex.toString());
        });
      }
    } catch (e) {
      ...
    }
  }

[当我第一次打电话时,uploader.result.listen只会打印一次。但是,如果我再次调用此方法,则uploader.result.listen将调用两次。为什么?

编辑

我将subscription.cancel()放在onError之下,但是监听器将停止工作。

flutter dart listener
1个回答
0
投票

从您的共享代码中,我可以看到您已经在此函数之外创建了uploader对象,因此,每当调用此函数时,实际上就是在该uploader中添加新的侦听器。最好在创建了uploader对象的位置添加列表器,而不是在此函数中添加列表器。

© www.soinside.com 2019 - 2024. All rights reserved.