Skip to main content

awesome_notifications 1.0.0-dev.10 copy "awesome_notifications: ^1.0.0-dev.10" to clipboard
awesome_notifications: ^1.0.0-dev.10 copied to clipboard

A complete solution to create Local and Push Notifications, customizing buttons, images, sounds, emoticons and applying many different layouts for Flutter apps.

example/lib/main.dart

// Minimal, self-contained Awesome Notifications example.
//
// Copy this file into your app's `lib/main.dart`, add `awesome_notifications`
// to your pubspec.yaml and run. It covers the essentials: initialize, request
// permission, create a notification (with a big picture + large icon), dismiss
// it, and open a details page when the user taps it.
//
// Each add-on package (schedules, localizations, FCM, …) ships its own example
// showing how it combines with this core.
import 'dart:io';
import 'dart:math' show max;

import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show SystemUiOverlayStyle;

const String channelKey = 'alerts';
const String badgeChannelKey = 'badges';
const Color mainColor = Color(0xFF9D50DD);

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // 1. Initialize with at least one channel. Keep the Future so the UI can wait
  //    for it: creating a notification before initialize completes can fail.
  final Future<bool> awesomeNotificationsInitialization =
      NotificationController.initializeLocalNotifications();

  runApp(
    MyApp(
      awesomeNotificationsInitialization: awesomeNotificationsInitialization,
    ),
  );
}

///  *********************************************
///     NOTIFICATION CONTROLLER
///  *********************************************
///
/// Keeps all the Awesome Notifications calls in one place so the widgets stay
/// focused on the UI.
class NotificationController {
  // Lets the (static) action listener open a page from anywhere.
  static final GlobalKey<NavigatorState> navigatorKey =
      GlobalKey<NavigatorState>();

  // Lets the (static) event listeners show snackbars from anywhere.
  static final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =
      GlobalKey<ScaffoldMessengerState>();

  ///  *********************************************
  ///     INITIALIZATION
  ///  *********************************************
  static Future<bool> initializeLocalNotifications() {
    return AwesomeNotifications().initialize(
      // The status bar icon: a white glyph on transparent (Android draws only
      // its alpha). Without it, the full-color app icon shows as a square.
      'resource://drawable/res_notification_icon',
      [
        NotificationChannel(
          channelKey: channelKey,
          channelName: 'Alerts',
          channelDescription: 'Notification tests as alerts',
          defaultColor: mainColor,
          ledColor: mainColor,
          importance: NotificationImportance.High,
        ),
        // Every notification of this channel adds one to the app's badge.
        NotificationChannel(
          channelKey: badgeChannelKey,
          channelName: 'Badges',
          channelDescription: 'Notifications that add to the app badge',
          defaultColor: mainColor,
          importance: NotificationImportance.High,
          channelShowBadge: true,
        ),
      ],
      debug: true,
    );
  }

  ///  *********************************************
  ///     EVENT LISTENERS
  ///  *********************************************
  ///  Notification events are only delivered after this is called.
  static Future<void> startListeningNotificationEvents() {
    return AwesomeNotifications().setListeners(
      onActionReceivedMethod: onActionReceivedMethod,
      onNotificationCreatedMethod: onNotificationCreatedMethod,
      onNotificationDisplayedMethod: onNotificationDisplayedMethod,
      onDismissActionReceivedMethod: onDismissActionReceivedMethod,
    );
  }

