我可以在Flutter中创建类似于Toasts的内容吗?只是一个微小的通知窗口,它不是直接面向用户,也不会锁定或淡化其后面的视图?
答案 0 :(得分:78)
您可以使用ScaffoldState
Scaffold.of(context)
然后执行类似
的操作Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Sending Message"),
));
Snackbars是来自材料设计的官方“吐司”。见https://material.io/design/components/snackbars.html#usage
这是一个完整的例子:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const Home(),
);
}
}
class Home extends StatelessWidget {
const Home({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Snack bar'),
),
/// We use [Builder] here to use a [context] that is a descendant of [Scaffold]
/// or else [Scaffold.of] will return null
body: Builder(
builder: (context) => Center(
child: RaisedButton(
child: const Text('Show toast'),
onPressed: () => _showToast(context),
),
),
),
);
}
void _showToast(BuildContext context) {
final scaffold = Scaffold.of(context);
scaffold.showSnackBar(
SnackBar(
content: const Text('Added to favorite'),
action: SnackBarAction(
label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
),
);
}
}
答案 1 :(得分:44)
SnackBar
绝对是正确使用的类。
如果您在构建showSnackBar
的构建方法中尝试调用ScaffoldState
,那么关于showSnackBar
的一个棘手问题就是转到Scaffold
。
您可能会看到这样的错误,其中包含一些解释如何解决问题的文字。
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
The following assertion was thrown while handling a gesture:
Scaffold.of() called with a context that does not contain a Scaffold.
No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). This
usually happens when the context provided is from the same StatefulWidget as that whose build
function actually creates the Scaffold widget being sought.
There are several ways to avoid this problem. The simplest is to use a Builder to get a context that
is "under" the Scaffold. For an example of this, please see the documentation for Scaffold.of():
https://docs.flutter.io/flutter/material/Scaffold/of.html
A more efficient solution is to split your build function into several widgets. This introduces a
new context from which you can obtain the Scaffold. In this solution, you would have an outer widget
that creates the Scaffold populated by instances of your new inner widgets, and then in these inner
widgets you would use Scaffold.of().
A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, then use the
key.currentState property to obtain the ScaffoldState rather than using the Scaffold.of() function.
The context used was:
MyHomePage
When the exception was thrown, this was the stack:
#0 Scaffold.of (package:flutter/src/material/scaffold.dart:444:5)
#1 MyHomePage.build.<anonymous closure> (/Users/jackson/Library/Developer/CoreSimulator/Devices/7072C907-DBAD-44FE-8F40-0257442C51D9/data/Containers/Data/Application/77FEC1A4-1453-442C-8208-96E0323DEFB2/tmp/so_scratch2Tkq9Jb/so_scratch2/lib/main.dart:23:24)
#2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:323:14)
#3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:375:30)
#4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
#5 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:149:9)
#6 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:119:7)
#7 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
#8 BindingBase&SchedulerBinding&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
#9 BindingBase&SchedulerBinding&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
#10 BindingBase&SchedulerBinding&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
#11 BindingBase&SchedulerBinding&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
#12 BindingBase&SchedulerBinding&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
#13 _invoke1 (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:100)
#14 _dispatchPointerDataPacket (file:///b/build/slave/Mac_Engine/build/src/flutter/lib/ui/hooks.dart:58)
Handler: onTap
Recognizer:
TapGestureRecognizer#69dbc(debugOwner: GestureDetector, state: ready)
════════════════════════════════════════════════════════════════════════════════════════════════════
您可以将GlobalKey
传递给Scaffold
构造函数:
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final key = new GlobalKey<ScaffoldState>();
return new Scaffold(
key: key,
floatingActionButton: new Builder(
builder: (BuildContext context) {
return new FloatingActionButton(
onPressed: () {
key.currentState.showSnackBar(new SnackBar(
content: new Text("Sending Message"),
));
},
tooltip: 'Increment',
child: new Icon(Icons.add),
);
}
),
);
}
}
或者您可以使用Builder
创建一个{1}}作为脚手架的子女。
BuildContext
最后,您可以将窗口小部件拆分为多个类,这是最好的长期方法。
答案 2 :(得分:35)
使用此plugin
Fluttertoast.showToast(
msg: "This is Toast messaget",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
答案 3 :(得分:6)
要显示吐司消息,您可以使用flutterToast插件来使用该插件,
fluttertoast: ^2.0.7
$ flutter packages get
import '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');
有关更多信息,请检查this
答案 4 :(得分:5)
在Flutter应用中有三种显示吐司的方式。
我将告诉您我所知道的所有三种方式,然后选择您要使用的哪种方式。我会推荐第二个。
1:使用外部软件包。
这是第一种在flutter应用程序上显示吐司的最简单方法。
首先,您必须将此包添加到pubspec.YAML
flutter_just_toast:^version_here
然后将包导入要显示吐司的文件中。
'package:flutter_just_toast/flutter_just_toast.dart';
最后一步显示吐司。
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
2:使用官方方式。
此方法也很简单,但是您必须处理它。我并不是说它很难简单又干净,我会推荐这种方法。
对于这种方法,您要做的所有显示吐司的动作就是使用下面的代码。
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Sending Message"),
));
但是请记住,您必须使用支架环境。
3:使用本机API。
现在,当您已经拥有上述两种方法时,此方法就不再有意义。使用此方法,您必须编写android和iOS的本机代码,然后将其转换为插件,即可开始使用。 这种方法会浪费您的时间,因此您必须重新发明轮子。已经被发明了。
答案 5 :(得分:4)
小吃店
当我尝试使用带有 ScaffoldState
对象的解决方案(由其他人建议)时,我收到一个警告,指出它已弃用:
'showSnackBar' 已弃用,不应使用。使用 ScaffoldMessenger.showSnackBar。此功能在 v1.23.0-14.0.pre.. 之后被弃用。
使用 ScaffoldMessenger
按预期工作:
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("My amazing message! O.o")));
示例:
答案 6 :(得分:4)
对于扑朔迷离的吐司消息,请使用bot_toast库。该库提供了丰富的功能,支持显示通知,文本,加载,附件等。Toast
答案 7 :(得分:3)
fluttertoast:^ 3.1.3
import 'package:fluttertoast/fluttertoast.dart';
Fluttertoast.showToast(
msg: "This is Center Short Toast",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
答案 8 :(得分:2)
使用这个:
Fluttertoast.showToast(
msg: "This is a Toast message",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
答案 9 :(得分:2)
为此,有不同的版本。
1)首先,可以使用Flutter中的小部件SnackBar。
2)您可以使用pub.dev中的Toast,flutter_toast之类的库。
3)第三个版本正在创建您的自定义窗口小部件。可以使用叠加小部件和Flutter中的动画创建。
您可以通过本教程来了解更多信息。这是a link
答案 10 :(得分:1)
您可以使用 this link 在 Flutter 中显示 Toast。
将其用作:
void method1(){
Fluttertoast.showToast(
msg: "This is Add Button",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.blueGrey,
textColor: Colors.white,
fontSize: 14.0
);
}
答案 11 :(得分:1)
这很简单
我们只需要安装Flutter Toast软件包即可。 请参阅以下文档: https://pub.dev/packages/fluttertoast
在安装选项卡中,您将获得依赖项,您必须将该依赖项粘贴到pubspec.yaml中然后进行安装。
之后,只需导入软件包:
import'package:fluttertoast / fluttertoast.dart';
类似于上一行。
然后通过使用FlutterToast类,可以使用fluttertoast。
您完成了!!!
答案 12 :(得分:1)
导入lib
fluttertoast:3.1.3
使用方式如下
Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,
);
答案 13 :(得分:0)
如果到目前为止提供的Fluttertoast软件包不起作用...
然后,我建议您尝试toast。
它没有多余的装饰,也没有仪式。
就是这样。
我在自述文件中的示例中发现了一个错误:
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
虽然该方法需要上下文。因此,最好添加这样的“上下文”:
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
不过,我已经提交了一份PR,很可能在您检查时已经解决了这个问题。
答案 14 :(得分:0)
使用此依赖项:
toast: ^0.1.3
然后在页面中导入toast的依赖项:
import 'package:toast/toast.dart';
然后在小部件的onTap()上:
Toast.show("Toast plugin app", context,duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
答案 15 :(得分:0)
对于android原始图形吐司,您可以使用以下命令:https://pub.dartlang.org/packages/fluttertoast
在Android和iOS上运行正常。 enter image description here
答案 16 :(得分:0)
您可以使用flutter commons package在Flutter应用程序中显示不同类型的祝酒,例如成功,错误,警告和信息。
successToast("Success Message");
答案 17 :(得分:0)
答案Scaffold.of(context).showSnackBar(...)
在大多数情况下不起作用。
我建议最佳方法是在类中声明一个scaffoldState密钥,然后像下面将其分配给Scaffold
GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
然后
Scaffold(
key: _scaffoldKey,
...
)
当您想显示小吃店时,执行此操作。
_scaffoldKey.currentState.showSnackBar(SnackBar(
content: Text("This works!"),
));
答案 18 :(得分:0)
在Flutter中显示Toast消息非常容易。Scaffold.of(context).showSnackBar(SnackBar( content: Text("Toast Text Here"), ));
答案 19 :(得分:0)
https://pub.dev/packages/toast将此用于烤面包,该库非常易于使用,并且非常适合ios和android,
表演吐司的语法:
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
答案 20 :(得分:0)
依赖性:
flutter_just_toast: ^1.0.1
import 'package:flutter_just_toast/flutter_just_toast.dart';
Toast.show(
message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
答案 21 :(得分:0)
我想提供替代解决方案以使用程序包flushbar。
https://github.com/AndreHaueisen/flushbar
就像软件包中所说的那样:如果在通知用户时需要更多自定义,请使用此软件包。对于Android开发人员而言,它可以替代烤面包和小吃店。
另一个使用冲洗栏How to show snackbar after navigator.pop(context) in Flutter?的建议
您还可以将flushbarPosition设置为TOP或BOTTOM
Flushbar(
title: "Hey Ninja",
message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
flushbarPosition: FlushbarPosition.TOP,
flushbarStyle: FlushbarStyle.FLOATING,
reverseAnimationCurve: Curves.decelerate,
forwardAnimationCurve: Curves.elasticOut,
backgroundColor: Colors.red,
boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
isDismissible: false,
duration: Duration(seconds: 4),
icon: Icon(
Icons.check,
color: Colors.greenAccent,
),
mainButton: FlatButton(
onPressed: () {},
child: Text(
"CLAP",
style: TextStyle(color: Colors.amber),
),
),
showProgressIndicator: true,
progressIndicatorBackgroundColor: Colors.blueGrey,
titleText: Text(
"Hello Hero",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
),
messageText: Text(
"You killed that giant monster in the city. Congratulations!",
style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
),
)..show(context);
答案 22 :(得分:0)
导入 cupertino_icons: ^0.1.2
和在下面的代码中写入
showToast(BuildContext context, String message) {
showDialog(
context: context,
builder: (BuildContext context) {
return CupertinoAlertDialog(
title: Text("Name of App",
content: Text(message,
actions: <Widget>[
FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
答案 23 :(得分:0)
最简单的方法是将以下行添加到依赖文件中
toast: ^0.1.5
并像下面一样使用它
import 'package:toast/toast.dart';
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
答案 24 :(得分:0)
答案 25 :(得分:0)
只需在诸如onTap和onPress之类的任何事件内使用 SnackBar(content:Text(“ hello”),))
上阅读有关Snackbar的更多信息。答案 26 :(得分:0)
没有用于随动吐司的小部件,您可以转到this plugin 用例:
Fluttertoast.showToast(
msg: "My toast messge",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,);
答案 27 :(得分:0)
get flutter toast package here
将此包添加到pubspec.yaml中的项目依赖项中
然后只要您希望像按一下按钮一样显示Toast
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
答案 28 :(得分:0)
将flutter_just_toast添加到Pubspecs.yaml中的依赖项
依赖性:
flutter_just_toast: ^1.0.1
下一个导入包到您的班级:
import 'package:flutter_just_toast/flutter_just_toast.dart';
用消息实现吐司
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
答案 29 :(得分:0)
对于那些正在寻找Toast
的人而言,SnackBar
可能不是改变路线的最佳选择。
请改为查看Overlay
。
答案 30 :(得分:-1)
您可以使用FlutterToast之类的东西
导入lib
fluttertoast: ^2.1.4
使用方式如下
Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,
);
就这样。
答案 31 :(得分:-1)
您可以使用库“ fluttertoast”。为此,请将其添加到pubspec.yaml文件中,例如:
dependencies:
fluttertoast: ^3.1.0
然后将该库导入dart文件中,您需要祝酒并编写代码。例如,请参考以下代码:
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ToastExample extends StatefulWidget {
@override
_ToastExampleState createState() {
return _ToastExampleState();
}
}
class _ToastExampleState extends State {
void showToast() {
Fluttertoast.showToast(
msg: 'Some text',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Colors.red,
textColor: Colors.white
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Toast Tutorial',
home: Scaffold(
appBar: AppBar(
title: Text('Toast Tutorial'),
),
body: Padding(
padding: EdgeInsets.all(15.0),
child: Center(
child: RaisedButton(
child: Text('Press to show'),
onPressed: showToast,
),
),
)
),
);
}
}
void main() => runApp(ToastExample());
答案 32 :(得分:-1)