showToast static method
void
showToast(
- BuildContext context,
- Widget content, {
- bool autoDismiss = true,
- Duration duration = const Duration(seconds: 2),
- bool replacePrevious = true,
Implementation
static void showToast(
BuildContext context,
Widget content, {
bool autoDismiss = true,
Duration duration = const Duration(seconds: 2),
bool replacePrevious = true,
}) {
final overlay = Overlay.maybeOf(context);
if (overlay == null) {
debugPrint(
'ToastManager: No Overlay found. Ensure the widget calling showToast '
'is placed inside a MaterialApp, CupertinoApp, or Navigator.',
);
return;
}
// If this is not an auto-dismissing toast and replacePrevious is true,
// remove any existing persistent toast
if (!autoDismiss && replacePrevious && _currentPersistentToast != null) {
removeToast(entry: _currentPersistentToast);
_currentPersistentToast = null;
}
// Create a controller to handle the toast state
final toastController = ToastController();
// Create the toast with its controller
final toast = ToastWidget(
content: content,
controller: toastController,
);
// Create the overlay entry
final overlayEntry = OverlayEntry(
builder: (context) => toast,
);
// Set the overlay entry in the controller
toastController.overlayEntry = overlayEntry;
_toasts.add(overlayEntry);
overlay.insert(overlayEntry);
// Store reference to non-auto-dismissing toast
if (!autoDismiss) {
_currentPersistentToast = overlayEntry;
}
// Auto remove after duration if enabled
if (autoDismiss) {
Future.delayed(duration, () {
removeToast(entry: overlayEntry);
});
}
}