api_overlay_toast
Context-free Flutter overlay notifications with automatic REST/WebSocket payload parsing and an optional Hive-backed offline queue.
Inspiration and attribution: this package is inspired by the public API and behavior of
live_api_notificationby Er. Samir Bogati / BogatiX (MIT). It is an independent implementation written from scratch; no source code was copied from that package.
What it does
| Feature | Description |
|---|---|
| Context-free toasts | Call ApiOverlayToast.success(...) from services, cubits, interceptors, or WebSocket listeners. |
| Semantic types | success, error, warning, info, and guestPrompt, each with its own accent color and glyph. |
| Overlay animations | Entry/exit slide + fade using configurable curves and durations. |
| Swipe to dismiss | Top toasts dismiss on an upward fling; bottom toasts on a downward fling. A fast horizontal fling also dismisses. |
| Action pill | Optional CTA such as Retry or Sign up, with a callback. |
| API payload parsing | Converts common REST error/success JSON shapes into the right toast type. |
| WebSocket parsing | Parses a JSON string from a socket frame with fromSocket. |
| Offline queue | Persists failed/offline HTTP calls in Hive and replays them when connectivity returns. |
| Exponential backoff | Retries with baseDelay * 2^(attempt - 1), capped by maxRetryDelay. |
| Queue controls | Inspect, remove, and clear queued requests; observe queue changes with a callback. |
Installation
dependencies:
api_overlay_toast: ^0.1.0
Then run:
flutter pub get
The package uses connectivity_plus, hive, hive_flutter, and http. Because of hive_flutter/path_provider, the offline queue is not intended for WebAssembly builds. connectivity_plus reports network availability; it does not guarantee that your specific server is reachable.
Quick start
1. Register a navigator key
import 'package:flutter/material.dart';
import 'package:api_overlay_toast/api_overlay_toast.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
void main() {
ApiOverlayToast.init(
navigatorKey: navigatorKey,
config: const ToastConfig(
position: ToastPosition.top,
duration: Duration(seconds: 4),
),
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
home: const HomePage(),
);
}
}
The key is what makes toasts work without a BuildContext. If you do have a context, every method also accepts an optional context parameter and will use that widget tree's OverlayState first.
2. Show toasts from anywhere
ApiOverlayToast.success(message: 'Profile saved');
ApiOverlayToast.error(message: 'Could not save profile');
ApiOverlayToast.warning(message: 'Your session expires soon');
ApiOverlayToast.info(message: 'Sync started');
ApiOverlayToast.guestPrompt(
message: 'Sign up to sync across devices',
actionLabel: 'Sign up',
onAction: () => openSignUp(),
);
Only one toast is visible at a time: a new call replaces the current one, so rapid events never stack or leak animation tickers.
REST and WebSocket payloads
fromApi chooses the toast type from the payload and extracts a human-readable message:
ApiOverlayToast.fromApi(<String, dynamic>{
'status': 'success',
'message': 'Payment confirmed',
});
ApiOverlayToast.fromApi(<String, dynamic>{
'error': <String, dynamic>{'message': 'Invalid API key'},
});
Recognized message keys include message, error, msg, detail, reason, status_message, errorMessage, and description. Nested data, error, response, result, and payload maps are searched too, as are validation error lists/maps. Success is recognized from 2xx codes, success: true, ok: true, status: 'success', status: 'ok', or numeric statusCode / status_code / code fields.
For socket frames:
ApiOverlayToast.fromSocket(
'{"status":"success","message":"Live update received"}',
);
Invalid JSON produces an error toast. If you only want to show a toast when a message exists, use errorFromApi or successFromApi.
Styling
ToastConfig is immutable and global by default, but every show method accepts a per-call override:
const toastConfig = ToastConfig(
position: ToastPosition.bottom,
duration: Duration(seconds: 6),
animationDuration: Duration(milliseconds: 300),
curve: Curves.easeOutCubic,
reverseCurve: Curves.easeInCubic,
backgroundColor: Color(0xFF0F172A),
textColor: Color(0xFFF8FAFC),
successColor: Color(0xFF22C55E),
errorColor: Color(0xFFEF4444),
enableBlur: true,
blurSigma: 12,
maxWidth: 460,
);
ApiOverlayToast.error(
message: 'Upload failed',
actionLabel: 'Retry',
onAction: retryUpload,
config: toastConfig,
);
Use config.copyWith(...) to derive a new configuration from the current one.
Offline queue
Initialize Hive before enabling persistence, then call initOffline:
import 'package:hive_flutter/hive_flutter.dart';
import 'package:api_overlay_toast/api_overlay_toast.dart';
await Hive.initFlutter();
await ApiOverlayToast.initOffline(
config: const OfflineConfig(
enabled: true,
persistQueue: true,
maxRetries: 3,
baseRetryDelay: Duration(seconds: 1),
maxRetryDelay: Duration(seconds: 60),
autoSyncOnConnectivity: true,
maxQueueSize: 100,
),
);
Now route calls through callApiWithOffline:
await ApiOverlayToast.callApiWithOffline(
method: 'POST',
url: 'https://api.example.com/events',
headers: <String, String>{'Content-Type': 'application/json'},
body: <String, dynamic>{'title': 'Queued while offline'},
fallbackSuccessMessage: 'Event sent',
fallbackErrorMessage: 'Could not send event',
);
When offline, the request is queued and a warning toast is shown. When connectivity returns, queued requests are replayed automatically. A non-2xx response or a transport failure increments the attempt counter and schedules the next try with exponential backoff. After maxRetries, the item is removed and an exhausted toast is shown.
Set persistQueue: false to keep the queue in memory only; in that case you do not need Hive.initFlutter().
Queue management
final pending = ApiOverlayToast.getOfflineQueue();
final count = ApiOverlayToast.offlineQueueLength;
ApiOverlayToast.setOfflineQueueChangedCallback(() {
// Rebuild a badge or list UI.
});
await ApiOverlayToast.removeOfflineQueueItem(pending.first.id);
await ApiOverlayToast.clearOfflineQueue();
await ApiOverlayToast.syncOfflineQueue();
await ApiOverlayToast.disposeOffline(); // Cancels connectivity listening.
Useful state getters: isOfflineModeEnabled, isOnline, isSyncing, and offlineQueueLength.
Minimal example
A runnable demo lives in example/. It shows all toast types, payload parsing, and an optional offline queue setup.
Development
flutter pub get
flutter analyze
flutter test
dart pub publish --dry-run
Limitations
- One toast is displayed at a time; newer toasts replace older ones.
- No custom toast builder API yet in
0.1.0; useToastConfigfor styling. - Requires native plugins for offline mode, so the package is not WASM-compatible.
- Connectivity is an availability signal, not a server health check.
License and credits
MIT © 2026 Chebel Seif (phantome001).
Inspired by live_api_notification by Er. Samir Bogati / BogatiX, also MIT licensed. See NOTICE.md for attribution details.
Libraries
- api_overlay_toast
- Context-free overlay notifications for Flutter, with automatic REST and WebSocket payload parsing and an optional Hive-backed offline queue.