在 Flutter 中,优雅地实现一个错误页面可以通过以下几个步骤:
class ErrorWidget extends StatelessWidget {
final String errorMessage;
ErrorWidget(this.errorMessage);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.error,
color: Colors.red,
size: 60,
),
SizedBox(height: 16),
Text(
errorMessage,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.red,
),
textAlign: TextAlign.center,
),
],
),
);
}
}
if (hasError) {
return ErrorWidget('出现错误,请重试。');
}
class ErrorHandlingWidget extends StatelessWidget {
final Widget child;
final Function onRetry;
ErrorHandlingWidget({
required this.child,
required this.onRetry,
});
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: someAsyncFunction(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return ErrorWidget(
'出现错误,请重试。',
onRetry: onRetry,
);
}
return child;
},
);
}
}
ErrorHandlingWidget(
child: SomeWidget(),
onRetry: () {
// 处理错误的逻辑
},
)
通过以上步骤,可以优雅地在 Flutter 中实现一个错误页面。
领取专属 10元无门槛券
手把手带您无忧上云