live_api_notification
Created by Er. Samir Bogati (BogatiX)
An intelligent, zero-boilerplate Flutter overlay notification package that
automatically parses REST API responses and WebSocket payloads into beautiful
animated toast banners. Trigger notifications from anywhere — even inside
Dio/HTTP interceptors — without needing a BuildContext.
Features
- Automatic API Parsing — Hand any REST or WebSocket response map to
fromApi()/fromSocket()and get a correctly-colored success or error banner with the extracted message. Supports nested JSON (data.message,error.message), validation error arrays, validation error maps, and standard HTTP status codes. - Context-Free / Global Interceptor Support — Register a
GlobalKey<NavigatorState>once withLiveNotification.init()and trigger notifications directly inside Dio, HTTP, or WebSocket interceptors without passingBuildContext. - Smooth Animations — Vertical slide + fade entry/exit with configurable curves and durations. Rapid consecutive calls safely replace the active banner without ticker or mounted exceptions.
- Swipe-to-Dismiss — Swipe up (top position) or down (bottom position) or horizontally to dismiss immediately.
- Semantic Types —
success,error,warning,info, andguestPromptwith curated color palettes and icons out of the box. - Configurable Positioning and Styling — Top or bottom placement,
custom
BorderRadius,EdgeInsetsmargins, glassmorphism/backdrop blur, elevation shadows, and global theme defaults viaLiveNotificationConfig. - Interactive Action Pills — Optional action button (e.g. "Sign Up", "Retry") with tap callbacks embedded right in the banner.
Getting Started
Add the dependency to your pubspec.yaml:
dependencies:
live_api_notification: ^1.0.0
Then run:
flutter pub get
Import the package:
import 'package:live_api_notification/live_api_notification.dart';
Quick Start
1. Initialize (optional, enables context-free triggers)
final navigatorKey = GlobalKey<NavigatorState>();
void main() {
LiveNotification.init(
navigatorKey: navigatorKey,
config: const LiveNotificationConfig(
position: LiveNotificationPosition.top,
duration: Duration(seconds: 4),
),
);
runApp(MaterialApp(navigatorKey: navigatorKey, home: HomeScreen()));
}
2. Show Semantic Notifications
// Success
LiveNotification.success(
context: context,
message: 'Profile updated!',
);
// Error
LiveNotification.error(
context: context,
message: 'Network request failed.',
);
// Warning
LiveNotification.warning(
context: context,
message: 'Session expires in 2 minutes.',
);
// Info with action button
LiveNotification.guestPrompt(
context: context,
message: 'Sign up for live deals!',
actionLabel: 'Sign Up',
onSignUp: () => openAuthFlow(),
);
3. Automatic API / Socket Parsing
// Parses the response and shows green (success) or red (error) automatically
final response = await dio.post('/api/orders', data: orderData);
LiveNotification.fromApi(response.data);
// WebSocket events work the same way
channel.stream.listen((event) {
LiveNotification.fromSocket(jsonDecode(event));
});
4. Context-Free Interceptor Usage (Dio Example)
class NotificationInterceptor extends Interceptor {
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
// No BuildContext needed!
LiveNotification.fromApi(response.data);
handler.next(response);
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
LiveNotification.errorFromApi(err.response?.data);
handler.next(err);
}
}
5. Custom Positioning and Styling
// Bottom notification with glassmorphism
LiveNotification.success(
context: context,
message: 'Download complete!',
position: LiveNotificationPosition.bottom,
);
// Global theme override
LiveNotification.config = const LiveNotificationConfig(
position: LiveNotificationPosition.bottom,
enableBlur: true,
blurSigma: 12.0,
borderRadius: BorderRadius.all(Radius.circular(20)),
successColor: Color(0xFF059669),
errorColor: Color(0xFFDC2626),
);
Offline Mode (v1.1.0+)
The package includes a production-ready offline mode that automatically queues failed API requests when the device is offline and retries them with exponential backoff when connectivity is restored.
Enable Offline Mode
import 'package:hive_flutter/hive_flutter.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter(); // Required for Hive persistence
// Initialize offline mode
await LiveNotification.initOffline(
config: const LiveNotificationOfflineConfig(
enabled: true,
maxRetries: 3,
showOfflineNotification: true,
showRetryNotification: true,
showExhaustedNotification: true,
autoSyncOnConnectivity: true,
),
);
// Standard notification init
LiveNotification.init(
navigatorKey: navigatorKey,
config: const LiveNotificationConfig(...),
);
runApp(MyApp());
}
Offline-Aware API Calls
Use callApiWithOffline() instead of raw HTTP calls — it automatically handles queueing on failure:
// Automatically queues if offline, retries when online
await LiveNotification.callApiWithOffline(
method: 'POST',
url: 'https://api.example.com/orders',
headers: {'Authorization': 'Bearer $token'},
body: jsonEncode(orderData),
context: context,
fallbackSuccessMessage: 'Order placed!',
fallbackErrorMessage: 'Failed to place order',
);
How It Works
| Scenario | Behavior |
|---|---|
| Online + Success | Shows success notification immediately |
| Online + Failure (4xx/5xx) | Shows error notification |
| Offline + Any Request | Queues request to Hive, shows "Offline — queued for retry" |
| Connectivity Restored | Auto-triggers sync, retries with exponential backoff (1s, 2s, 4s, 8s... max 60s) |
| Max Retries Exhausted | Shows "Failed after max retries" notification, removes from queue |
Queue Management
// Get all queued items
final queue = LiveNotification.getOfflineQueue();
// Manual sync trigger
await LiveNotification.syncOfflineQueue();
// Check queue status
print('Queued: ${LiveNotification.offlineQueueLength}');
print('Online: ${LiveNotification.isOnline}');
print('Syncing: ${LiveNotification.isSyncing}');
// Clear queue (e.g., user logs out)
await LiveNotification.clearOfflineQueue();
// Remove specific item
await LiveNotification.removeOfflineQueueItem(itemId);
// Listen for queue changes (for UI badges)
LiveNotification.setOfflineQueueChangedCallback(() {
setState(() {}); // Update badge count
});
Offline Configuration
LiveNotificationOfflineConfig(
enabled: true, // Master switch
maxRetries: 3, // Max retry attempts per request
baseRetryDelay: Duration(seconds: 1), // Base delay for backoff
maxRetryDelay: Duration(seconds: 60), // Cap for backoff
queueName: 'live_notification_offline_queue', // Hive box name
showOfflineNotification: true, // Toast when queued offline
showRetryNotification: true, // Toast when retrying
showExhaustedNotification: true, // Toast when max retries hit
offlineMessage: 'You\'re offline. Request queued.',
retryMessage: 'Connection restored. Retrying...',
exhaustedMessage: 'Failed after max retries.',
autoSyncOnConnectivity: true, // Auto-sync when online
maxQueueSize: 100, // Max queued requests
persistQueue: true, // Persist to disk (Hive)
)
Payload Parsing Details
extractMessage() traverses responses in this priority order:
- Direct string responses
- Top-level keys:
message,error,msg,detail,reason,status_message,errorMessage,description - Nested
data.message,data.error, etc. - Nested
error.message,error.detail, etc. - Validation error lists:
errors: ['field required', ...] - Validation error maps:
errors: {'email': ['invalid'], ...}
isSuccessResponse() checks:
- Integer status codes (
200..299) - Boolean
success: true/false - String
status: 'success'orstatus: 'ok' statusCode/status_code/codefields in the2xxrange
API Reference
| Method | Description |
|---|---|
LiveNotification.init(...) |
Configure navigator key and global defaults |
LiveNotification.success(...) |
Green success banner |
LiveNotification.error(...) |
Red error banner |
LiveNotification.warning(...) |
Amber warning banner |
LiveNotification.info(...) |
Blue informational banner |
LiveNotification.guestPrompt(...) |
Blue banner with action pill |
LiveNotification.fromApi(...) |
Auto-parse any API response |
LiveNotification.fromSocket(...) |
Auto-parse WebSocket payload |
LiveNotification.errorFromApi(...) |
Show error only if message found |
LiveNotification.successFromApi(...) |
Show success only if message found |
LiveNotification.extractMessage(...) |
Extract message string from payload |
LiveNotification.isSuccessResponse(...) |
Check if response indicates success |
LiveNotification.dismiss(...) |
Dismiss the active notification |
Offline Mode API
| Method | Description |
|---|---|
LiveNotification.initOffline(config) |
Initialize offline mode with Hive |
LiveNotification.offlineConfig |
Get current offline configuration |
LiveNotification.isOfflineModeEnabled |
Check if offline mode is active |
LiveNotification.isOnline |
Current connectivity status |
LiveNotification.isSyncing |
Whether background sync is running |
LiveNotification.offlineQueueLength |
Number of queued requests |
LiveNotification.getOfflineQueue() |
Get all queued OfflineQueueItems |
LiveNotification.callApiWithOffline(...) |
Execute HTTP call with auto-queue on failure |
LiveNotification.syncOfflineQueue() |
Manually trigger queue sync |
LiveNotification.clearOfflineQueue() |
Clear entire queue |
LiveNotification.removeOfflineQueueItem(id) |
Remove specific queued item |
LiveNotification.setOfflineQueueChangedCallback(cb) |
Listen for queue changes |
LiveNotification.disposeOffline() |
Clean up resources |
Support and Sponsorship
If this package saves you time, consider supporting its development:
Author
License
This project is licensed under the MIT License. See the LICENSE file for details.