How to create SnackBar in Flutter | SnackBar Tutorial
In this article, we will create and display different types of SnackBars in Flutter.
SnackBars in Flutter
SnackBars are used to briefly display some information or inform the user about an action. For instance, when a user deletes a mail or message you may want to inform the user about the action. Also, the user can undo the action he performed by the undo button in the Snackbar.
Syntax
For creating a SnackBar, we use the following code.
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: content));
Inside the content field of SnackBar, we will pass the content. Any content can be passed inside it, but in practice, small messages with or without a button.
Example
Simple SnackBar
class SnackBarTutorial extends StatelessWidget {
const SnackBarTutorial({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("SnackBar Tutorial"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Welcome to AllAboutFlutter"),
),
);
},
child: const Text("Create SnackBar"),
)
],
),
),
);
}
}
Output
Custom SnackBar
There are many parameters to customize a SnackBar.
Modify the code as follows.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
behavior: SnackBarBehavior.floating,
content: const Text("Welcome to AllAboutFlutter"),
backgroundColor: Colors.orangeAccent,
margin: const EdgeInsets.all(12.0),
elevation: 2.0,
duration: const Duration(seconds: 2),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
Output
Summary
In this tutorial, we learnt to create s simple SnackBar as well as a custom SnackBar.
Subscribe to my newsletter
Read articles from Manav Sarkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by