存在由dart:async提供的特殊功能runZoned.文件在这里: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个任务的执行.

Updated version of the answer:

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

Dart相关问答推荐

NetworkImage 正在缓存旧图像

如何在 Dart 中返回函数?

禁用 ListView 滚动

Flutter Expansion Tile -- 标题 colored颜色 变化和尾随动画箭头 colored颜色 变化

Angular Dart 和 Polymer Dart 的区别

InheritedWidget - 在 navigator.push 之后在 null 上调用 getter

如何处理 ListView 滚动方向

如何调整ShowDialog的子级大小

如何防止键盘在Flutter中按提交键时失效?

用百分比将小部件放置在堆栈中

Flutter 在整个屏幕上禁用touch

Flutter-当文本字段有焦点时隐藏提示文本

将函数/方法分配给 Dart 中的变量

Dart:并行处理传入的 HTTP 请求

可选参数的默认值必须是常量

Dart:Iterable 与 List,总是使用 Iterable?

在 Dart 中没有换行符的 print()?

从函数返回多个值

Dart:创建一个从 0 到 N 的列表

如何删除dart列表中的重复项? list.distinct()?