  /// If the app was launched by tapping a notification (killed state), the tap
  /// is not delivered to [onActionReceivedMethod] (no listener existed yet):
  /// it is retrieved here instead, and opens the details page.
  static Future<void> handleInitialAction() async {
    final ReceivedAction? action = await AwesomeNotifications()
        .getInitialNotificationAction(removeFromActionEvents: true);
    debugPrint(
      'getInitialNotificationAction -> '
      '${action == null ? 'null (no launch action)' : 'id=${action.id} '
                'channelKey=${action.channelKey} '
                'buttonKeyPressed=${action.buttonKeyPressed}'}',
    );
    if (action == null) return;
    navigatorKey.currentState?.pushAndRemoveUntil(
      MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
      (route) => route.isFirst,
    );
  }

  // Listeners must be static / top-level and annotated with vm:entry-point.

  @pragma('vm:entry-point')
  static Future<void> onNotificationCreatedMethod(
    ReceivedNotification received,
  ) async {
    _showEventSnackBar('Created #${received.id}', Colors.green);
  }

  @pragma('vm:entry-point')
  static Future<void> onNotificationDisplayedMethod(
    ReceivedNotification received,
  ) async {
    _showEventSnackBar('Displayed #${received.id}', Colors.blue);
  }

  @pragma('vm:entry-point')
  static Future<void> onActionReceivedMethod(ReceivedAction action) async {
    _showEventSnackBar('Action #${action.id}', Colors.orange);
    // Open the details page when the user taps the notification.
    navigatorKey.currentState?.pushAndRemoveUntil(
      MaterialPageRoute(builder: (_) => NotificationPage(action: action)),
      (route) => route.isFirst,
    );
  }

  @pragma('vm:entry-point')
  static Future<void> onDismissActionReceivedMethod(
    ReceivedAction action,
  ) async {
    _showEventSnackBar('Dismissed #${action.id}', Colors.red);
  }

  // Shows a notification event as a colored snackbar.
  static void _showEventSnackBar(String message, Color color) {
    scaffoldMessengerKey.currentState
      ?..hideCurrentSnackBar()
      ..showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: color,
          behavior: SnackBarBehavior.floating,
          duration: const Duration(seconds: 2),
        ),
      );
  }

  /// Checks the permission before each notification (as the 0.12.1 example):
  /// asks for it, with the rationale first, when it isn't granted yet.
  static Future<bool> _ensureAllowed() async {
    if (await AwesomeNotifications().isNotificationAllowed()) return true;
    final context = navigatorKey.currentContext;
    if (context == null || !context.mounted) return false;
    return requestPermission(context);
  }

  ///  *********************************************
  ///     REQUESTING PERMISSIONS
  ///  *********************************************
  ///
  /// Shows a short rationale before the system permission prompt.
  static Future<bool> requestPermission(BuildContext context) async {
    final userAuthorized = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Get Notified!'),
        content: const Text(
          'Allow Awesome Notifications to send you beautiful notifications!',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(false),
            child: const Text('Deny', style: TextStyle(color: Colors.red)),
          ),
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(true),
            child: const Text('Allow', style: TextStyle(color: mainColor)),
          ),
        ],
      ),
    );

    if (userAuthorized != true) return false;
    final allowed =
        await AwesomeNotifications().requestPermissionToSendNotifications();
    if (!allowed) {
      _showEventSnackBar(
        'Notifications are blocked: allow them in the settings of the system '
        'or of the browser',
        Colors.red,
      );
    }
    return allowed;
  }

  ///  *********************************************
  ///     CREATE — BASIC (text only)
  ///  *********************************************
  // Title + body.
  static Future<void> createTitleAndBody() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 1,
        channelKey: channelKey,
        title: 'Simple notification',
        body: 'Notification with a title and a body.',
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  // Title only.
  static Future<void> createTitleOnly() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 2,
        channelKey: channelKey,
        title: 'Notification with a title only',
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  // Body only.
  static Future<void> createBodyOnly() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 3,
        channelKey: channelKey,
        body: 'Notification with a body only.',
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  // Neither title nor body (only a payload).
  static Future<void> createWithoutTitleAndBody() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 4,
        channelKey: channelKey,
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  ///  *********************************************
  ///     CREATE — IMAGE SOURCES
  ///  *********************************************
  // We demonstrate the image sources that need no bundled media here
  // (network, file and resource); `asset://` is also supported. The resource
  // is the app's own icon, generated with the launcher icons.
  // The network images are pinned to a commit of the plugin repository, so
  // they never expire.
  static const String _imagesRoot =
      'https://raw.githubusercontent.com/rafaelsetragni/awesome_notifications/'
      '2f5a5346f36cfea0b8d221062b32a54ae309339f/example/assets/images';
  static const String _networkImage = '$_imagesRoot/awn-rocks-en.jpg';
  // resource:// (Android drawable, iOS/macOS asset catalog image).
  static const String _appIconResource = 'resource://drawable/res_app_icon';
  // Only Android, iOS and macOS have resources.
  static bool get hasResources =>
      !kIsWeb && (Platform.isAndroid || Platform.isIOS || Platform.isMacOS);
  // The web app serves its own icon; Windows and Linux get no large icon.
  static String? get _largeIcon => kIsWeb
      ? Uri.base.resolve('icons/Icon-192.png').toString()
      : hasResources
      ? _appIconResource
      : null;

  // Network image (https://).
  static Future<void> createImageFromNetwork() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 11,
        channelKey: channelKey,
        title: 'Big picture (Network)',
        body: 'Image loaded from an https:// URL.',
        notificationLayout: NotificationLayout.BigPicture,
        bigPicture: _networkImage,
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  // Local file (file://) — download an image to a temp file first, using only
  // dart:io (no extra dependencies), then show it from disk.
  static Future<void> createImageFromFile() async {
    // A browser has no file system: a page can't save the image nor read a
    // file:// path.
    if (kIsWeb) {
      _showEventSnackBar(
        'Files on disk aren\'t available on the web',
        Colors.grey,
      );
      return;
    }
    if (!await _ensureAllowed()) return;
    final filePath = '${Directory.systemTemp.path}/awesome_bigpicture.jpg';
    final request = await HttpClient().getUrl(Uri.parse(_networkImage));
    final response = await request.close();
    final bytes = await response.fold<List<int>>(
      <int>[],
      (buffer, chunk) => buffer..addAll(chunk),
    );
    await File(filePath).writeAsBytes(bytes);

    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 13,
        channelKey: channelKey,
        title: 'Big picture (File)',
        body: 'Image read from a file on disk.',
        notificationLayout: NotificationLayout.BigPicture,
        bigPicture: 'file://$filePath',
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  // Resource image (resource://), from the app's native resources.
  static Future<void> createImageFromResource() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 14,
        channelKey: channelKey,
        title: 'Big picture (Resource)',
        body: "The app's icon, read from the native resources.",
        notificationLayout: NotificationLayout.BigPicture,
        bigPicture: _appIconResource,
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  // A notification with a large icon (the app's icon) shown beside the text.
  static Future<void> createWithLogo() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 21,
        channelKey: channelKey,
        title: 'Large icon',
        body: "The app's icon is shown next to the text.",
        largeIcon: _largeIcon,
        roundedLargeIcon: true,
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  ///  *********************************************
  ///     CREATE — ACTION BUTTONS
  ///  *********************************************
  // Buttons rendered under the notification. The pressed key (and any typed
  // reply) arrives in the ReceivedAction handled by onActionReceivedMethod.
  static Future<void> createWithActionButtons() async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: 31,
        channelKey: channelKey,
        title: 'Action buttons',
        body: 'Tap a button below.',
        payload: {'uuid': 'uuid-test'},
      ),
      actionButtons: [
        NotificationActionButton(key: 'ACCEPT', label: 'Accept'),
        NotificationActionButton(
          key: 'REPLY',
          label: 'Reply',
          requireInputText: true,
        ),
        NotificationActionButton(
          key: 'DISMISS',
          label: 'Dismiss',
          actionType: ActionType.DismissAction,
          isDangerousOption: true,
        ),
      ],
    );
  }

  ///  *********************************************
  ///     CREATE — LAYOUTS, ACTION TYPES AND DISPLAY RULES
  ///  *********************************************
  static Future<void> _create(
    int id,
    String title,
    String body, {
    String channel = channelKey,
    NotificationLayout layout = NotificationLayout.Default,
    ActionType actionType = ActionType.Default,
    String? summary,
    double? progress,
    int? badge,
    bool locked = false,
    bool autoDismissible = true,
    bool displayOnForeground = true,
    bool displayOnBackground = true,
  }) async {
    if (!await _ensureAllowed()) return;
    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: id,
        channelKey: channel,
        title: title,
        body: body,
        summary: summary,
        notificationLayout: layout,
        actionType: actionType,
        progress: progress,
        badge: badge,
        locked: locked,
        autoDismissible: autoDismissible,
        displayOnForeground: displayOnForeground,
        displayOnBackground: displayOnBackground,
        payload: {'uuid': 'uuid-test'},
      ),
    );
  }

  static Future<void> createBigText() => _create(
    41,
    'Big text',
    'A long text that the notification shows in full when expanded. ' * 4,
    summary: 'Summary',
    layout: NotificationLayout.BigText,
  );

  static Future<void> createInbox() => _create(
    42,
    'Inbox',
    'First message\nSecond message\nThird message',
    summary: '3 messages',
    layout: NotificationLayout.Inbox,
  );

  // The same id updates the notification on screen.
  static Future<void> createProgressBar() async {
    for (var progress = 0; progress <= 100; progress += 20) {
      await _create(
        43,
        progress < 100 ? 'Downloading' : 'Download complete',
        '$progress%',
        layout: NotificationLayout.ProgressBar,
        progress: progress.toDouble(),
        locked: progress < 100,
      );
      await Future<void>.delayed(const Duration(seconds: 1));
    }
  }

  static Future<void> createSilentAction() => _create(
    51,
    'Silent action',
    'A tap runs the action without opening the app.',
    actionType: ActionType.SilentAction,
  );

  static Future<void> createKeepOnTop() => _create(
    52,
    'Keep on top',
    'A tap fires the action and the notification stays.',
    actionType: ActionType.KeepOnTop,
    autoDismissible: false,
  );

  static Future<void> createDismissAction() => _create(
    53,
    'Dismiss action',
    'A tap dismisses it, as a swipe does.',
    actionType: ActionType.DismissAction,
  );

  static Future<void> createLocked() => _create(
    54,
    'Locked',
    'The user can\'t swipe it away: dismiss it from the app.',
    locked: true,
    autoDismissible: false,
  );

  // Not shown now; its created and displayed events still arrive.
  static Future<void> createOnlyInBackground() => _create(
    61,
    'Only in background',
    'Never shown while the app is open.',
    displayOnForeground: false,
  );

  static Future<void> createOnlyInForeground() => _create(
    62,
    'Only in foreground',
    'Shown because the app is open.',
    displayOnBackground: false,
  );

  ///  *********************************************
  ///     BADGE
  ///  *********************************************
  static int _badgeId = 100;

  // Its channel has channelShowBadge: adds one to the badge.
  static Future<void> createAddingToBadge() => _create(
    _badgeId++,
    'New notification',
    'This channel adds one to the app badge.',
    channel: badgeChannelKey,
  );

  // The content's badge replaces the counter.
  static Future<void> createSettingBadge() =>
      _create(71, 'Badge 10', 'This notification sets the badge.', badge: 10);

  ///  *********************************************
  ///     PERMISSIONS, SETTINGS, CHANNELS AND STATE
  ///  *********************************************
  static void _show(String message) =>
      _showEventSnackBar(message, Colors.black87);

  static Future<void> checkPermissions() async {
    final allowed = await AwesomeNotifications().checkPermissionList();
    _show('Allowed: ${allowed.map((p) => p.name).join(', ')}');
  }

  static Future<void> checkRationale() async {
    final missing = await AwesomeNotifications().shouldShowRationaleToRequest();
    _show('To ask again: ${missing.map((p) => p.name).join(', ')}');
  }

  static Future<void> checkStatuses() async {
    final statuses = await AwesomeNotifications().getPermissionStatusList();
    _show(
      statuses.entries.map((e) => '${e.key.name}: ${e.value.name}').join('\n'),
    );
  }

  static Future<void> openNotificationPage() =>
      AwesomeNotifications().showNotificationConfigPage();

  static Future<void> openChannelPage() =>
      AwesomeNotifications().showNotificationConfigPage(channelKey: channelKey);

  static Future<void> openAlarmPage() => AwesomeNotifications().showAlarmPage();

  static Future<void> openDndPage() =>
      AwesomeNotifications().showGlobalDndOverridePage();

  static Future<void> createChannel() async {
    await AwesomeNotifications().setChannel(
      NotificationChannel(
        channelKey: 'temporary',
        channelName: 'Temporary',
        channelDescription: 'A channel created and removed by the app',
      ),
    );
    _show('Channel created');
  }

  static Future<void> removeChannel() async {
    final removed = await AwesomeNotifications().removeChannel('temporary');
    _show(removed ? 'Channel removed' : 'No such channel');
  }

  static Future<void> showActiveNotifications() async {
    final ids = await AwesomeNotifications()
        .getAllActiveNotificationIdsOnStatusBar();
    _show('On the status bar: $ids');
  }

  static Future<void> showLifeCycle() async {
    final lifeCycle = await AwesomeNotifications().getAppLifeCycle();
    _show('Life cycle: ${lifeCycle.name}');
  }

  static Future<void> showTimeZones() async {
    final local = await AwesomeNotifications().getLocalTimeZoneIdentifier();
    final utc = await AwesomeNotifications().getUtcTimeZoneIdentifier();
    _show('Local: $local, UTC: $utc');
  }

  ///  *********************************************
  ///     DISMISS / CANCEL
  ///  *********************************************
  // Dismiss removes the notifications from the status bar (keeps any schedule).
  static Future<void> dismissNotifications() {
    return AwesomeNotifications().dismissAllNotifications();
  }

  // Cancel removes the notifications AND cancels their schedule.
  static Future<void> cancelNotifications() {
    return AwesomeNotifications().cancelAll();
  }
}

