How To Show Message in Flutter

Showing messages is an essential feature in any mobile application to display feedback, prompt user for action, and show error.

Flutter provides various types of messages that you can display for users for different purposes. To show message in Flutter, you can use Flutter Toast, Flutter Snackbar, and Flutter Alert dialog. Each of these is used for different purpose and is implemented differently.

In this tutorial, we’ll learn how to show Toast in Flutter, how to show Snackbar in Flutter, and how to show alert dialog box in Flutter.

Table of Contents

Toast message in Flutter

Flutter Toast message is a flash small message that displays information to the user for a short period of time. By default, Toast message appears at the bottom of the screen. It appears for seconds to notify user about operation status and provide feedback upon task completion. For example, you can display a toast message to notify user about completion of registration process. It helps in improving the overall user experience of the application as it helps in keeping the user aware of operations status. It us usually implemented using FlutterToast package.

Toast properties

PropertyDescription
msgdefines the toast text (required)
toastLengthspecifies the duration of the toast. It takes 2 values which are Toast.LENGTH_SHORT and Toast.LENGTH_LONG
textColordefines the text color. For example Colors.white
fontSizedefines the text size
gravityspecifies the position of the toast message. It takes 3 main values which are ToastGravity.TOP, ToastGravity.BOTTOM, and ToastGravity.CENTER
backgroundColorspecifies the background color. For example Colors.red

Flutter Toast example

First of all, you need to add the FlutterToast dependency to the pubspec.yaml file in your Flutter project

fluttertoast: ^8.0.9

Then, import the library in the dart file where you’ll implement it

import 'package:fluttertoast/fluttertoast.dart';

Now, let’s write the code to display the toast message

Center(
child: ElevatedButton(
child: Text('Show Message', style: TextStyle(fontSize: 20),),
onPressed: (){
Fluttertoast.showToast(
msg: 'This is a toast message',
gravity: ToastGravity.BOTTOM,
fontSize: 20,
textColor: Colors.white,
backgroundColor: Colors.blue,
toastLength: Toast.LENGTH_LONG,
);
},
),
)
show toast in flutter

Flutter Toast with Icon

Now, to display a toast message with an icon, we can use the FToast from the same package we’re using FlutterToast. This requires a child widget instead of the text widget that we used earlier.

First, we need to create a FToast variable right after the class initiation.

late FToast fToast;

Then, we need to initiate it inside the initState() function

@override
void initState() {
super.initState();
fToast = FToast();
fToast.init(context);
}

Now, let’s create a function called _showToast() that will create and display the toast message.

_showToast() {
Widget toast = Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.blue,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.check, color: Colors.white,),
SizedBox(
width: 12.0,
),
Text('Completed!', style: TextStyle(fontSize: 24, color: Colors.white),),
],
),
);


fToast.showToast(
child: toast,
gravity: ToastGravity.BOTTOM,
toastDuration: Duration(seconds: 2),
);

}

Then, we only need to call it in the onPressed() function inside the OutlinedButton we created earlier.

onPressed: (){
_showToast();
},
flutter toast with icon

Flutter Snackbar

Snackbar in Flutter is a widget that shows a short message with an optional action to the user at the bottom of the screen. It’s a way to show message in Flutter that’s similar to Toast message except that it has an optional action and it’s the official form of message that Flutter provides. The optional action may be undo a certain event or dismiss a notification. For example, you can display a snackbar when the user adds an item to the cart with an optional action to undo that. It’s recommended to display the snackbar for no longer than 10 seconds to avoid distracting the user.

Snackbar constructor

SnackBar({Key key, 
@required Widget content, 
Color backgroundColor, 
double elevation, 
EdgeInsetsGeometry margin, 
EdgeInsetsGeometry padding, 
double width, 
ShapeBorder shape, 
SnackBarBehavior behavior, 
SnackBarAction action, 
Duration duration: _snackBarDisplayDuration, 
Animation<double> animation, 
VoidCallback onVisible})

Snackbar properties

PropertyDescription
contentthe main content that the snackbar shows, usually a text.
durationdefines the amount of time the snackbar displayed for
actiondefines the action that takes place when the user taps on the snackbar.
shapecustomize the shape of the snackbar
elevationcontrols the shadow below the snackbar
backgroundColorspecifies the color of the snackbar background
behaviordefines the location of the snackbar
animation

