我試圖測驗未來的行為,但是
將來拋出例外會破壞飛鏢主執行緒
然而,在 Flutter 中情況正好相反:
飛鏢代碼
Future(() async {
await Future.delayed(Duration(seconds: 10));
print("TimeOut");
}).timeout(Duration(seconds: 5));
Future(() async {
await Future.delayed(Duration(seconds: 15));
print("AAAAAAA");
});
在 Dart 中使用代碼 dart run ./a.dart
Unhandled exception:
TimeoutException after 0:00:05.000000: Future not completed
在顫振中:
E/flutter (11789): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: TimeoutException after 0:00:05.000000: Future not completed
E/flutter (11789):
I/flutter (11789): TimeOut
I/flutter (11789): AAAAAAA
為什么 ?
uj5u.com熱心網友回復:
Dart 和 Flutter 之間的區別在于,Flutter 會捕獲所有未處理的例外并將它們列印出來(包括堆疊跟蹤)。這是故意的,秘訣在于 Flutter 向靜態類函式FlutterError.onError注冊了一個回呼,默認實作是函式FlutterError.presentError。有關官方檔案的更多詳細資訊:Flutter 中的處理錯誤
禁用 Dart 中的致命錯誤終止
可以通過呼叫Isolate.setErrorsFatal來禁用在致命錯誤時終止應用程式/腳本false。例如,即使拋出未處理的例外也要保持異步代碼運行,只需執行此操作即可。
void main () {
Isolate.current.setErrorsFatal(false); // <- Here
Future(() async {
await Future.delayed(Duration(seconds: 10));
print("TimeOut");
}).timeout(Duration(seconds: 5));
Future(() async {
await Future.delayed(Duration(seconds: 15));
print("AAAAAAA");
});
}
輸出將是:
TimeOut
AAAAAAA
與 Flutter 具有相同行為的 Dart
以下代碼模擬了 Flutter 在 Dart 中使用runZonedGuarded所做的相同事情:
import 'dart:async';
void main(List<String> args) {
runZonedGuarded(program, errorHandler);
}
void program() {
Future(() async {
await Future.delayed(Duration(seconds: 10));
print("TimeOut");
}).timeout(Duration(seconds: 5));
Future(() async {
await Future.delayed(Duration(seconds: 15));
print("AAAAAAA");
});
}
void errorHandler(Object error, StackTrace stack) {
print('Unhandled exception:\n$error');
}
Dart 中的輸出將如下所示:
Unhandled exception:
TimeoutException after 0:00:05.000000: Future not completed
TimeOut
AAAAAAA
與 Dart 具有相同行為的 Flutter
另一方面,在 Flutter 中也可以像 Dart 一樣做同樣的事情。即在出現未處理的例外時終止應用程式。這只是再次使用runZonedGuarded的問題:
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
runZonedGuarded(() async {
runApp(const MyApp());
}, (Object error, StackTrace stack) {
print('Unhandled exception:\n$error');
exit(1);
});
}
void program() {
Future(() async {
await Future.delayed(Duration(seconds: 10));
print("TimeOut");
}).timeout(Duration(seconds: 5));
Future(() async {
await Future.delayed(Duration(seconds: 15));
print("AAAAAAA");
});
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
program();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => const Scaffold(
body: Center(child: Text('The app is going to exit in 5 seconds...')),
),
);
}
}
輸出將如下所示:
flutter: Unhandled exception:
TimeoutException after 0:00:05.000000: Future not completed
Lost connection to device.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493911.html
上一篇:使用asyncio從websockets輸出變數的更好方法?
下一篇:將方法轉換為異步
