我可以在Flutter中创建类似Toasts的东西吗?
只是一个很小的通知窗口,不直接面对用户,也不锁定或淡出它后面的视图。
我可以在Flutter中创建类似Toasts的东西吗?
只是一个很小的通知窗口,不直接面对用户,也不锁定或淡出它后面的视图。
当前回答
对于那些正在寻找能在路线变化中幸存下来的吐司的人来说,SnackBar可能不是最好的选择。
让我们来看看Overlay。
其他回答
你可以直接使用小吃店的元素
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Successfully!"),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(20),
shape: StadiumBorder(),
action: SnackBarAction(
label: 'Dismiss',
disabledTextColor: Colors.white,
textColor: Colors.blue,
onPressed: () {
//Do whatever you want
},
),
),
);
用https://pub.dev/packages/toast做吐司。这个库非常容易使用,适用于iOS和Android。
显示Toast的语法:
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
要显示Toast消息,您可以使用FlutterToast插件。要使用这个插件,你必须:
将此依赖项添加到您的pubspec中。Yaml文件:fluttertoast: ^8.0.8 要获取包,必须运行以下命令:$ flutter packages get 导入包:导入'package:fluttertoast/fluttertoast.dart';
像这样使用它:
Fluttertoast.showToast(
msg: "your message",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM // Also possible "TOP" and "CENTER"
backgroundColor: "#e74c3c",
textColor: '#ffffff');
要了解更多信息,请查看这个。
你可以很容易地实现这种效果使用叠加。
代码:
OverlayEntry entry = OverlayEntry(builder: (context) {
return Positioned(
top: MediaQuery.of(context).size.height * 0.8,
child: Container(
width: MediaQuery.of(context).size.width,
alignment: Alignment.center,
child: const Card(
color: Colors.redAccent,
child: Padding(
padding: EdgeInsets.all(8),
child: Text("This is a message."),
),
),
));
});
//show overlay
Overlay.of(context)!.insert(entry);
//auto remove this overlay after 3 seconds
Future.delayed(const Duration(seconds: 3)).then((value) => entry.remove());
截图:
导入库fluttertoast: 3.1.3
像下面这样使用它:
Fluttertoast.showToast(
msg: "Hello, World!",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,
);