为什么要自定义错误处理
以下面数组越界的错误为例:
dart
class _YcHomeBodyState extends State<YcHomeBody> {
List<String> list = ['苹果', '香蕉'];
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Text(list[0]),
Text(list[2]),
],
));
}
}
当构建失败后会在屏幕上如下显示,这样不太友好,是否可以进行自定义错误显示呢?
自定义错误显示
使用Flutter的错误处理机制:Flutter提供了一个全局的错误处理机制,可以通过重写ErrorWidget.builder
来自定义错误显示。
自定义的错误widget
dart
class CustomErrorHandle extends StatelessWidget {
final String errorMessage;
const CustomErrorHandle({Key? key, required this.errorMessage})
: super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.grey.withOpacity(0.5),
child: Center(
child: Container(
padding: const EdgeInsets.all(20),
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.3,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10), color: Colors.white),
child: Column(
children: [
Row(
children: const [
Icon(Icons.warning_amber_sharp),
Text(
"错误提示",
style: TextStyle(fontSize: 20),
)
],
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
//当超出两行时,文本将被截断
child: Align(
alignment: Alignment.topLeft,
child: Text(
errorMessage,
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
)),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('确定'))
],
),
],
),
),
),
));
}
}
全局监听
dart
main() {
// 全局错误处理机制
FlutterError.onError = (FlutterErrorDetails errorDetails) {
print('错误消息:$errorDetails');
ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
return CustomErrorHandle(
errorMessage: errorDetails.exception.toString(),
);
};
};
runApp(const MyApp());
}
如果不想显示系统提示的异常信息,可以进行自定义,比如:
dart
String errorMessage = '发生错误,请稍后重试。';
var exception = errorDetails.exception;
if(exception is RangeError){
errorMessage ='数组越界';
}
return CustomErrorHandle(
errorMessage: errorMessage,
);