官方文档:
在构建阶段发生错误时,
调用ErrorWidget.builder 回调来构建小部件
被用来代替失败的那个。默认情况下,在调试模式下
以红色显示错误消息,在发布模式下显示灰色
背景。
您可以在 MaterialApp 小部件的builder 方法中定义它。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class CustomError extends StatelessWidget {
final FlutterErrorDetails errorDetails;
const CustomError({
Key key,
@required this.errorDetails,
}) : assert(errorDetails != null),
super(key: key);
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
child: Text(
"Something is not right here...",
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
padding: const EdgeInsets.all(8.0),
),
color: Colors.red,
margin: EdgeInsets.zero,
);
}
}
class MyApp extends StatelessWidget {
MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
builder: (BuildContext context, Widget widget) {
ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
return CustomError(errorDetails: errorDetails);
};
return widget;
},
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
Text(
'Welcome,',
style: Theme.of(context).textTheme.headline6,
),
FirstName(),
],
padding: const EdgeInsets.all(30.0),
),
);
}
}
class FirstName extends StatelessWidget {
FirstName({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(null);
}
}
看起来是这样的:
(点击放大)