toastDemo.dart
import 'package:flutter/material.dart';
import 'dart:async';
class ToastHelper {
static const style = TextStyle(
color: Colors.white,
fontSize: 14.0,
decoration: TextDecoration.none,
);
// 生成widget
Widget makeWidget(icon, text) {
return Center(
child: Container(
decoration: new BoxDecoration(
color: Colors.lightBlue,
borderRadius: BorderRadius.all(Radius.circular(4.0)),
//设置四周边框
border: new Border.all(width: 1, color: Colors.grey),
),
padding: const EdgeInsets.symmetric(vertical: 5.0, horizontal: 10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// 图标或图片
Container(
child: Image.asset(
icon,
width: 32.0,
height: 28.0,
),
margin: const EdgeInsets.only(left: 4.0, right: 4.0),
),
Text(
text,
style: style,
),
],
),
),
);
}
// crying
void showCryingToast(BuildContext context, String text) {
const icon = 'images/icon/crying.png';
Widget widget = makeWidget(icon, text);
var entry = OverlayEntry(
builder: (_) => widget,
);
Overlay.of(context).insert(entry);
Timer(const Duration(seconds: 2), () {
entry?.remove();
});
}
// laughing
void showLaughingToast(BuildContext context, String text) {
const icon = 'images/icon/laughing.png';
Widget widget = makeWidget(icon, text);
var entry = OverlayEntry(
builder: (_) => widget,
);
Overlay.of(context).insert(entry);
Timer(const Duration(seconds: 2), () {
entry?.remove();
});
}
// info
void showInfoToast(BuildContext context, String text) {
const icon = 'images/icon/info.png';
Widget widget = makeWidget(icon, text);
var entry = OverlayEntry(
builder: (_) => widget,
);
Overlay.of(context).insert(entry);
Timer(const Duration(seconds: 2), () {
entry?.remove();
});
}
// warning
void showWarningToast(BuildContext context, String text) {
const icon = 'images/icon/warning.png';
Widget widget = makeWidget(icon, text);
var entry = OverlayEntry(
builder: (_) => widget,
);
Overlay.of(context).insert(entry);
Timer(const Duration(seconds: 2), () {
entry?.remove();
});
}
// error
void showErrorToast(BuildContext context, String text) {
const icon = 'images/icon/error.png';
Widget widget = makeWidget(icon, text);
var entry = OverlayEntry(
builder: (_) => widget,
);
Overlay.of(context).insert(entry);
Timer(const Duration(seconds: 2), () {
entry?.remove();
});
}
}
里面的图表需要在pubspec.yaml 引入
assets:
# loading
- images/loading/01.jpg
- images/loading/02.jpg
- images/loading/03.jpg
- images/loading/04.jpg
- images/loading/05.jpg
# icon
- images/icon/sawako.jpg
- images/icon/flower.png
- images/icon/code.png
- images/icon/tools.png
- images/icon/hat.png
- images/icon/socks.png
- images/icon/crying.png
- images/icon/laughing.png
- images/icon/info.png
- images/icon/warning.png
- images/icon/error.png
使用:
onPressed: () async {
final toastHelp = new ToastHelper();
toastHelp.showErrorToast(context, "出错了呢~"); // context
}
传入context即可。
显示效果:
cryingToast:
errorToast: