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,
      );
相关推荐
阿里嘎多学长7 小时前
2026-10-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
布吉岛的石头8 小时前
Java 程序员第 50 阶段2:预训练的目标函数:自回归语言建模本质
java·开发语言·人工智能·深度学习·回归·transformer
小羊没烦恼!8 小时前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
quantdash_cc9 小时前
从实时行情到价格观察表:用 Python 和 Pandas 构建策略输入数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
昂好的day10 小时前
VisionMaster 通信模块实战(上):Modbus、TCP 收发、协议组装解析
开发语言·网络·网络协议·tcp/ip·c#
努力实干11 小时前
面向对象设计原则——C++
开发语言·c++·数码相机
NetX行者13 小时前
四语言 Hello World 背后:编译模型与运行时对比
开发语言
Pin_Qing13 小时前
账单没超,请求先被拒了
大数据·开发语言·人工智能
2601_9628857213 小时前
如何用 Python 计算 VaR 和 CVaR(在险价值)?
开发语言·python