dart Flutter区与未来

yyhrrdl8  于 2023-06-19  发布在  Flutter
关注(0)|答案(1)|浏览(158)

我读过关于Zone的文章,并在许多语言中使用过Futures。我知道事件循环和Dart是单线程的。然而,当我写下面的代码时,我无法区分它的工作方式有多不同,以及何时使用一个而不是另一个。
zone和future的区别是什么?
例如:

runZoned(() async {
  // Do Something
}, onError: (e, stackTrace) {
  print(e);
});

VS

someAsyncCall().catchError((e) {

  print(e);
});
t40tm48m

t40tm48m1#

Futures error handling
Zones
什么是未来
编辑1:我使用了 * runZonedGuarded * instaed * runZoned *,因为 * runZoned.onError * 已弃用。
Flutter : 'onError' is deprecated on runZoned function
嗨!使用runZoned,你基本上可以处理通常由future(http请求等)引起的异步错误。这个概念类似于同步代码中的try-catch。未来,你不能这样做。
runZoned示例:

runZonedGuarded(() {
  _timerError();
}, (error, stack) {
  print('Uncaught error runZoneGuard: $error');
});

结果:

I/flutter (13567): Uncaught error runZoneGuard: asynchronous error

未来的例子:

someCall().then((value) {
  _timerError();
}, onError: (value) {
  print('Uncaught error onError: $value');
}).catchError((e) {
  print('Uncaught error catchError: $e');
});

结果:

E/flutter (13567): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: asynchronous error
E/flutter (13567): #0      _MyHomePageState._timerError.<anonymous closure> (package:async_study/main.dart:60:7)
E/flutter (13567): #1      _rootRun (dart:async/zone.dart:1418:47)
E/flutter (13567): #2      _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (13567): #3      _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter (13567): #4      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter (13567): #5      _rootRun (dart:async/zone.dart:1426:13)
E/flutter (13567): #6      _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (13567): #7      _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1260:23)
E/flutter (13567): #8      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (13567): #9      _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (13567): #10     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (13567): #11     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

以及用于trhow异步错误的'_timerError()'方法:

void _timerError() {
    Timer.run(() {
      throw "asynchronous error";
    });
}

相关问题