showTopToast function
- BuildContext context,
- String message, {
- Color backgroundColor = Colors.red,
Displays a temporary, dismissible toast message at the top of the screen.
The toast message will automatically disappear after 2 seconds.
context
The BuildContext to display the toast within.
message
The text message to be displayed in the toast.
backgroundColor
The background color of the toast. Defaults to Colors.red.
Implementation
void showTopToast(BuildContext context, String message, {Color backgroundColor = Colors.red}) {
final overlay = Overlay.of(context);
final overlayEntry = OverlayEntry(
builder: (context) => Positioned(
top: MediaQuery.of(context).padding.top + 20,
left: MediaQuery.of(context).size.width * 0.1,
right: MediaQuery.of(context).size.width * 0.1,
child: Material(
color: Colors.transparent,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 8,
offset: Offset(0, 2),
),
],
),
child: Center(
child: Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white, fontSize: 14),
),
),
),
),
),
);
overlay.insert(overlayEntry);
Future.delayed(const Duration(seconds: 2), () {
overlayEntry.remove();
});
}