问题描述
我在我的项目中使用。
I using https://pub.dev/packages/flutter_uploader in my project.
存储库
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
将调用两次。为什么?
When first time I call this, uploader.result.listen
will only print once. But if I call this method again, uploader.result.listen
will call twice. Why?
编辑
我已将代码更改为此
PageA
StreamSubscription<UploadTaskResponse> _subscription;
FlutterUploader uploader = FlutterUploader();
@override
void initState() {
super.initState();
_subscription = uploader.result.listen(
(result) {
// insert result to database
.....
},
onError: (ex, stacktrace) {
// ... code to handle error
},
);
}
void dispose() {
super.dispose();
_subscription.cancel();
_defectBloc.dispose();
}
在页面A中,它具有floatActionButton。单击浮动操作按钮后,它将打开页面B。我将 uploader
参数传递给PageB和 bloc
,因此它可以收听上载器
。如果我在初始化页面上,数据能够插入本地数据库。如果我退出应用程序,该如何使插入也起作用?
In page A, it has floatingActionButton. When the floating action button is clicked, it will open page B. I will pass the uploader
param to PageB and bloc
, so it can listen to the uploader
. Data able to insert into local database if I on the init page. How can I let the insert work too if I exit the app?
推荐答案
调用 uploader时。 result.listen
它将每次添加一个订阅,如果您调用n次,则将添加n个订阅。
When you call uploader.result.listen
it'll add a subscription each time, if you call that n times, n subscription will be added.
问题,您需要使用 cancel()方法,否则您只需添加一次订阅(在initState中,然后在dispose方法中取消)。
To fix the issue, either you need to cancel previous subscription using cancel() method or you have to add the subscription only once (In your initState and cancel in your dispose method).
这篇关于Flutter .listen被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!