[flutter] How to create Toast in Flutter?

Can I create something similar to Toasts in Flutter? Just a tiny notification window that is not directly in the face of the user and does not lock or fade the view behind it?

This question is related to flutter dart toast android-toast

The answer is


just use SnackBar(content: Text("hello"),) inside any event like onTap and onPress

you can read more about Snackbar here https://flutter.dev/docs/cookbook/design/snackbars


For android original graphics toast you can use this: https://pub.dartlang.org/packages/fluttertoast

Works fine on Android and iOS. enter image description here


You can use something like FlutterToast

Import the lib

fluttertoast: ^2.1.4

Use like below

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

Thats it..


It's quite simple,

We just have to install the flutter toast package. Refer the following documentation: https://pub.dev/packages/fluttertoast

In the installing tab you will get the dependency which you have to paste it in the pubspec.yaml andthen install.

After this just import the package:

import 'package:fluttertoast/fluttertoast.dart';

Similar to above line.

And then by using FlutterToast class you can use your fluttertoast.

You're Done!!!


The answer Scaffold.of(context).showSnackBar(...) has not worked in most cases.

I suggest the optimal method be declaring a scaffoldState key within the class and assigning it to Scaffold like below

GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

and then

Scaffold(
  key: _scaffoldKey,
  ...
)

when you want to show the Snackbar do this..

_scaffoldKey.currentState.showSnackBar(SnackBar(
  content: Text("This works!"),
));

to show toast message you can use flutterToast plugin to use this plugin you have to

  1. Add this dependency to your pubspec.yaml file :- fluttertoast: ^3.1.0
  2. to get the package you have to run this command :- $ flutter packages get
  3. import the package :- import 'package:fluttertoast/fluttertoast.dart';

use it like this

Fluttertoast.showToast(
        msg: "your message",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM // also possible "TOP" and "CENTER"
        backgroundColor: "#e74c3c",
        textColor: '#ffffff');

For more info check this


Use this plugin

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

enter image description here


get flutter toast package here

Add this package to your project dependencies in pubspec.yaml

Then whenever you want the Toast to be shown like on a tap of a button

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

I would like to provide alternative solution to use package flushbar. https://github.com/AndreHaueisen/flushbar
As the package said: Use this package if you need more customization when notifying your user. For Android developers, it is made to substitute toasts and snackbars.
Another suggestion to use flushbar How to show snackbar after navigator.pop(context) in Flutter?
You can also set flushbarPosition to TOP or BOTTOM
enter image description here

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

Import the lib

fluttertoast: 3.1.3

Use like below

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

);


For the toast message in flutter use bot_toast library. This library provides Feature-rich, support for displaying notifications, text, loading, attachments, etc. Toast

enter image description here


SnackBar is definitely the right class to use, as pointed out by Darky.

snackbar

One tricky thing about showSnackBar is getting to the ScaffoldState, if you're trying to call showSnackBar within the build method where you construct your Scaffold.

You might see an error like this, which includes some text explaining how to solve the problem.

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

You can either pass a GlobalKey to your Scaffold constructor:

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

Or you can use a Builder to create a BuildContext that is a child of the 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),
          );
        }
      ),
    );
  }
}

Finally, you could split your widget into multiple classes, which is the best long-term approach.


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

you can use this package : toast

add this line to your dependencies

toast: ^0.1.5

then use it like this :

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

use this dependency: toast: ^0.1.3 then import the dependency of toast in the page : import 'package:toast/toast.dart'; then on onTap() of the widget: Toast.show("Toast plugin app", context,duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);


There's no widget for toast in flutter, You can go to this plugin Usecase:

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

Use this

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

For the ones that are looking for a Toast what can survive the route changes the SnackBar might not be the best option.

Have a look at Overlay instead.

https://api.flutter.dev/flutter/widgets/Overlay-class.html


Import cupertino_icons: ^0.1.2 and Write below code

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

https://pub.dev/packages/toast use this for toast this library is pretty easy to use and perfect work for ios and android,

Syntax for show Toast:

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

In case the Fluttertoast package given so far doesnt work... Then I will suggest you try toast.
It has no frills and no ceremony.

