Answers:
您可以ScaffoldState
使用Scaffold.of(context)
然后做类似的事情
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Sending Message"),
));
小吃店是材料设计中的官方“吐司”。参见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),
),
);
}
}
showSnackBar()
应有一个Scaffold
父项。
使用这个插件
Fluttertoast.showToast(
msg: "This is Toast messaget",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
Unhandled Exception: MissingPluginException(No implementation found for method showToast on channel PonnamKarthik/fluttertoast)
SnackBar
正如Darky所指出的那样,绝对是使用正确的类。
关于棘手的事情showSnackBar
是ScaffoldState
,如果您试图showSnackBar
在构建您的.NET的build方法中调用,请进入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)
════════════════════════════════════════════════════════════════════════════════════════════════════
您可以将a传递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
来创建一个BuildContext
脚手架的子代。
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButton: new Builder(
builder: (BuildContext context) {
return new FloatingActionButton(
onPressed: () {
Scaffold.of(context).showSnackBar(new SnackBar(
content: new Text("Sending Message"),
));
},
tooltip: 'Increment',
child: new Icon(Icons.add),
);
}
),
);
}
}
最后,您可以将窗口小部件分为多个类,这是最好的长期方法。
I/flutter ( 4965): The following assertion was thrown while handling a gesture: I/flutter ( 4965): type 'LabeledGlobalKey<ScaffoldState>' is not a subtype of type 'BuildContext' of 'context' where I/flutter ( 4965): LabeledGlobalKey is from package:flutter/src/widgets/framework.dart I/flutter ( 4965): ScaffoldState is from package:flutter/src/material/scaffold.dart I/flutter ( 4965): Scaffold is from package:flutter/src/material/scaffold.dart I/flutter ( 4965): BuildContext is from package:flutter/src/widgets/framework.dart
GlobalKey
作为BuildContext
预期的a参数。如果看不到更多代码,我无法帮助您进一步调试。请发布引发异常的代码行,可能您只是未使用正确的参数。
Builder
您提供的选项效果很好。遇到这个问题,这为我解决了。
final key = new GlobalKey<ScaffoldState>();
从Widget build之外进行了修复。
要显示吐司消息,您可以使用flutterToast插件来使用此插件,
fluttertoast: ^3.1.0
$ 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');
有关更多信息,请检查此
吐司:^ 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
);
我想提供使用包flushbar的替代解决方案。
https://github.com/AndreHaueisen/flushbar
如该软件包所述:如果在通知用户时需要更多自定义,请使用此软件包。对于Android开发人员而言,它可以替代烤面包和小吃店。
使用flushbar的另一个建议如何在Flutter中在navigator.pop(context)之后显示小吃栏?
您还可以将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);
如果到目前为止提供的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,但有可能在您检查时已经解决了。
pub.dartlang.org/packages/fluttertoast
插件。这个更简洁[简洁],更易于自定义。
有三种方法可以在Flutter App上显示吐司。
我将告诉您我所知道的所有三种方式,然后选择要使用的哪种方式。我会推荐第二个。
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编写本机代码,然后将其转换为插件,即可开始使用。这种方法会浪费您的时间,因此您必须重新发明轮子。已经被发明了。
对于那些正在寻找Toast
可以生存的路线的人来说,SnackBar
可能不是最佳选择。
看一下 Overlay
代替。
只需在诸如onTap和onPress之类的任何事件中使用SnackBar(content:Text(“ hello”),)
您可以在这里阅读有关Snackbar的更多信息https://flutter.dev/docs/cookbook/design/snackbars
为此,有不同的版本。
1)首先,可以使用Flutter中的小部件SnackBar。
2)您可以使用pub.dev中的toast,flutter_toast之类的库。
3)第三个版本正在创建您的自定义窗口小部件。可以使用叠加小部件和Flutter中的动画创建它。
您可以通过本教程来了解更多信息。这是一个链接
对于android原始图形吐司,您可以使用以下代码:https : //pub.dartlang.org/packages/fluttertoast
在Android和iOS上正常运行。 在此处输入图片说明
https://pub.dev/packages/toast使用此库进行烤面包这个库非常易于使用,并且非常适合ios和android,
show Toast的语法:
Toast.show("Toast plugin app", duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
你可以使用这个包:吐司
toast: ^0.1.5
import 'package:toast/toast.dart';
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
将此包添加到pubspec.yaml中的项目依赖项中
然后,只要您希望像按一下按钮一样显示Toast
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
您可以使用库“ 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());
导入 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();
},
)
],
);
});
很简单
我们只需要安装Flutter Toast软件包即可。请参阅以下文档:https : //pub.dev/packages/fluttertoast
在安装选项卡中,您将获得依赖项,您必须将该依赖项粘贴到pubspec.yaml中然后进行安装。
之后,只需导入软件包:
导入'package:fluttertoast / fluttertoast.dart';
与上面的行类似。
然后通过使用FlutterToast类,可以使用fluttertoast。
你完成了!!!
在Flutter中显示Toast消息非常容易。Scaffold.of(context).showSnackBar(SnackBar( content: Text("Toast Text Here"), ));