live_api_notification

Created by Er. Samir Bogati (BogatiX)

pub package License: MIT Sponsor on Patreon

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 with LiveNotification.init() and trigger notifications directly inside Dio, HTTP, or WebSocket interceptors without passing BuildContext.
  • 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, and guestPrompt with curated color palettes and icons out of the box.
  • Configurable Positioning and Styling — Top or bottom placement, custom BorderRadius, EdgeInsets margins, glassmorphism/backdrop blur, elevation shadows, and global theme defaults via LiveNotificationConfig.
  • 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),
);

Payload Parsing Details

extractMessage() traverses responses in this priority order:

  1. Direct string responses
  2. Top-level keys: message, error, msg, detail, reason, status_message, errorMessage, description
  3. Nested data.message, data.error, etc.
  4. Nested error.message, error.detail, etc.
  5. Validation error lists: errors: ['field required', ...]
  6. Validation error maps: errors: {'email': ['invalid'], ...}

isSuccessResponse() checks:

  • Integer status codes (200..299)
  • Boolean success: true / false
  • String status: 'success' or status: 'ok'
  • statusCode / status_code / code fields in the 2xx range

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

Support and Sponsorship

If this package saves you time, consider supporting its development:

Sponsor on Patreon


Author

Er. Samir Bogati — BogatiX


License

This project is licensed under the MIT License. See the LICENSE file for details.