enter image description here

It just works.

I noticed a bug within the example given within its Readme though:

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

While the method requires a context. So do well to add 'context' like this:

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

There is a chance that this would have been fixed by the time you checked though, I already submitted a PR.


For this, there are different versions.

1) First of all, you can use SnackBar which is a widget in Flutter.

2) You can use libraries like toast, flutter_toast from pub.dev.

3) Third version is creating your custom widget. It can be created using Overlay widget and Animation in Flutter.

You can this this tutorial to learn more about it. Here is a link


You can use library "fluttertoast". To do this, add it in pubspec.yaml file like:

dependencies:
  fluttertoast: ^3.1.0

Then import that library in the dart file you need the toast and write your code. For example, refer to the following code:

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

Add flutter_just_toast to your dependencies in your Pubspecs.yaml

dependencies:

flutter_just_toast: ^1.0.1

Next import package into your class:

import 'package:flutter_just_toast/flutter_just_toast.dart';

Implement Toast with message

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

There is a three-way to show toast on flutter App.
I will tell you about all three way that I know and choose which one you want to use. I would recommend the second one.

1: using of the external package.

this is the first method which is the easiest way to show toast on flutter app.

first of all, you have to add this package to pubspec.YAML

flutter_just_toast:^version_here

then import the package in the file where you want to show a toast.

'package:flutter_just_toast/flutter_just_toast.dart';

and the last step shows the toast.

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

2 : using official way.

this method is also simple but you have to deal with it. I am not saying that it is hard it is simple and clean I would recommend this method.

for this method, all you have to do show toast is using the below code.

Scaffold.of(context).showSnackBar(SnackBar(
          content: Text("Sending Message"),
        ));

but remember that you have to use the scaffold context.

3: using native API.

now, this method does not make sense anymore when you already have the two methods above. using this method you have to write native code for android and iOS and then convert it to plugin and you are ready to go. this method will consume your time and you have to reinvent the wheel. which has already been invented.


You can use flutter commons package to display different types of toasts like success, error, warning and info in flutter applications.

successToast("Success Message");

It's quite Easy to show a Toast Message in Flutter.Scaffold.of(context).showSnackBar(SnackBar( content: Text("Toast Text Here"), ));


Step 1:

dependencies:

flutter_just_toast: ^1.0.1

Step 2:

import 'package:flutter_just_toast/flutter_just_toast.dart';

Step 3:

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


Snack Bar

When I tried to use solution with using ScaffoldState object (suggested by others), I got a warning that it is deprecated:

'showSnackBar' is deprecated and shouldn't be used. Use ScaffoldMessenger.showSnackBar. This feature was deprecated after v1.23.0-14.0.pre..

Using ScaffoldMessenger works as expected:

ScaffoldMessenger.of(context)
    .showSnackBar(SnackBar(content: Text("My amazing message! O.o")));

Example:

Snack bar message


You can use this link to show Toast in Flutter. Use this as :--

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

Examples related to flutter

Flutter Countdown Timer How to make an AlertDialog in Flutter? FlutterError: Unable to load asset Set the space between Elements in Row Flutter Flutter: RenderBox was not laid out Space between Column's children in Flutter How to change status bar color in Flutter? How can I add shadow to the widget in flutter? Flutter - The method was called on null Flutter- wrapping text

Examples related to dart

How to integrate Dart into a Rails app Flutter Countdown Timer How to make an AlertDialog in Flutter? Set the space between Elements in Row Flutter Flutter: RenderBox was not laid out Space between Column's children in Flutter How to change status bar color in Flutter? How can I add shadow to the widget in flutter? Flutter - The method was called on null Flutter- wrapping text

Examples related to toast

How to create Toast in Flutter? java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(); Custom toast on Android: a simple example Use Toast inside Fragment Call to getLayoutInflater() in places not in activity How to display Toast in Android? How to change position of Toast in Android?

Examples related to android-toast

How to create Toast in Flutter? Can't create handler inside thread that has not called Looper.prepare() How do you display a Toast from a background thread on Android? Can an Android Toast be longer than Toast.LENGTH_LONG?