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

Show user-friendly error page instead of exception in Flutter

是否有可能全局错误处理显示用户友好的错误页面而不是显示红色异常

我已经做了错误处理(here),它会向后端报告异常,但我真正想要实现的是隐藏红色异常并显示一些更友好的东西。

我到处搜索,几乎什么也没找到。很抱歉,我没有任何代码可以显示,因为我不知道如何开始。

官方文档:

When an error occurs during the build phase, the ErrorWidget.builder callback is invoked to build the widget that is used instead of the one that failed. By default, in debug mode this shows an error message in red, and in release mode this shows a gray background.

您可以在 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);
  }
}

这是它的样子:

(点击放大)

基于 Spectarion 的回答:

  1. 添加了脚手架。如果没有 Scaffold,消息会出现在之前呈现的内容之上。
  2. 将更多代码移至辅助方法。

代码:

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'),
     );
   }
 }

要定义在构建器构建小部件失败时显示的自定义错误小部件,请使用 MaterialApp.builder

class MyApp extends StatelessWidget {
...
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      ...
      builder: (BuildContext context, Widget widget) {
        Widget error = Text('...rendering error...');
        if (widget is Scaffold || widget is Navigator)
          error = Scaffold(body: Center(child: error));
        ErrorWidget.builder = (FlutterErrorDetails errorDetails) => error;
        return widget;
      },
    );
  }
}