How to show Toast Message on Button Click in Flutter App

Toast is the best way to show the message in Flutter because it gets dismissed automatically, doesn’t affect any other UI components, and looks app interactive. See the example below and learn to show the Toast message when a button is pressed or on any action.

To show Toast message, you need to add fluttertoast Flutter package in dependency by adding the following line in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  fluttertoast: ^4.0.0

You can show toast by using the following code:

Fluttertoast.showToast(
   msg: message, //message to show toast
   toastLength: Toast.LENGTH_LONG, //duration for message to show
   gravity: ToastGravity.CENTER, //where you want to show, top, bottom
   timeInSecForIosWeb: 1, //for iOS only
   //backgroundColor: Colors.red, //background Color for message
   textColor: Colors.white, //message text color
   fontSize: 16.0 //message font size
);

Cancel all Toast using:

Fluttertoast.cancel();

Show toast on Button Click (Full Code):

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';

void main() {
  runApp(MyApp()); 
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Test App",
        home: ShowToast(),
    );
  }
}

class ShowToast extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar( 
         title: Text("Show Toast on Flutter"),
         backgroundColor: Colors.redAccent,
       ),
       body: Container( 
           height: 150,
           alignment: Alignment.center, //align content to center
           padding: EdgeInsets.all(20),
           child:RaisedButton(
             onPressed: (){
                showToastMessage("Show Toast Message on Flutter");
             },
             colorBrightness: Brightness.dark, //background color is dark
             color: Colors.redAccent, //set background color is redAccent
             child: Text("Show Toast Message"),
           ),
       )
    );
  }

  //create this function, so that, you needn't to configure toast every time
  void showToastMessage(String message){
     Fluttertoast.showToast(
        msg: message, //message to show toast
        toastLength: Toast.LENGTH_LONG, //duration for message to show
        gravity: ToastGravity.CENTER, //where you want to show, top, bottom
        timeInSecForIosWeb: 1, //for iOS only
        //backgroundColor: Colors.red, //background Color for message
        textColor: Colors.white, //message text color
        fontSize: 16.0 //message font size
    );
  }

}

Output Screenshot:

In this way, you can show toast message with button click and make your app more interactive.

No any Comments on this Article


Please Wait...