工具类
import 'package:flutter/material.dart';
class Toast {
static const Duration lengthShort = Duration(milliseconds: 1000);
static const Duration lengthLong = Duration(milliseconds: 3000);
String _text; //显示的文本
BuildContext _context; //上下文
Duration _duration; //持续的时长
TextStyle? _textStyle; //文本样式
Color _backgroundColor; //背景颜色
double _radiusSize; //圆角大小
EdgeInsetsGeometry? _padding; //内边距大小
double _top; //顶部距离 百分比
Toast._(this._text, this._context, this._duration, this._textStyle,
this._backgroundColor, this._radiusSize, this._padding, this._top);
factory Toast.makeText(
BuildContext context,
String text, {
Duration duration = lengthShort,
TextStyle? textStyle,
Color backgroundColor = Colors.black,
double radiusSize = 4,
EdgeInsetsGeometry? padding,
double top = 0.8,
}) {
return Toast._(text, context, duration, textStyle, backgroundColor,
radiusSize, padding, top);
}
OverlayEntry _buildBody() {
return OverlayEntry(builder: (context) {
Size size = MediaQuery.of(context).size;
return Positioned(
top: size.height * _top,
child: Material(
color: Colors.transparent,
child: Container(
width: size.width * 0.8,
alignment: Alignment.center,
margin: EdgeInsets.only(left: size.width * 0.1),
child: _buildToastView(),
),
));
});
}
Widget _buildToastView() {
return Container(
padding:
_padding ?? const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
decoration: BoxDecoration(
color: _backgroundColor,
borderRadius: BorderRadius.all(Radius.circular(_radiusSize)),
),
child: Text(_text,
style:
_textStyle ?? const TextStyle(fontSize: 12, color: Colors.white)),
);
}
show() {
OverlayEntry entry = _buildBody();
Overlay.of(_context)?.insert(entry);
Future.delayed(_duration, () {
entry.remove();
});
}
}
调用方式
Toast.makeText(context,"加载成功").show();
Toast.makeText(context,"加载成功",duration: Toast.lengthLong).show();
展示结果
?
|