///  *********************************************
///     MAIN WIDGET
///  *********************************************
///
class MyApp extends StatelessWidget {
  final Future<bool> awesomeNotificationsInitialization;

  const MyApp({super.key, required this.awesomeNotificationsInitialization});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Awesome Notifications - Simple Example',
      navigatorKey: NotificationController.navigatorKey,
      scaffoldMessengerKey: NotificationController.scaffoldMessengerKey,
      theme: ThemeData(colorSchemeSeed: mainColor, useMaterial3: true),
      // Show a simple splash until the plugin finished initializing.
      home: FutureBuilder<bool>(
        future: awesomeNotificationsInitialization,
        builder: (context, snapshot) {
          if (snapshot.connectionState != ConnectionState.done) {
            return const _SplashScreen();
          }
          return const HomePage();
        },
      ),
    );
  }
}

class _SplashScreen extends StatelessWidget {
  const _SplashScreen();

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: mainColor,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.notifications_active, size: 72, color: Colors.white),
            SizedBox(height: 24),
            CircularProgressIndicator(color: Colors.white),
          ],
        ),
      ),
    );
  }
}

///  *********************************************
///     HOME PAGE
///  *********************************************
///
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  bool _allowed = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    NotificationController.startListeningNotificationEvents();
    // Handle a notification tap that launched the app from a killed state.
    NotificationController.handleInitialAction();
    _refreshAllowed();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // The permission may change in the system settings while the app is away.
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) _refreshAllowed();
  }

  Future<void> _refreshAllowed() async {
    final allowed = await AwesomeNotifications().isNotificationAllowed();
    if (mounted) setState(() => _allowed = allowed);
  }

  Future<void> _requestPermission() async {
    final allowed = await NotificationController.requestPermission(context);
    setState(() => _allowed = allowed);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: mainColor,
        foregroundColor: Colors.white,
        title: const Text('Awesome Notifications Example'),
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(horizontal: 24),
        children: [
          const _SectionDivisor('Permission'),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                _allowed ? Icons.notifications_active : Icons.notifications_off,
                color: mainColor,
              ),
              const SizedBox(width: 8),
              Text(
                _allowed
                    ? 'Notifications are allowed.'
                    : 'Notifications are not allowed yet.',
              ),
            ],
          ),
          const SizedBox(height: 8),
          _WideButton(
            'Allow notifications',
            enabled: !_allowed,
            backgroundColor: mainColor,
            labelColor: Colors.white,
            onPressed: _requestPermission,
          ),
          const _SectionDivisor('Basic notifications'),
          _WideButton(
            'Title and body',
            onPressed: NotificationController.createTitleAndBody,
          ),
          _WideButton(
            'Title only',
            onPressed: NotificationController.createTitleOnly,
          ),
          _WideButton(
            'Body only',
            onPressed: NotificationController.createBodyOnly,
          ),
          _WideButton(
            'Without title and body',
            onPressed: NotificationController.createWithoutTitleAndBody,
          ),
          const _SectionDivisor('Image sources'),
          _WideButton(
            'Big picture from network',
            onPressed: NotificationController.createImageFromNetwork,
          ),
          _WideButton(
            'Big picture from file',
            onPressed: NotificationController.createImageFromFile,
          ),
          if (NotificationController.hasResources)
            _WideButton(
              'Big picture from resource',
              onPressed: NotificationController.createImageFromResource,
            ),
          _WideButton(
            'Large icon (app icon)',
            onPressed: NotificationController.createWithLogo,
          ),
          const _SectionDivisor('Action buttons'),
          _WideButton(
            'Notification with action buttons',
            onPressed: NotificationController.createWithActionButtons,
          ),
          const _SectionDivisor('Badge'),
          const _BadgeCounter(),
          const _SectionDivisor('Layouts'),
          _WideButton(
            'Big text',
            onPressed: NotificationController.createBigText,
          ),
          _WideButton('Inbox', onPressed: NotificationController.createInbox),
          _WideButton(
            'Progress bar',
            onPressed: NotificationController.createProgressBar,
          ),
          const _SectionDivisor('Action types'),
          _WideButton(
            'Silent action',
            onPressed: NotificationController.createSilentAction,
          ),
          _WideButton(
            'Keep on top',
            onPressed: NotificationController.createKeepOnTop,
          ),
          _WideButton(
            'Dismiss action',
            onPressed: NotificationController.createDismissAction,
          ),
          _WideButton('Locked', onPressed: NotificationController.createLocked),
          const _SectionDivisor('Display rules'),
          _WideButton(
            'Only in background',
            onPressed: NotificationController.createOnlyInBackground,
          ),
          _WideButton(
            'Only in foreground',
            onPressed: NotificationController.createOnlyInForeground,
          ),
          const _SectionDivisor('Permissions and settings'),
          _WideButton(
            'Check permissions',
            onPressed: NotificationController.checkPermissions,
          ),
          _WideButton(
            'Permissions to ask again',
            onPressed: NotificationController.checkRationale,
          ),
          _WideButton(
            'Permission statuses',
            onPressed: NotificationController.checkStatuses,
          ),
          _WideButton(
            'App notification settings',
            onPressed: NotificationController.openNotificationPage,
          ),
          _WideButton(
            'Channel settings',
            onPressed: NotificationController.openChannelPage,
          ),
          _WideButton(
            'Alarm settings',
            onPressed: NotificationController.openAlarmPage,
          ),
          _WideButton(
            'Do Not Disturb settings',
            onPressed: NotificationController.openDndPage,
          ),
          const _SectionDivisor('Channels and state'),
          _WideButton(
            'Create a channel',
            onPressed: NotificationController.createChannel,
          ),
          _WideButton(
            'Remove the channel',
            onPressed: NotificationController.removeChannel,
          ),
          _WideButton(
            'Notifications on the status bar',
            onPressed: NotificationController.showActiveNotifications,
          ),
          _WideButton(
            'App life cycle',
            onPressed: NotificationController.showLifeCycle,
          ),
          _WideButton(
            'Time zones',
            onPressed: NotificationController.showTimeZones,
          ),
          const _SectionDivisor('Dismiss vs Cancel'),
          Text(
            'Dismiss only removes the notification from the status bar. '
            'Cancel does the same AND cancels its schedule.',
            textAlign: TextAlign.center,
            style: Theme.of(context).textTheme.bodySmall,
          ),
          const SizedBox(height: 8),
          _WideButton(
            'Dismiss notifications',
            onPressed: NotificationController.dismissNotifications,
          ),
          _WideButton(
            'Cancel notifications',
            onPressed: NotificationController.cancelNotifications,
          ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }
}

