我可以在Flutter中创建类似Toasts的东西吗?
只是一个很小的通知窗口,不直接面对用户,也不锁定或淡出它后面的视图。
我可以在Flutter中创建类似Toasts的东西吗?
只是一个很小的通知窗口,不直接面对用户,也不锁定或淡出它后面的视图。
当前回答
Importcupertino_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: [
CupertinoButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
});
其他回答
正如Darky指出的那样,SnackBar绝对是正确的类。
关于showSnackBar的一个棘手的事情是到达Scaffold state,如果你试图在构建方法中调用showSnackBar。
您可能会看到这样的错误,其中包括一些解释如何解决问题的文本。
══╡ 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来创建一个BuildContext,它是Scaffold的子对象。
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),
);
}
),
);
}
}
最后,您可以将小部件分成多个类,这是最佳的长期方法。
使用这个依赖:
toast: ^0.1.3
然后在页面中导入toast的依赖关系:
import 'package:toast/toast.dart';
然后在小部件的onTap()上:
Toast.show("Toast plugin app", context, duration:Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
在Flutter应用程序中有一个三种方式来显示吐司。
我会告诉你我所知道的三种方法,并选择你想要使用的一种。我推荐第二种。
1:使用外挂包。
这是第一个方法,这是最简单的方法显示吐司在Flutter应用程序。
首先,您必须将这个包添加到文件pubspec中。YAML:
flutter_just_toast:^version_here
然后在您想要显示toast的文件中导入该包。
'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编写本地代码,然后将其转换为插件,你就可以开始了。
这种方法会消耗你的时间,你必须重新发明轮子。这已经被发明出来了。
更新:Scaffold.of(上下文)。showSnackBar在Flutter 2.0.0中已弃用(稳定)
你可以使用ScaffoldMessenger.of(context)访问父类ScaffoldMessengerState。
然后做一些类似的事情
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Sending Message"),
));
零食条是材料设计的官方“吐司”。看到间小吃店。
下面是一个完整的例子:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: 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'),
),
body: Center(
child: RaisedButton(
onPressed: () => _showToast(context),
child: const Text('Show toast'),
),
),
);
}
void _showToast(BuildContext context) {
final scaffold = ScaffoldMessenger.of(context);
scaffold.showSnackBar(
SnackBar(
content: const Text('Added to favorite'),
action: SnackBarAction(label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
),
);
}
}
小吃店
当我尝试使用脚手架状态对象(由其他人建议)的解决方案时,我得到了一个警告,它已弃用:
'showSnackBar'已弃用,不应该使用。使用ScaffoldMessenger.showSnackBar。此特性在v1.23.0-14.0.pre..之后已弃用。
使用ScaffoldMessenger可以正常工作:
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("My amazing message! O.o")));
例子: