Snackbar for Notifications in Flutter
Snackbars are an essential part of user interaction in mobile applications. They provide brief messages at the bottom of the screen to notify users about actions, processes, or alerts. This guide will cover everything you need to know about implementing and customizing Snackbars in Flutter.
What is a Snackbar?
A Snackbar is a lightweight, unobtrusive notification that appears temporarily on the screen. It is typically used to inform users about actions like "Message Sent," "File Deleted," or "Action Completed." Snackbars are a part of Flutter's Material Design framework.
Why Use Snackbars?
- Quick Notifications: Ideal for short messages without interrupting the user’s flow.
- Actionable Feedback: Can include actions like "Undo" or "Retry."
- Transient: Automatically disappears after a specified duration.
- Customizable: You can style them to fit your app's theme.
How to Implement Snackbars in Flutter
1. Basic Implementation
The Scaffold
widget provides the ScaffoldMessenger
which is used to display Snackbars.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Snackbar Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// Displaying a Snackbar
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('This is a Snackbar notification!'),
),
);
},
child: Text('Show Snackbar'),
),
),
);
}
}
Key Components of Snackbar
content
: The main text or widget displayed inside the Snackbar.
Example:Text('Item added to cart')
action
: An optional button for user interaction, like "Undo" or "Retry."
Example:
duration: Duration(seconds: 2),
3. duration
: The time for which the Snackbar is visible.
Default is 4 seconds. You can customize it:
Customizing Snackbar
Snackbars can be styled to match your app's theme.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Custom Snackbar!',
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.green,
behavior: SnackBarBehavior.floating, // Makes the Snackbar float
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
),
);
Using Global Key for Snackbar
For more control over where the Snackbar appears, use a GlobalKey.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final GlobalKey<ScaffoldMessengerState> _scaffoldKey =
GlobalKey<ScaffoldMessengerState>();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('Snackbar with GlobalKey'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_scaffoldKey.currentState?.showSnackBar(
SnackBar(content: Text('Global Key Snackbar!')),
);
},
child: Text('Show Snackbar'),
),
),
),
);
}
}
Common Errors and Solutions
- Snackbar Not Showing: Ensure you're calling
ScaffoldMessenger.of(context).showSnackBar()
within a validBuildContext
that contains aScaffold
. - Multiple Snackbars Overlapping: Add
ScaffoldMessenger.of(context).clearSnackBars()
before showing a new Snackbar to dismiss any existing ones.
Best Practices for Using Snackbars
- Short and Informative Messages: Keep the message concise.
- Don’t Overuse: Use them sparingly to avoid overwhelming the user.
- Avoid Critical Notifications: Use dialogs for critical information instead.
- Provide Actions Wisely: Include actions only if they enhance user experience (e.g., Undo).
Complete Example
Here’s a complete example demonstrating a styled Snackbar with an action.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SnackbarExample(),
);
}
}
class SnackbarExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Snackbar Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('This is a styled Snackbar!'),
action: SnackBarAction(
label: 'Retry',
textColor: Colors.yellow,
onPressed: () {
// Retry action
},
),
duration: Duration(seconds: 3),
backgroundColor: Colors.blueGrey,
behavior: SnackBarBehavior.floating,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
},
child: Text('Show Snackbar'),
),
),
);
}
}
Conclusion
Snackbars are an excellent tool for delivering transient feedback to users in a Flutter app. By mastering their implementation and customization, you can enhance your app’s user experience significantly. Experiment with different styles, durations, and actions to tailor Snackbars to your app's needs!