controls how the snackbar enters and exists the screen

Flutter Snackbar example

ElevatedButton(
child: Text('Show Snackbar', style: TextStyle(fontSize: 20),),
onPressed: (){
var snackbar = SnackBar(
content: Text('I am a SnackBar'),
elevation: 16,
backgroundColor: Colors.blueGrey,
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.all(10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25)
),
duration: Duration(seconds: 10),
action: SnackBarAction(
label: 'Dismiss',
onPressed: () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
},
),

);

ScaffoldMessenger.of(context).showSnackBar(snackbar);
},
)
flutter snackbar

Alert Dialog Box in Flutter

An alert dialog is a pop up message that appears to display important information to the user to make a decision. It appears on top of the screen in the middle section and it sticks there until the user manually closes it. Alert dialog has a title, content, and optional list of actions. The content may consist of text widgets, text fields, buttons, etc. Alert dialogs are usually used to confirm an action that’s about to occur. For example, deleting an item from cart or logging out.

Alert Dialog constructor

AlertDialog(
{
   Key key,
   Widget title,
   EdgeInsetsGeometry titlePadding,
   TextStyle titleTextStyle,
   Widget content,
   EdgeInsetsGeometry contentPadding: const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
   TextStyle contentTextStyle,
   List<Widget> actions,
   EdgeInsetsGeometry actionsPadding: EdgeInsets.zero,
   VerticalDirection actionsOverflowDirection,
   double actionsOverflowButtonSpacing,
   EdgeInsetsGeometry buttonPadding,
   Color backgroundColor,
   double elevation,
   String semanticLabel,
   EdgeInsets insetPadding: _defaultInsetPadding,
   Clip clipBehavior: Clip.none,
   ShapeBorder shape,
   bool scrollable: false
 }
)

Alert Dialog properties

PropertyDescription
titlespecifies the title to be displayed at the top
contentdefines the content of the dialog. It can be text, text fields, etc.
actionstakes a list of actions, usually buttons, which are displayed at the bottom of the dialog
backgroundColorspecifies the background color
shapedefines the shape of the dialog’s border
elevationdefines the size of the shadow below the alert dialog

Flutter Alert Dialog Example

Alert dialog comes in different forms and types including confirmation dialog, input requires dialogs, options dialogs, and so on. The content of the alert dialog varies based on its type and it develops from simple to more complex content. In today’s tutorial, we’ll go through examples on few dialogs types.

Information Alert Dialog

This is an alert dialog that simply displays an important information that requires the user’s acknowledgement. It only disappears when the user clicks on the OK button.

showAlertDialog(BuildContext context) {
//ok button
Widget okButton = ElevatedButton(

onPressed: () {
//action to be taken
Navigator.of(context).pop();
},
child: Text('Dismiss'),
style: ElevatedButton.styleFrom(primary: Colors.indigo),

);





AlertDialog alert = AlertDialog(
title: Text('Item removed'),
content: Text('The item has been successfully removed from your cart'),
actions: [
okButton,
],
backgroundColor: Colors.grey[200],
);

showDialog(context: context, builder: (BuildContext context) {
return alert;
});


}
information alert dialog

Confirmation Alert Dialog

This is an alert dialog that appears to get the user’s confirmation to perform a specific action. For example, when deleting an item or downloading a file.

showAlertDialog(BuildContext context) {
//ok button
Widget okButton = ElevatedButton(

onPressed: () {
//action to be taken
Navigator.of(context).pop();
},
child: Text('Delete'),
style: ElevatedButton.styleFrom(primary: Colors.indigo),

);


Widget cancelButton = ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Cancel'),
style: ElevatedButton.styleFrom(primary: Colors.indigo),
);


AlertDialog alert = AlertDialog(
title: Text('Delete Account?'),
content: Text('This will permanently delete your account'),
actions: [
okButton,
cancelButton
],
backgroundColor: Colors.grey[200],
);

showDialog(context: context, builder: (BuildContext context) {
return alert;
});


}
confirmation lert dialog

Input Alert Dialog

This is an alert dialog that appears to get an input from the user. For example, when the user needs to input a verfication code to complete a transaction.

TextEditingController _textFieldController = TextEditingController();

