如何在Flutter中创建Toast?


166

我可以在Flutter中创建类似于Toasts的东西吗?只是一个很小的通知窗口,它不直接在用户面前,并且不会锁定或淡化后面的视图?

Answers:


204

您可以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),
      ),
    );
  }
}

1
例如,如何将其包装在onPressed中?因为我尝试过,但屏幕上没有任何显示。
aziza

好吧,我从不适合自己,我知道“官方”并不意味着绝对!Snackbar非常适合我的应用UX,因此我始终保持清醒状态,并始终实施较早的浮动弹出式通知。我觉得用户很容易错过Snackbar通知(特别是如果他们不习惯的话);但是想念一个悬浮在屏幕中间,顶部或底部的弹出窗口并不容易。
SilSur

@aziza将您的按钮小部件包装到Builder()中,它将起作用
Tabrizapps

小部件调用showSnackBar()应有一个Scaffold父项。
Lahiru Chandima

80

使用这个插件

Fluttertoast.showToast(
        msg: "This is Toast messaget",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1
    );

在此处输入图片说明


2
您必须首先在pubspec.yaml文件中添加Fluttertoast依赖项。到依赖项的链接在这里[link](pub.dartlang.org/packages/fluttertoast)。然后,您可以使用上面的代码
fritz-playmaker '18

Unhandled Exception: MissingPluginException(No implementation found for method showToast on channel PonnamKarthik/fluttertoast)
罗宾

1
现在它可以工作了,我需要停止应用程序并运行🏃‍♂️而不进行调试:)
Robin

任何人都面临在设置bg颜色后禁用圆形边框的问题 github.com/PonnamKarthik/FlutterToast/issues/156
thanhbinh84

73

SnackBar 正如Darky所指出的那样,绝对是使用正确的类。

小吃店

关于棘手的事情showSnackBarScaffoldState,如果您试图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传递GlobalKeyScaffold构造函数:

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),
          );
        }
      ),
    );
  }
}

最后,您可以将窗口小部件分为多个类,这是最好的长期方法。


尝试过GlobalKey,现在我得到了这个例外: 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
Shajeel Afzal

1
看来您正在使用a GlobalKey作为BuildContext预期的a参数。如果看不到更多代码,我无法帮助您进一步调试。请发布引发异常的代码行,可能您只是未使用正确的参数。
科林·杰克逊

2
我可以确认使用Builder您提供的选项效果很好。遇到这个问题,这为我解决了。
SeaFuzz

我在使用GlobalKey方法时遇到错误,但是将声明final key = new GlobalKey<ScaffoldState>();从Widget build之外进行了修复。
Sagar V

StackOverflow最好的答案之一!感谢@CollinJackson
Masterfego

13

要显示吐司消息,您可以使用flutterToast插件来使用此插件,

  1. 将此依赖项添加到您的pubspec.yaml文件中: fluttertoast: ^3.1.0
  2. 要获取软件包,您必须运行以下命令:- $ flutter packages get
  3. 导入包:- 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');

有关更多信息,请检查


24
与其回答别人发布的相同答案,不如对他的答案进行投票。
CopsOnRoad '18

7

吐司:^ 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
    );

请尝试添加一两个描述性语句,以描述在哪里放置哪些代码。诸如“将包添加到pubspec中”和“在代码中,使用:”之类的东西
mlyko

6

我想提供使用包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);

5

导入库

吐司:3.1.3

如下使用

Fluttertoast.showToast(
msg: "Hello world",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,

);


4

如果到目前为止提供的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插件。这个更简洁[简洁],更易于自定义。
SilSur

2

有三种方法可以在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编写本机代码,然后将其转换为插件,即可开始使用。这种方法会浪费您的时间,因此您必须重新发明轮子。已经被发明了。



1

将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);


1

为此,有不同的版本。

1)首先,可以使用Flutter中的小部件SnackBar。

2)您可以使用pub.dev中的toast,flutter_toast之类的库。

3)第三个版本正在创建您的自定义窗口小部件。可以使用叠加小部件和Flutter中的动画创建它。

您可以通过本教程来了解更多信息。这是一个链接




0

第1步:

依赖项:

flutter_just_toast: ^1.0.1

第2步:

import 'package:flutter_just_toast/flutter_just_toast.dart';

第三步:

Toast.show(
message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);


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);


0

你可以使用这个包:吐司

将此行添加到您的依赖项

toast: ^0.1.5

然后像这样使用它:

import 'package:toast/toast.dart';
Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);

0

在这里拿起吐司面包包

将此包添加到pubspec.yaml中的项目依赖项中

然后,只要您希望像按一下按钮一样显示Toast

Toast.show("Toast plugin app", context, duration: Toast.LENGTH_SHORT, gravity:  Toast.BOTTOM);

0

在flutter中没有用于烤面包的小部件,您可以转到此插件 Usecase:

Fluttertoast.showToast(
msg: "My toast messge",
textColor: Colors.white,
toastLength: Toast.LENGTH_SHORT,
timeInSecForIos: 1,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.indigo,);

0

您可以使用库“ 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());

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();
              },
            )
          ],
        );
      });


0

很简单

我们只需要安装Flutter Toast软件包即可。请参阅以下文档:https : //pub.dev/packages/fluttertoast

在安装选项卡中,您将获得依赖项,您必须将该依赖项粘贴到pubspec.yaml中然后进行安装。

之后,只需导入软件包:

导入'package:fluttertoast / fluttertoast.dart';

与上面的行类似。

然后通过使用FlutterToast类,可以使用fluttertoast。

你完成了!!!



-2

您可以使用FlutterToast之类的东西

导入库

fluttertoast: ^2.1.4

如下使用

Fluttertoast.showToast(
    msg: "Hello world",
    textColor: Colors.white,
    toastLength: Toast.LENGTH_SHORT,
    timeInSecForIos: 1,
    gravity: ToastGravity.BOTTOM,
    backgroundColor: Colors.indigo,
);

而已..

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.