///  *********************************************
///     REUSABLE WIDGETS (inlined to keep this a single-file example)
///  *********************************************
///
/// The app's badge counter and the calls that move it.
class _BadgeCounter extends StatefulWidget {
  const _BadgeCounter();

  @override
  State<_BadgeCounter> createState() => _BadgeCounterState();
}

class _BadgeCounterState extends State<_BadgeCounter> {
  int? _badge;

  @override
  void initState() {
    super.initState();
    _run(() async {});
  }

  // Runs [change], then reads the counter back from the platform.
  Future<void> _run(Future<void> Function() change) async {
    await change();
    final badge = await AwesomeNotifications().getGlobalBadgeCounter();
    if (mounted) setState(() => _badge = badge);
  }

  @override
  Widget build(BuildContext context) {
    final plugin = AwesomeNotifications();
    return Column(
      children: [
        Text(
          'Current badge: ${_badge ?? '…'}',
          style: Theme.of(context).textTheme.titleMedium,
        ),
        const SizedBox(height: 8),
        _WideButton('Read', onPressed: () => _run(() async {})),
        _WideButton(
          'Set to 5',
          onPressed: () => _run(() => plugin.setGlobalBadgeCounter(5)),
        ),
        _WideButton(
          'Increment',
          onPressed: () => _run(plugin.incrementGlobalBadgeCounter),
        ),
        _WideButton(
          'Decrement',
          onPressed: () => _run(plugin.decrementGlobalBadgeCounter),
        ),
        _WideButton('Reset', onPressed: () => _run(plugin.resetGlobalBadge)),
        _WideButton(
          'Notification that adds one',
          onPressed: () => _run(NotificationController.createAddingToBadge),
        ),
        _WideButton(
          'Notification that sets 10',
          onPressed: () => _run(NotificationController.createSettingBadge),
        ),
      ],
    );
  }
}

