Flutter Toast is an essential UI component that provides quick feedback to users in Flutter applications. When developing Flutter apps, showing toast messages is crucial for displaying temporary notifications, success messages, error alerts, and user feedback. Flutter Toast allows developers to create non-intrusive popup messages that appear briefly on the screen and automatically disappear after a specified duration. Understanding how to implement Flutter Toast effectively can significantly enhance your app’s user experience and provide seamless communication between your Flutter application and its users.
Toast messages in Flutter serve as lightweight notifications that don’t interrupt the user’s workflow while still delivering important information. Whether you’re building a simple Flutter app or a complex enterprise application, mastering Flutter Toast implementation is fundamental for creating professional and user-friendly interfaces.
Flutter Toast refers to small popup messages that appear on the screen temporarily to provide feedback or information to users. These toast notifications are commonly used in mobile applications to show status updates, confirmations, warnings, or simple messages without requiring user interaction. Flutter Toast messages typically appear at the bottom of the screen by default, though their position can be customized based on your application’s needs.
The concept of toast messages originated from Android development, where Toast notifications provide a simple way to display brief messages. In Flutter development, toast functionality can be implemented using various packages and libraries, with fluttertoast
being the most popular and widely adopted solution for creating toast messages in Flutter applications.
Flutter Toast messages are designed to be non-modal, meaning they don’t block user interaction with the underlying interface. This makes them perfect for showing quick feedback without disrupting the user’s current task or navigation flow.
Flutter Toast offers numerous customization properties that allow developers to create tailored toast experiences for their applications. Understanding these properties is essential for implementing effective toast notifications.
The msg
property defines the text content displayed in the Flutter Toast. This is the primary property that contains the actual message you want to show to users.
Fluttertoast.showToast(
msg: "This is a Flutter Toast message"
);
The toastLength
property determines how long the Flutter Toast remains visible on screen. Flutter Toast supports two duration options: Toast.LENGTH_SHORT
for brief messages and Toast.LENGTH_LONG
for extended visibility.
Fluttertoast.showToast(
msg: "Short duration toast",
toastLength: Toast.LENGTH_SHORT
);
The gravity
property controls the position where Flutter Toast appears on the screen. You can position toast messages at the top, center, or bottom of the screen using ToastGravity.TOP
, ToastGravity.CENTER
, or ToastGravity.BOTTOM
.
Fluttertoast.showToast(
msg: "Toast at top of screen",
gravity: ToastGravity.TOP
);
Flutter Toast allows customization of background colors using the backgroundColor
property. This enables you to match toast messages with your app’s theme and branding.
Fluttertoast.showToast(
msg: "Colored background toast",
backgroundColor: Colors.red
);
The textColor
property lets you customize the color of text displayed in Flutter Toast messages, ensuring proper contrast and readability.
Fluttertoast.showToast(
msg: "Custom text color",
textColor: Colors.white
);
Flutter Toast supports font size customization through the fontSize
property, allowing you to adjust text size based on your design requirements.
Fluttertoast.showToast(
msg: "Large font toast",
fontSize: 18.0
);
To use Flutter Toast in your Flutter application, you need to add the fluttertoast dependency to your project’s pubspec.yaml
file. The fluttertoast package is the most reliable and feature-rich solution for implementing toast messages in Flutter apps.
Add the following dependency to your pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
fluttertoast: ^8.2.4
After adding the dependency, run flutter pub get
to install the Flutter Toast package. Once installed, you can import the package in your Dart files where you want to use Flutter Toast functionality.
import 'package:fluttertoast/fluttertoast.dart';
The fluttertoast package provides seamless integration with both Android and iOS platforms, ensuring consistent toast behavior across different devices and operating systems.
Implementing basic Flutter Toast messages is straightforward once you have the package configured. The simplest way to show a Flutter Toast is by calling the Fluttertoast.showToast()
method with a message parameter.
Here’s how to create a basic Flutter Toast:
void showBasicToast() {
Fluttertoast.showToast(msg: "Hello Flutter Toast!");
}
You can trigger this Flutter Toast from button presses, form submissions, or any other user interactions in your application. The toast will appear with default styling and automatically disappear after the specified duration.
For more control over your Flutter Toast appearance and behavior, you can combine multiple properties:
void showCustomToast() {
Fluttertoast.showToast(
msg: "Custom Flutter Toast Message",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
backgroundColor: Colors.blue,
textColor: Colors.white,
fontSize: 16.0
);
}
Beyond basic Flutter Toast implementation, you can create sophisticated toast experiences using advanced customization options. These techniques allow you to build toast messages that perfectly align with your app’s design language and user experience requirements.
You can create Flutter Toast messages that match your app’s theme by using theme colors and consistent styling:
void showThemedToast(BuildContext context) {
final theme = Theme.of(context);
Fluttertoast.showToast(
msg: "Themed Flutter Toast",
backgroundColor: theme.primaryColor,
textColor: theme.primaryTextTheme.bodyLarge?.color,
fontSize: 16.0
);
}
You can implement logic to show different Flutter Toast messages based on application state or user actions:
void showConditionalToast(bool isSuccess) {
if (isSuccess) {
Fluttertoast.showToast(
msg: "Operation successful!",
backgroundColor: Colors.green,
textColor: Colors.white
);
} else {
Fluttertoast.showToast(
msg: "Operation failed!",
backgroundColor: Colors.red,
textColor: Colors.white
);
}
}
Flutter Toast can display dynamic content based on variables, user input, or application data:
void showDynamicToast(String username) {
Fluttertoast.showToast(
msg: "Welcome back, $username!",
toastLength: Toast.LENGTH_LONG
);
}
When working with state management solutions like Provider, Bloc, or Riverpod, Flutter Toast can be effectively integrated to provide user feedback based on state changes. This approach ensures that toast messages are displayed at appropriate times during your app’s lifecycle.
class UserService with ChangeNotifier {
void loginUser(String email) {
// Login logic here
Fluttertoast.showToast(
msg: "Login successful for $email",
backgroundColor: Colors.green
);
notifyListeners();
}
}
Flutter Toast works excellently with asynchronous operations, providing feedback when network requests complete or background tasks finish:
Future<void> fetchDataWithToast() async {
try {
// Simulate API call
await Future.delayed(Duration(seconds: 2));
Fluttertoast.showToast(
msg: "Data loaded successfully",
backgroundColor: Colors.green
);
} catch (e) {
Fluttertoast.showToast(
msg: "Failed to load data",
backgroundColor: Colors.red
);
}
}
Here’s a comprehensive example demonstrating various Flutter Toast implementations in a complete Flutter application. This example showcases different toast types, customizations, and use cases that you can adapt for your own projects.
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class FlutterToastDemo extends StatefulWidget {
@override
_FlutterToastDemoState createState() => _FlutterToastDemoState();
}
class _FlutterToastDemoState extends State<FlutterToastDemo> {
final TextEditingController _messageController = TextEditingController();
void showBasicToast() {
Fluttertoast.showToast(
msg: "Basic Flutter Toast Message",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM
);
}
void showSuccessToast() {
Fluttertoast.showToast(
msg: "✓ Success! Operation completed successfully",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.TOP,
backgroundColor: Colors.green,
textColor: Colors.white,
fontSize: 16.0
);
}
void showErrorToast() {
Fluttertoast.showToast(
msg: "✗ Error! Something went wrong",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
void showWarningToast() {
Fluttertoast.showToast(
msg: "⚠ Warning! Please check your input",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.orange,
textColor: Colors.black,
fontSize: 14.0
);
}
void showCustomToast() {
String message = _messageController.text.isEmpty
? "Custom Flutter Toast Message"
: _messageController.text;
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
backgroundColor: Colors.purple,
textColor: Colors.white,
fontSize: 18.0
);
}
void showInfoToast() {
Fluttertoast.showToast(
msg: "ℹ Information: Flutter Toast is working perfectly!",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.blue,
textColor: Colors.white,
fontSize: 15.0
);
}
Future<void> simulateAsyncOperation() async {
Fluttertoast.showToast(
msg: "Processing... Please wait",
backgroundColor: Colors.grey
);
try {
// Simulate network request or heavy operation
await Future.delayed(Duration(seconds: 3));
Fluttertoast.showToast(
msg: "Async operation completed successfully!",
backgroundColor: Colors.green,
textColor: Colors.white,
toastLength: Toast.LENGTH_LONG
);
} catch (e) {
Fluttertoast.showToast(
msg: "Async operation failed!",
backgroundColor: Colors.red,
textColor: Colors.white
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Toast Demo'),
backgroundColor: Colors.deepPurple,
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'Flutter Toast Examples',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.deepPurple
),
textAlign: TextAlign.center,
),
SizedBox(height: 20),
TextField(
controller: _messageController,
decoration: InputDecoration(
labelText: 'Enter custom message',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.message)
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: showBasicToast,
child: Text('Show Basic Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: showSuccessToast,
child: Text('Show Success Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: showErrorToast,
child: Text('Show Error Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: showWarningToast,
child: Text('Show Warning Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: showInfoToast,
child: Text('Show Info Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.indigo,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: showCustomToast,
child: Text('Show Custom Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.purple,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: simulateAsyncOperation,
child: Text('Test Async Toast'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
padding: EdgeInsets.symmetric(vertical: 12)
),
),
],
),
),
);
}
@override
void dispose() {
_messageController.dispose();
super.dispose();
}
}
// Main application entry point
class FlutterToastApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Toast Demo',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: FlutterToastDemo(),
debugShowCheckedModeBanner: false,
);
}
}
// Required dependencies for pubspec.yaml:
/*
dependencies:
flutter:
sdk: flutter
fluttertoast: ^8.2.4
*/
void main() {
runApp(FlutterToastApp());
}
This comprehensive Flutter Toast example demonstrates various implementation patterns, customization options, and real-world usage scenarios. The code includes basic toast messages, themed variations, async operations, and user input handling. You can copy this complete example and run it in your Flutter development environment to see Flutter Toast in action.