Flutter - Show Toast Message Example

This is a tutorial of how to display toast message on Flutter application which works on Android and iOS.

Toast has been used as a standard way to show flash message in Android. Moreover, some iOS apps also implement it. If you're developing application using Flutter and want to display toast for both platforms, this tutorial will show you how to do so.

Dependencies

The easiest way is using a library called fluttertoast. It has the capability to show toast message in a simple way and customize the look of the toast popup.

First, add it to the pubspec.yaml file of your project, on the dependencies section and run Packages Get.

pubspec.yml

  dependencies:
    fluttertoast: ^3.1.0

To display toast using that library, call its Fluttertoast.showToast method which is available after adding import 'package:fluttertoast/fluttertoast.dart'; to the dart file where you want to call the method.

OptionDescription
String msg (required)The message to be displayed
Toast toastLengthHow long the it will be displayed. Values:
  • Toast.LENGTH_SHORT (default)
  • Toast.LENGTH_LONG
int timeInSecForIosHow long the it will be displayed in iOS (default is 1 second)
double fontSizeThe font size (default is 16.0)
ToastGravity gravityVertical gravity. Values:
  • ToastGravity.TOP
  • ToastGravity.CENTER
  • ToastGravity.BOTTOM (default)
Color backgroundColorThe background color
Color textColorThe text color

In the below example, there is a button that will trigger to display a toast message when it's pressed by calling FlutterToast.showToast.

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