/// A section title between two divider lines.
class _SectionDivisor extends StatelessWidget {
  final String title;

  const _SectionDivisor(this.title);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: Row(
        children: [
          const Expanded(child: Divider(thickness: 1)),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Text(
              title,
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
            ),
          ),
          const Expanded(child: Divider(thickness: 1)),
        ],
      ),
    );
  }
}

/// A full-width button matching the example's style.
class _WideButton extends StatelessWidget {
  final String label;
  final Color? backgroundColor;
  final Color? labelColor;
  final bool enabled;
  final VoidCallback? onPressed;

  const _WideButton(
    this.label, {
    this.backgroundColor,
    this.labelColor,
    this.enabled = true,
    this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          backgroundColor: backgroundColor ?? Colors.grey.shade200,
          padding: const EdgeInsets.symmetric(vertical: 16),
        ),
        onPressed: enabled ? onPressed : null,
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 14,
            color: enabled
                ? (labelColor ?? Colors.black87)
                : Colors.grey.shade500,
          ),
        ),
      ),
    );
  }
}

///  *********************************************
///     NOTIFICATION DETAILS PAGE
///  *********************************************
///
/// Opened when a notification is tapped, as in the original complete example: the
/// big picture faded at the top, the large icon in a yellow ring, the title with
/// the date, the body and, at the base, the payload and the received action.
class NotificationPage extends StatelessWidget {
  final ReceivedAction action;

