是否可以进行全局错误处理,以显示用户友好的错误页面而不是显示红色异常?
我已经进行了错误处理(here),它会向后端报告异常,但我真正希望实现的是隐藏红色异常并显示一些更常见的东西。
我到处搜索,我发现什么都没有。对不起,我没有任何代码要显示,因为我不知道如何开始。
我在GitHub页面上打开了这个问题,得到了答案there。
Widget getErrorWidget(BuildContext context, FlutterErrorDetails error) { return Center( child: Text( "Error appeared.", style: Theme.of(context).textTheme.title.copyWith(color: Colors.white), ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { ErrorWidget.builder = (FlutterErrorDetails errorDetails) { return getErrorWidget(context, errorDetails); }; return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } }
解决方案由Wouter Hardeman提供
更新:
使用上面的解决方案,您无法使用ThemeData,因为在我们定义自定义异常窗口小部件时没有实例化MaterialApp。要解决这个问题:
Widget getErrorWidget(BuildContext context, FlutterErrorDetails error) {
return Center(
child: Text(
"Error appeared.",
style: Theme.of(context).textTheme.title.copyWith(color: Colors.white),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
return getErrorWidget(context, errorDetails);
};
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
builder: (BuildContext context, Widget widget) {
ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
return getErrorWidget(context, errorDetails);
};
return widget;
},
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
没有自定义错误:
有自定义错误: