runZoned
提供了一个特殊的功能dart:async
。该文件在这里:https://api.dartlang.org/docs/channels/stable/latest/dart_async.html#runZoned
我不确定此功能的目的是什么,我们什么时候需要它,以及如何正确使用它?
最佳答案
看下面的代码:
import 'dart:async';
void main() {
fineMethod().catchError((s) {}, test : (e) => e is String);
badMethod().catchError((s) {}, test : (e) => e is String);
}
Future fineMethod() {
return new Future(() => throw "I am fine");
}
Future badMethod() {
new Future(() => throw "I am bad");
return new Future(() => throw "I am fine");
}
输出
Unhandled exception:
I am bad
现在看下面的代码:
import 'dart:async';
void main() {
fineMethod().catchError((s) {}, test : (e) => e is String);
runZoned(() {
badMethod().catchError((s) {}, test : (e) => e is String);
}, onError : (s) {
print("It's not so bad but good in this also not so big.");
print("Problem still exists: $s");
});
}
Future fineMethod() {
return new Future(() => throw "I am fine");
}
Future badMethod() {
new Future(() => throw "I am bad");
return new Future(() => throw "I am fine");
}
输出
It's not so bad but good in this also not so big.
Problem still exists: I am bad
如果可能,您应严格避免使用
badMethod
。只有在这种情况下,您才可以临时使用
runZoned
您也可以使用
runZoned
模拟任务的sandboxed
执行。