onStart method
子类实现:启动时的操作
Implementation
@override
Future<void> onStart() async {
// 捕获前一个处理器,避免直接调用 [FlutterError.presentError]:
// presentError 在部分 Flutter 版本中会再次派发到 FlutterError.onError,
// 造成无限递归;同时确保原始处理器(如默认控制台输出)不会被覆盖丢失。
_previousOnError = FlutterError.onError;
// 同样捕获 PlatformDispatcher 的原处理器,停止时还原而非置 null。
_previousPlatformOnError = PlatformDispatcher.instance.onError;
FlutterError.onError = (FlutterErrorDetails details) {
// 直接调用前一个处理器,禁止通过 FlutterError.presentError 回派。
_previousOnError?.call(details);
// 收集异常日志
collect(LogEntry(
level: LogLevel.error,
message: details.exceptionAsString(),
tag: 'flutter_error',
source: LogSource.exception,
stackTrace: details.stack,
error: details.exception,
extra: {
'library': details.library,
'context': details.context?.toString(),
},
));
};
// Dart异常处理
PlatformDispatcher.instance.onError = (error, stack) {
// 先转发给前一个处理器(镜像上方 FlutterError 分支的先转发后采集),
// 返回值取原处理器的结果;未注册时视为已处理(保持既有默认 true)。
// 若恒返回 true,会吃掉宿主 App 已注册处理器的判定结果。
final bool handled = _previousPlatformOnError?.call(error, stack) ?? true;
// 收集异常日志
collect(LogEntry(
level: LogLevel.fatal,
message: error.toString(),
tag: 'dart_error',
source: LogSource.exception,
stackTrace: stack,
error: error,
));
return handled;
};
}