14

runZoned提供了一个特殊的功能dart:async。文档在这里:https ://api.dartlang.org/docs/channels/stable/latest/dart_async.html#runZoned

我不确定这个功能的目的是什么,我们什么时候需要它,以及如何正确使用它?

4

1 回答 1

14

看看这段代码:

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任务的执行。

答案的更新版本:

import 'dart:async';

Future<void> main() async {
  try {
    await fineMethod();
  } catch (e) {
    log(e);
  }

  await runZonedGuarded(() async {
    try {
      await badMethod();
    } catch (e) {
      log(e);
    }
  }, (e, s) {
    print("========");
    print("Unhandled exception, handled by `runZonedGuarded`");
    print("$e");
    print("========");
  });
}

Future badMethod() {
  // Unhandled exceptions
  Future(() => throw "Bad method: bad1");
  Future(() => throw "Bad method: bad2");
  return Future(() => throw "Bad method: fine");
}

Future fineMethod() {
  return Future(() => throw "Fine method: fine");
}

void log(e) {
  print('Handled exception:');
  print('$e');
}

输出:

Handled exception:
Fine method: fine
========
Unhandled exception, handled by `runZonedGuarded`
Bad method: bad1
========
========
Unhandled exception, handled by `runZonedGuarded`
Bad method: bad2
========
Handled exception:
Bad method: fine
于 2014-02-03T17:30:42.823 回答