showAlertDialog(BuildContext context) {
//ok button
Widget okButton = ElevatedButton(

onPressed: () {
//action to be taken
Navigator.of(context).pop();
},
child: Text('Done'),
style: ElevatedButton.styleFrom(primary: Colors.indigo),

);

TextField input = TextField(
controller: _textFieldController,
decoration: InputDecoration(
hintText: 'Verification code',

),
);
AlertDialog alert = AlertDialog(
title: Text('Enter Verification Code'),
content: input,
actions: [
okButton,
],
backgroundColor: Colors.grey[200],
);

showDialog(context: context, builder: (BuildContext context) {
return alert;
});


}
input alert dialog

Select option Alert Dialog

This is an alert dialog that prompts user to select an option from multiple options the screens. You can implement alert dialog with options using the AlertDialog widget but it’s recommended to use other type of alert dialog which is called SimpleDialog. SimpleDialog provides an easier and simpler way to add selective option to the dialog. choices are displayed using the SimpleDialogOption widget.

showSimpleDialog(BuildContext context)  async{
_selectedOption = await showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: Text('Select your favorite color!'),
elevation: 10,
children: [
SimpleDialogOption(
child: Text('Red'),
onPressed: () {
//action
Navigator.pop(context, 'Red');
},
),

SimpleDialogOption(
child: Text('Blue'),
onPressed: () {
//action
Navigator.pop(context, 'Blue');
},
),

SimpleDialogOption(
child: Text('Green'),
onPressed: () {
//action
Navigator.pop(context, 'Green');
},
),

SimpleDialogOption(
child: Text('Black'),
onPressed: () {
//action
Navigator.pop(context, 'Black');
},
),
],
);
}
);

setState(() {
_selectedOption = _selectedOption;
});
}

and here’s the code for the UI

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Alert Dialog Example'),
centerTitle: true,
),
body: Column(
children: [
SizedBox(height: 20,),
Text('Currently Selected = ' + _selectedOption, style: TextStyle(fontSize: 30),),
SizedBox(height: 30,),
Center(
child: ElevatedButton(
child: Text('Show Alert Dialog', style: TextStyle(fontSize: 20),),
onPressed: (){
showSimpleDialog(context);
},
),
),
],
)
);
}
alert dialog with option

Flutter Custom Alert Dialog

you’d want to create your custom widgets with your own design from time to time. It’s common to create custom alert dialogs for more advanced look and features. You can do so by creating a separate widget from scratch then add it to your UI.

In the below example, I created a separate file customAlertDialog.dart and implemented a stateless widget called CustomAlertDialog.

import 'package:flutter/material.dart';

class CustomAlertDialog extends StatelessWidget {
const CustomAlertDialog({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),

child: Stack(
alignment: Alignment.topCenter,
overflow: Overflow.visible,
children: [
Container(
height: 230,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 70,10,10),
child: Column(
children: [
Text('Success!', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), textAlign: TextAlign.center,),
SizedBox(height: 5,),
Text('You have successfully downloaded the file', style: TextStyle(fontSize: 20, ),textAlign: TextAlign.center),
SizedBox(height: 20,),
ElevatedButton(
style: ElevatedButton.styleFrom(primary: Colors.indigo),
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK', style: TextStyle(color: Colors.white),))
],
),
),
),
Positioned(
top: -60,
child: CircleAvatar(
backgroundColor: Colors.indigo,
radius: 50,
child: Icon(
Icons.check,
size: 50,
color: Colors.white,
),
),
)
],
),
);
}
}

Then, in the file where I implemented the UI, I called showDialog() function

ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return CustomAlertDialog();
}

);
},

child: Text('Display Custom Alert Dialog'),
)
flutter custom alert dialog

Conclusion

Wooo, you’ve just learnt how to show toast message in Flutter!, how to show Snackbar in Flutter, and how to show an alert in Flutter, too.

It’s very good to know how to implement them in your application as you’ll need them for sure!

If you wish to learn more about Flutter, I have a whole category called Flutter that’s ripe for you to explore. You can learn about Flutter widgets, layouts, onboarding screen, tabbar, inkwell and gesture detector, stepper and practice with a bunch of real examples.

Also, don’t forget to like and share my Facebook page, share the post with those who care to learn, and subscribe to my blog to be one of the firsts to know about my newest posts!

Thank you!

Oh hi there!
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

Let's Do This!

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top