Trong Flutter, để hiển thị thông báo dạng toast mà không phụ thuộc vào nền tảng (native), bạn có thể sử dụng OverlayEntry kết hợp với các widget tùy chỉnh. Cách này cho phép bạn kiểm soát hoàn toàn giao diện và hành vi của thông báo.
CustomToastManager.dart
import 'package:flutter/material.dart';
import 'dart:async';
class CustomToastManager {
// Định nghĩa kiểu chữ chung cho nội dung
static const TextStyle _textStyle = TextStyle(
color: Colors.white,
fontSize: 14,
decoration: TextDecoration.none,
);
// Tạo widget thông báo với biểu tượng và văn bản
static Widget _buildToastContent(String imagePath, String message) {
return Center(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Colors.blueGrey.withOpacity(0.9),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Colors.grey.shade300, width: 1),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
imagePath,
width: 28,
height: 28,
),
const SizedBox(width: 10),
Text(
message,
style: _textStyle,
),
],
),
),
);
}
// Hiển thị toast dạng buồn
static void showSadToast(BuildContext context, String message) {
final widget = _buildToastContent('images/icon/crying.png', message);
_showOverlay(context, widget);
}
// Hiển thị toast dạng vui
static void showHappyToast(BuildContext context, String message) {
final widget = _buildToastContent('images/icon/laughing.png', message);
_showOverlay(context, widget);
}
// Hiển thị toast dạng thông tin
static void showInfoToast(BuildContext context, String message) {
final widget = _buildToastContent('images/icon/info.png', message);
_showOverlay(context, widget);
}
// Hiển thị toast cảnh báo
static void showWarningToast(BuildContext context, String message) {
final widget = _buildToastContent('images/icon/warning.png', message);
_showOverlay(context, widget);
}
// Hiển thị toast lỗi
static void showErrorToast(BuildContext context, String message) {
final widget = _buildToastContent('images/icon/error.png', message);
_showOverlay(context, widget);
}
// Hàm chèn overlay và tự động ẩn sau 2 giây
static void _showOverlay(BuildContext context, Widget widget) {
final overlay = Overlay.of(context);
final entry = OverlayEntry(builder: (_) => widget);
overlay.insert(entry);
Timer(const Duration(seconds: 2), () {
if (entry.mounted) {
entry.remove();
}
});
}
}
Đăng ký tài nguyên trong pubspec.yaml
Đảm bảo các hình ảnh được khai báo trong file pubspec.yaml để sử dụng với Image.asset:
flutter:
assets:
- images/icon/crying.png
- images/icon/laughing.png
- images/icon/info.png
- images/icon/warning.png
- images/icon/error.png
Cách sử dụng trong màn hình
ElevatedButton(
onPressed: () {
CustomToastManager.showErrorToast(context, "Có lỗi xảy ra!");
},
child: const Text("Hiển thị lỗi"),
)
Chỉ cần truyền context từ Widget build(BuildContext context), lớp quản lý toast sẽ tự động thêm và gỡ bỏ thông báo khỏi giao diện mà không làm ảnh hưởng đến luồng chính.