显示用户友好的错误页面,而不是Flutter中的异常

kuhbmx9i  于 2023-01-02  发布在  Flutter
关注(0)|答案(2)|浏览(111)

是否可以进行全局错误处理显示用户友好的错误页面,而不是显示红色异常
我已经做了错误处理(here),它将向后端报告异常,但我真正想实现的是隐藏红色异常,并显示一些更友好的东西。

dsekswqp

dsekswqp1#

官方文件:
当构建阶段出现错误时,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);
  }
}

它看起来是这样的:


(点击放大)

vs3odd8k

vs3odd8k2#

基于Anis Alibegić的答案:
1.添加了Scaffold。如果没有Scaffold,消息将显示在以前呈现的内容的顶部。
1.将更多代码移到帮助器方法中。
代码:

void setErrorBuilder() {
  ErrorWidget.builder = (FlutterErrorDetails errorDetails) {
    return Scaffold(
        body: Center(
            child: Text("Unexpected error. See console for details.")));
  };
} 

class MyApp extends StatelessWidget {
   @override
   Widget build(BuildContext context) {
     setErrorBuilder();

     return MaterialApp(
       builder: (BuildContext context, Widget widget) {
         setErrorBuilder();    
         return widget;
       },
       title: 'Flutter Demo',
       home: MyHomePage(title: 'Flutter Demo Home Page'),
     );
   }
 }

相关问题