  const NotificationPage({super.key, required this.action});

  @override
  Widget build(BuildContext context) {
    final mediaQueryData = MediaQuery.of(context);
    final themeData = Theme.of(context);

    ImageProvider? largeIcon = action.largeIconImage;
    final ImageProvider? bigPicture = action.bigPictureImage;
    if (largeIcon == bigPicture) largeIcon = null;

    final double maxSize = max(
      mediaQueryData.size.width,
      mediaQueryData.size.height,
    );

    final DateTime? date = action.displayedDate ?? action.createdDate;
    final String? dateText = date == null
        ? null
        : AwesomeDateUtils.parseDateToString(
            // The plugin's dates hold UTC time.
            AwesomeDateUtils.utcToLocal(date),
            format: 'dd/MM/yyyy HH:mm',
          );

    final Map<String, String?> payload = action.payload ?? {};
    final TextStyle? onSurface = themeData.textTheme.bodyMedium?.copyWith(
      color: themeData.colorScheme.onSurface,
    );

    return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        value: bigPicture == null
            ? SystemUiOverlayStyle.dark
            : SystemUiOverlayStyle.light,
        child: Stack(
          children: <Widget>[
            ListView(
              padding: EdgeInsets.zero,
              children: <Widget>[
                Stack(
                  children: <Widget>[
                    // The big picture fading out, or a soft shade.
                    if (bigPicture == null)
                      Container(
                        height: mediaQueryData.padding.top + 120,
                        width: mediaQueryData.size.width,
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            colors: [Colors.black12, Colors.transparent],
                          ),
                        ),
                      )
                    else
                      SizedBox(
                        height: maxSize * 0.4 + mediaQueryData.padding.top,
                        width: mediaQueryData.size.width,
                        child: ShaderMask(
                          shaderCallback: (rect) =>
                              const LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [
                                  Colors.black,
                                  Colors.black,
                                  Colors.transparent,
                                ],
                                stops: [0.0, 0.75, 0.98],
                              ).createShader(
                                Rect.fromLTRB(0, 0, rect.width, rect.height),
                              ),
                          blendMode: BlendMode.dstIn,
                          child: Image(
                            image: bigPicture,
                            width: mediaQueryData.size.width,
                            // 4 pixels short: no seam under the mask while
                            // the page slides.
                            height:
                                maxSize * 0.4 + mediaQueryData.padding.top - 4,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stack) =>
                                const SizedBox(),
                          ),
                        ),
                      ),

                    // The large icon in its yellow ring.
                    if (largeIcon != null)
                      Positioned(
                        left: bigPicture == null
                            ? mediaQueryData.size.width / 2 - maxSize * 0.08
                            : 20,
                        top:
                            mediaQueryData.padding.top +
                            (bigPicture == null ? 32 : maxSize * 0.25),
                        child: CircleAvatar(
                          radius: maxSize * 0.08,
                          backgroundColor: const Color(0xffFDCF09),
                          child: CircleAvatar(
                            radius: maxSize * 0.075,
                            backgroundColor: Colors.white,
                            backgroundImage: largeIcon,
                          ),
                        ),
                      ),

                    // The title and when it was shown.
                    Container(
                      width: mediaQueryData.size.width,
                      padding: EdgeInsets.only(
                        left: 20,
                        right: 20,
                        bottom: 12,
                        top: bigPicture == null
                            ? (largeIcon == null
                                  ? mediaQueryData.padding.top + 72
                                  : mediaQueryData.padding.top +
                                        maxSize * 0.16 +
                                        52)
                            : maxSize * 0.48,
                      ),
                      child: RichText(
                        text: TextSpan(
                          children: [
                            TextSpan(
                              text:
                                  action.titleWithoutHtml ??
                                  (action.bodyWithoutHtml ?? ''),
                              style: TextStyle(
                                fontSize: (action.title?.isEmpty ?? true)
                                    ? 24
                                    : 32,
                                height: 1.2,
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            if (dateText != null)
                              TextSpan(
                                text: '\n$dateText',
                                style: themeData.textTheme.titleSmall?.copyWith(
                                  color: Colors.black26,
                                ),
                              ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),

                // The body, when the title took the top.
                if (!(action.title?.isEmpty ?? true) &&
                    !(action.body?.isEmpty ?? true))
                  Padding(
                    padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
                    child: Text(
                      action.bodyWithoutHtml ?? '',
                      style: themeData.textTheme.bodyMedium,
                    ),
                  ),

                // The payload and everything the action received.
                Container(
                  width: mediaQueryData.size.width,
                  color: themeData.disabledColor,
                  padding: const EdgeInsets.fromLTRB(20, 32, 20, 32),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      if (action.buttonKeyPressed.isNotEmpty) ...[
                        Text(
                          'Button pressed:',
                          style: themeData.textTheme.titleMedium?.copyWith(
                            color: themeData.colorScheme.onSurface,
                          ),
                        ),
                        const SizedBox(height: 12),
                        Text(
                          action.buttonKeyInput.isEmpty
                              ? action.buttonKeyPressed
                              : '${action.buttonKeyPressed}: '
                                    '${action.buttonKeyInput}',
                          style: onSurface,
                        ),
                        const SizedBox(height: 24),
                      ],
                      Text(
                        'Payload:',
                        style: themeData.textTheme.titleMedium?.copyWith(
                          color: themeData.colorScheme.onSurface,
                        ),
                      ),
                      const SizedBox(height: 12),
                      Text(
                        payload.isEmpty
                            ? '(empty)'
                            : payload.entries
                                  .map((e) => '${e.key}: ${e.value}')
                                  .join('\n'),
                        style: onSurface,
                      ),
                      const SizedBox(height: 24),
                      Text(
                        'ReceivedAction details:',
                        style: themeData.textTheme.titleMedium?.copyWith(
                          color: themeData.colorScheme.onSurface,
                        ),
                      ),
                      const SizedBox(height: 12),
                      Text(
                        action.toString(),
                        style: themeData.textTheme.bodySmall?.copyWith(
                          color: themeData.colorScheme.onSurface,
                          fontFamily: 'monospace',
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),

            // The rounded back button.
            Positioned(
              top: mediaQueryData.padding.top + 12,
              left: 12,
              child: Container(
                height: 40,
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(12)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black26,
                      spreadRadius: 4,
                      blurRadius: 8,
                      offset: Offset(0, 4),
                    ),
                  ],
                ),
                child: IconButton(
                  alignment: Alignment.center,
                  icon: const Icon(Icons.chevron_left),
                  onPressed: () => Navigator.pop(context),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
3.44k
likes
160
points
73.7k
downloads
screenshot

Documentation

API reference

Publisher

verified publishercarda.me

Weekly Downloads

A complete solution to create Local and Push Notifications, customizing buttons, images, sounds, emoticons and applying many different layouts for Flutter apps.

Homepage
Repository (GitHub)
View/report issues
Contributing

License

Apache-2.0 (license)

Dependencies

flutter, flutter_web_plugins, intl, plugin_platform_interface, web

More

Packages that depend on awesome_notifications

Packages that implement awesome_notifications