gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:29:23 25 4
gpt4 key购买 nike

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

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

我到处搜索,但实际上一无所获。很抱歉我没有任何代码可显示,因为我不知道如何开始。

最佳答案

官方文档:

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

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

看起来是这样的:

Before and after(点击放大)

关于flutter - 在 Flutter 中显示用户友好的错误页面而不是异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53334608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com