话不多说直接上代码:
import 'dart:async';
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flutter Crash Capture'),),
body: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<String> list = ["a"];
print(list[10]);
return Container();
}
}
Future<Null> main() async {
FlutterError.onError = (FlutterErrorDetails details) async {
if (isInDebugMode) {
FlutterError.dumpErrorToConsole(details);
} else {
Zone.current.handleUncaughtError(details.exception, details.stack);
}
};
runZoned<Future<void>>(() async {
runApp(MyApp());
}, onError: (error, stackTrace) async {
await _reportError(error, stackTrace);
});
}
Future<Null> _reportError(dynamic error, dynamic stackTrace) async {
// TODO
// 上传错误信息
// 可以打印也可以上传服务器
print(error.toString());
print(stackTrace.toString());
}
bool get isInDebugMode {
// Assume you're in production mode.
bool inDebugMode = false;
// Assert expressions are only evaluated during development. They are ignored
// in production. Therefore, this code only sets `inDebugMode` to true
// in a development environment.
assert(inDebugMode = true);
return inDebugMode;
}
运行结果:
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following RangeError was thrown building MyHomePage(dirty):
flutter: RangeError (index): Invalid value: Only valid value is 0: 10
flutter:
flutter: The relevant error-causing widget was:
flutter: MyHomePage
flutter:
package:firstflutter_project/main.dart:11
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 List.[] (dart:core-patch/growable_array.dart:149:60)
flutter: #1 MyHomePage.build
package:firstflutter_project/main.dart:21
flutter: #2 StatelessElement.build
package:flutter/…/widgets/framework.dart:4291
...
...
flutter: (elided 8 frames from package dart:async and package dart:async-patch)
flutter:
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
网友评论