Flutter:自定义错误显示

为什么要自定义错误处理

以下面数组越界的错误为例:

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,
      );
相关推荐
To_OC12 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
灯澜忆梦13 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-13 小时前
C#中的StringBuilder相关方法
开发语言·c#
To_OC13 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
GitLqr14 小时前
玩转 WebSocket:从原理到 Flutter 实战
websocket·网络协议·flutter
小林ixn14 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
-银雾鸢尾-14 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
世人万千丶14 小时前
参数管理_Flutter在鸿蒙平台路由参数最佳实践
学习·flutter·华为·harmonyos·鸿蒙
এ慕ོ冬℘゜14 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
大模型码小白15 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程