这是几个常用的全局共用的提示框方法,在我之后的文章里可能会多次用到,这里统一记录一下。
以下方法全部写在lib/common/toast.dart
中。
showToast
fluttertoast 适用于Flutter的Android和iOS的Toast库。
在pubspec.yaml文件里添加:
fluttertoast: ^3.1.3
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
void showToast(
String text, {
gravity: ToastGravity.CENTER,
toastLength: Toast.LENGTH_SHORT,
}) {
Fluttertoast.showToast(
msg: text,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.grey[600], // 灰色背景
fontSize: 16.0,
);
}
使用:
showToast("删除成功!");
showLoading
一个加载中的动画,不传text时,默认显示文字Loading...
void showLoading(context, [String text]) {
text = text ?? "Loading...";
showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return Center(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(3.0),
boxShadow: [
//阴影
BoxShadow(
color: Colors.black12,
//offset: Offset(2.0,2.0),
blurRadius: 10.0,
)
]),
padding: EdgeInsets.all(16),
margin: EdgeInsets.all(16),
constraints: BoxConstraints(minHeight: 120, minWidth: 180),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 30,
width: 30,
child: CircularProgressIndicator(
strokeWidth: 3,
),
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Text(
text,
style: Theme.of(context).textTheme.body2,
),
),
],
),
),
);
});
}
使用:
showLoading(context, '删除中,请等待......');
showConfirmDialog
带有确定取消按钮的提示框,content是提示框的内容文字,confirmCallback是点击确定按钮的回调
void showConfirmDialog(BuildContext context,String content, Function confirmCallback) {
showDialog(
context: context,
builder: (context) {
return new AlertDialog(
title: new Text("提示"),
content: new Text(content),
actions: [
new FlatButton(
onPressed: () {
confirmCallback();
Navigator.of(context).pop();
},
child: new Text("确认"),
),
new FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: new Text("取消"),
),
],
);
});
}
使用:
showConfirmDialog(context, '确认删除该数据吗?', () {
// print('点击了确定删除......');
// 执行确定操作后的逻辑
});
参考资料
fluttertoast
showDialog
AlertDialog class: A material design alert dialog.
【Flutter】ActionSheet, Alert, Dialog