常用于加载网络数据,直接上代码:
import 'package:flutter/material.dart';
class LoadingDialog extends Dialog {
LoadingDialog(
{Key? key,
this.text,
this.width,
this.height,
this.color,
this.contentPadding = 20})
: super(key: key);
final Widget? text;
final double? width;
final double? height;
final Color? color;
final double contentPadding;
@override
Widget build(BuildContext context) {
Widget? textWidget;
if (text != null) {
final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context);
textWidget = Padding(
padding: EdgeInsets.only(top: contentPadding),
child: DefaultTextStyle(
style: dialogTheme.titleTextStyle ?? theme.textTheme.headline6!,
child: text!,
),
);
}
return Center(
child: Container(
width: width ?? 120.0,
height: height ?? 120.0,
decoration: ShapeDecoration(
color: color ?? Color(0xffffffff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
),
),
padding: EdgeInsets.all(contentPadding),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
if (textWidget != null) textWidget,
],
),
),
);
}
}
Future<T?> showLoadingDialog<T>({
required BuildContext context,
bool barrierDismissible = false,
String? title,
bool canCancel = false,
WillPopCallback? onWillPop,
double? width,
double? height,
}) {
Widget? textWidget;
if (title != null) {
textWidget = Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12),
);
}
return showDialog(
context: context,
barrierDismissible: barrierDismissible,
builder: (context) {
Widget dialog = LoadingDialog(
text: textWidget,
width: width,
height: height,
);
if (!canCancel) {
dialog = WillPopScope(
child: dialog,
onWillPop: onWillPop ?? () => Future.value(false),
);
}
return dialog;
});
}
使用方法:
showLoadingDialog(
context: context,
title: "加载中,请稍候",
onWillPop: () {
Future.delayed(Duration(seconds: 3), () {
Navigator.of(context).pop();
});
return Future.value(false);
});
效果图:
高级使用:
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return LoadingDialog(
width: 200,
height: 150,
text: DefaultTextStyle(
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12),
child: Column(
children: [
Text("数据加载中.....", style: TextStyle(color: Colors.blue)),
Text("当前网络较慢,请耐心等候", style: TextStyle(color: Colors.red)),
],
),
),
);
});
效果图:
版权声明:本文为xy109原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。