Change Toast color in flutter
Toast refers to a small, non-intrusive, and temporary pop-up message or notification that appears on the screen to provide information or feedback to the user. Toasts are commonly used to display short messages, alerts, or notifications that do not require user interaction. In this tutorial we will see that how to change color of toast in flutter.
In mobile apps we often need to change the color of toast message to enhance the user experience. For example if we want to show the success message, then wen will display toast message in green color. And if we want to show an error message then we will display toast message in red color. Let’s see how to change toast color in flutter.
First of all we need to add toast plugin in pubspec.yaml
toast: ^0.3.0
Add this plugin in and run flutter pub get command in terminal.
Now add this import in your file where we want to show toast message.
import 'package:toast/toast.dart' as Toast;
Now create this function which will show toast message
void _showToast() {
Toast.ToastContext().init(context);
Toast.Toast.show('Success Message',
duration: 2,
gravity: Toast.Toast.bottom,
backgroundColor: Colors.green);
}
Now call this function on press the button like this
ElevatedButton( child: Text('Show Toast'), onPressed: () { _showToast(); }, ),
Output
Here is the complete code
import 'package:flutter/material.dart';
import 'package:toast/toast.dart' as Toast;
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Toast Color'),
),
body: Center(
child: ElevatedButton(
child: Text('Show Toast'),
onPressed: () {
_showToast();
},
),
),
);
}
void _showToast() {
Toast.ToastContext().init(context);
Toast.Toast.show('Success Message',
duration: 2,
gravity: Toast.Toast.bottom,
backgroundColor: Colors.green);
}
}