### Example pubspec.yaml Entry Source: https://pub.dev/packages/awesome_notifications/install This is how the dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: awesome_notifications: ^0.11.0 ``` -------------------------------- ### Run Flutter Pub Get Source: https://pub.dev/packages/awesome_notifications After adding dependencies to pubspec.yaml, run this command to fetch the packages. ```bash flutter pub get ``` -------------------------------- ### Start Listening Notification Events Source: https://pub.dev/packages/awesome_notifications/example This method should be called in the initState of your main widget to start listening for notification events. It ensures that the app can react to user interactions with notifications. ```dart NotificationController.startListeningNotificationEvents() ``` -------------------------------- ### Start Listening for Notification Events Source: https://pub.dev/packages/awesome_notifications_fcm/example Sets up listeners for notification actions, specifically the `onActionReceivedMethod` for handling user interactions with notifications. ```dart static Future startListeningNotificationEvents() async { AwesomeNotifications() .setListeners(onActionReceivedMethod: onActionReceivedMethod); } ``` -------------------------------- ### App Navigation Setup Source: https://pub.dev/packages/awesome_notifications/example Configures the initial routes and general route generation for the application. It handles navigation to the home page and a dedicated notification page. ```dart static const String routeHome = '/', routeNotification = '/notification-page'; @override void initState() { NotificationController.startListeningNotificationEvents(); super.initState(); } List> onGenerateInitialRoutes(String initialRouteName) { List> pageStack = []; pageStack.add(MaterialPageRoute( builder: (_) = const MyHomePage(title: 'Awesome Notifications Example App'))) if (initialRouteName == routeNotification && NotificationController.initialAction != null) { pageStack.add(MaterialPageRoute( builder: (_) => NotificationPage( receivedAction: NotificationController.initialAction!))); } return pageStack; } Route? onGenerateRoute(RouteSettings settings) { switch (settings.name) { case routeHome: return MaterialPageRoute( builder: (_) = const MyHomePage(title: 'Awesome Notifications Example App')); case routeNotification: ReceivedAction receivedAction = settings.arguments as ReceivedAction; return MaterialPageRoute( builder: (_) => NotificationPage(receivedAction: receivedAction)); } return null; } ``` -------------------------------- ### Import awesome_notifications_core in Dart Source: https://pub.dev/packages/awesome_notifications_core/install Import the package into your Dart files to start using its functionalities. ```dart import 'package:awesome_notifications_core/awesome_notifications_core.dart'; ``` -------------------------------- ### Configure Awesome FCM Podfile for iOS Source: https://pub.dev/packages/awesome_notifications_fcm Include this script in your Podfile to set up the Awesome Notifications FCM integration for your iOS project. Ensure you run `pod install` afterwards. ```ruby awesome_fcm_pod_file = File.expand_path(File.join('plugins', 'awesome_notifications_fcm', 'ios', 'Scripts', 'AwesomeFcmPodFile'), '.symlinks') require awesome_fcm_pod_file target 'MyAppServiceExtension' do use_frameworks! use_modular_headers! install_awesome_fcm_ios_pod_target File.dirname(File.realpath(__FILE__)) end update_awesome_fcm_service_target('MyAppServiceExtension', File.dirname(File.realpath(__FILE__)), flutter_root) ``` -------------------------------- ### Get Initial Notification Action Source: https://pub.dev/packages/awesome_notifications_fcm/example Retrieves the initial notification action that might have launched the application. This is useful for handling deep links or specific actions triggered by a notification when the app starts. ```dart static Future getInitialNotificationAction() async { ReceivedAction? receivedAction = await AwesomeNotifications() .getInitialNotificationAction(removeFromActionEvents: true); if (receivedAction == null) return; // Fluttertoast.showToast( // msg: 'Notification action launched app: $receivedAction', // backgroundColor: Colors.deepPurple // ); print('App launched by a notification action: $receivedAction'); } ``` -------------------------------- ### Start Listening to Notification Events Source: https://pub.dev/packages/awesome_notifications_fcm/example Initializes the listener for notification events. This is typically called in the application's initState. ```dart NotificationController.startListeningNotificationEvents(); ``` -------------------------------- ### Activate FlutterFire CLI Source: https://pub.dev/packages/awesome_notifications_fcm Execute this command at the root of your Flutter project to install the FlutterFire CLI. This tool is essential for integrating Firebase into your Flutter application. ```bash dart pub global activate flutterfire_cli ``` -------------------------------- ### Get Initial Notification Action Source: https://pub.dev/packages/awesome_notifications Call this method during app initialization to retrieve any notification action that launched the app. It returns `null` if the app was not started by a notification action. Ensure `removeFromActionEvents` is set appropriately if you also use `onActionReceivedMethod`. ```dart void main() async { ReceivedAction? receivedAction = await AwesomeNotifications().getInitialNotificationAction( removeFromActionEvents: false ); if(receivedAction?.channelKey == 'call_channel') setInitialPageToCallPage(); else setInitialPageToHomePage(); } ``` -------------------------------- ### Start Android Foreground Service Source: https://pub.dev/packages/awesome_notifications Initiate an Android foreground service with specified configurations. This method allows for detailed control over the service's behavior and notification display. ```dart AndroidForegroundService.startAndroidForegroundService( foregroundStartMode: ForegroundStartMode.stick, foregroundServiceType: ForegroundServiceType.phoneCall, content: NotificationContent( id: 2341234, body: 'Service is running!', title: 'Android Foreground Service', channelKey: 'basic_channel', bigPicture: 'asset://assets/images/android-bg-worker.jpg', notificationLayout: NotificationLayout.BigPicture, category: NotificationCategory.Service ), actionButtons: [ NotificationActionButton( key: 'SHOW_SERVICE_DETAILS', label: 'Show details' ) ] ); ``` -------------------------------- ### Import awesome_notifications_fcm in Dart Source: https://pub.dev/packages/awesome_notifications_fcm/install Import the package into your Dart files to start using its functionalities. ```dart import 'package:awesome_notifications_fcm/awesome_notifications_fcm.dart'; ``` -------------------------------- ### Initialize Awesome Notifications and Isolate Receive Port Source: https://pub.dev/packages/awesome_notifications/example Initializes local notifications and sets up an isolate receive port for handling notification actions. This is a crucial setup step for the notification system. ```dart Future main() async { WidgetsFlutterBinding.ensureInitialized(); // Always initialize Awesome Notifications await NotificationController.initializeLocalNotifications(); await NotificationController.initializeIsolateReceivePort(); runApp(const MyApp()); } ``` -------------------------------- ### Missing Type Annotation for Static Getter Source: https://pub.dev/packages/awesome_notifications/score This example shows a static getter `values` in `MediaSource` that is missing a type annotation. Adding explicit type annotations improves code readability and helps static analysis tools catch potential errors. ```dart static get values => [Resource, Asset, File, Network, Unknown]; ``` -------------------------------- ### Original Podfile Configuration Source: https://pub.dev/packages/awesome_notifications This is the default post_install section in an iOS Podfile before modifications. ```ruby post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) end end ``` -------------------------------- ### Main App Widget Configuration Source: https://pub.dev/packages/awesome_notifications/example Sets up the root widget of the application, including the navigator key, theme, and route generation handlers. This is the entry point for the Flutter app. ```dart class MyApp extends StatefulWidget { const MyApp({super.key}); // The navigator key is necessary to navigate using static methods static final GlobalKey navigatorKey = GlobalKey(); static Color mainColor = const Color(0xFF9D50DD); @override State createState() => _AppState(); } class _AppState extends State { // This widget is the root of your application. static const String routeHome = '/', routeNotification = '/notification-page'; @override void initState() { NotificationController.startListeningNotificationEvents(); super.initState(); } List> onGenerateInitialRoutes(String initialRouteName) { List> pageStack = []; pageStack.add(MaterialPageRoute( builder: (_) = const MyHomePage(title: 'Awesome Notifications Example App'))) if (initialRouteName == routeNotification && NotificationController.initialAction != null) { pageStack.add(MaterialPageRoute( builder: (_) => NotificationPage( receivedAction: NotificationController.initialAction!))); } return pageStack; } Route? onGenerateRoute(RouteSettings settings) { switch (settings.name) { case routeHome: return MaterialPageRoute( builder: (_) = const MyHomePage(title: 'Awesome Notifications Example App')); case routeNotification: ReceivedAction receivedAction = settings.arguments as ReceivedAction; return MaterialPageRoute( builder: (_) => NotificationPage(receivedAction: receivedAction)); } return null; } @override Widget build(BuildContext context) { return MaterialApp( title: 'Awesome Notifications - Simple Example', navigatorKey: MyApp.navigatorKey, onGenerateInitialRoutes: onGenerateInitialRoutes, onGenerateRoute: onGenerateRoute, theme: ThemeData( primarySwatch: Colors.deepPurple, ), ); } } ``` -------------------------------- ### Execute Long Task in Background Source: https://pub.dev/packages/awesome_notifications/example Simulates a long-running task in the background, including an HTTP GET request. ```APIDOC ## executeLongTaskInBackground ### Description Executes a simulated long task in the background. This includes a delay and an HTTP GET request to google.com, printing the response body to the console. ### Method `static Future executeLongTaskInBackground()` ### Parameters None ### Returns `Future` ``` -------------------------------- ### Initialize Firebase and AwesomeNotificationsFcm Source: https://pub.dev/packages/awesome_notifications_fcm Initializes Firebase and AwesomeNotificationsFcm, setting up handlers for silent data, FCM tokens, and native tokens. Ensure Firebase is available and debug mode is configured as needed. ```dart /// ********************************************* /// INITIALIZATION METHODS /// ********************************************* static Future initializeRemoteNotifications({ required bool debug }) async { await Firebase.initializeApp(); await AwesomeNotificationsFcm().initialize( onFcmSilentDataHandle: NotificationController.mySilentDataHandle, onFcmTokenHandle: NotificationController.myFcmTokenHandle, onNativeTokenHandle: NotificationController.myNativeTokenHandle, // This license key is necessary only to remove the watermark for // push notifications in release mode. To know more about it, please // visit http://awesome-notifications.carda.me#prices licenseKey: null, debug: debug); } ``` -------------------------------- ### Generate Initial Routes Source: https://pub.dev/packages/awesome_notifications_fcm/example Handles the generation of initial routes for the application, including the home page and a notification page if an initial action is present. ```dart List> onGenerateInitialRoutes(String initialRouteName) { List> pageStack = []; pageStack.add(MaterialPageRoute( builder: (_) = const MyHomePage(title: 'Awesome Notifications FCM Example App'))); final initialAction = NotificationController().initialAction; print("initial action: ${initialAction}"); if (initialAction != null) { pageStack.add(MaterialPageRoute( builder: (_) => NotificationPage(receivedAction: initialAction))); } return pageStack; } ``` -------------------------------- ### Initialize Awesome Notifications and Display Platform Version Source: https://pub.dev/packages/awesome_notifications_core/example This snippet shows how to initialize the AwesomeNotifications plugin and retrieve the platform version. It handles potential platform exceptions and ensures the UI is updated only if the widget is mounted. ```dart import 'package:awesome_notifications/awesome_notifications.dart'; import 'package:flutter/material.dart'; import 'dart:async'; import 'package:flutter/services.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { String _platformVersion = 'Unknown'; @override void initState() { super.initState(); initPlatformState(); } // Platform messages are asynchronous, so we initialize in an async method. Future initPlatformState() async { String platformVersion; // Platform messages may fail, so we use a try/catch PlatformException. // We also handle the message potentially returning null. try { platformVersion = AwesomeNotifications().toString(); } on PlatformException { platformVersion = 'Failed to get platform version.'; } // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. if (!mounted) return; setState(() { _platformVersion = platformVersion; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Awn Core example app'), centerTitle: true, ), body: Center( child: Text('Running on: $_platformVersion\n'), ), ), ); } } ``` -------------------------------- ### Request Firebase Token on Init Source: https://pub.dev/packages/awesome_notifications_fcm/example Requests the Firebase Cloud Messaging token when the application starts. This is typically called in the application's initState. ```dart NotificationController.requestFirebaseToken(); ``` -------------------------------- ### Execute Long Task in Background Source: https://pub.dev/packages/awesome_notifications_fcm/example A sample method to simulate a long-running task in the background. It includes a delay and an HTTP GET request to google.com. ```dart static Future executeLongTaskInBackground() async { print("starting long task"); await Future.delayed(const Duration(seconds: 4)); final url = Uri.parse("http://google.com"); final re = await http.get(url); print(re.body); print("long task done"); } ``` -------------------------------- ### Initialize Notification Listener for Background Actions Source: https://pub.dev/packages/awesome_notifications Set up a `ReceivePort` in your main isolate during app initialization to listen for background notification actions. Register this port with a unique name so other isolates can send messages to it. This is crucial for handling actions when the app is in the background or was launched by a notification. ```dart // Create a receive port ReceivePort port = ReceivePort(); // Register the receive port with a unique name IsolateNameServer.registerPortWithName( port, 'notification_actions', ); // Listen for messages on the receive port port.listen((var serializedData) async { print('Action running on main isolate'); final receivedAction = ReceivedAction().fromMap(serializedData); _handleActionReceived(receivedAction); }); // Set the initialization flag _initialized = true; ``` -------------------------------- ### Start Listening for Notification Events Source: https://pub.dev/packages/awesome_notifications/example Enables the listener for notification events, including actions and dismissals. This method must be called to receive any notification-related callbacks. ```dart AwesomeNotifications() .setListeners(onActionReceivedMethod: onActionReceivedMethod); ``` -------------------------------- ### Configure Android SDK and Compile Versions Source: https://pub.dev/packages/awesome_notifications Update your Android project's build.gradle file to set the minimum SDK to 23, and compile and target SDK versions to 34. Ensure Gradle version is 8.1.1 or greater. ```gradle buildscript { ... dependencies { classpath 'com.android.tools.build:gradle:8.1.1' } } android { compileSdkVersion 36 defaultConfig { minSdkVersion 23 targetSdkVersion 36 ... } ... } ``` -------------------------------- ### Add awesome_notifications_fcm to pubspec.yaml Source: https://pub.dev/packages/awesome_notifications_fcm/install This is how the dependency will appear in your `pubspec.yaml` file after running the add command. Your editor might automatically run `flutter pub get`. ```yaml dependencies: awesome_notifications_fcm: ^0.11.0 ``` -------------------------------- ### Initialize Awesome Notifications Plugin Source: https://pub.dev/packages/awesome_notifications Initialize the plugin in your main.dart file before the MaterialApp widget. Ensure you provide a native icon and at least one notification channel. ```dart AwesomeNotifications().initialize( // set the icon to null if you want to use the default app icon 'resource://drawable/res_app_icon', [ NotificationChannel( channelGroupKey: 'basic_channel_group', channelKey: 'basic_channel', channelName: 'Basic notifications', channelDescription: 'Notification channel for basic tests', defaultColor: Color(0xFF9D50DD), ledColor: Colors.white) ], // Channel groups are only visual and are not required channelGroups: [ NotificationChannelGroup( channelGroupKey: 'basic_channel_group', channelGroupName: 'Basic group') ], debug: true ); ``` -------------------------------- ### Add awesome_notifications Dependency Source: https://pub.dev/packages/awesome_notifications/install Run this command in your project's root directory to add the package to your pubspec.yaml file. ```bash $ flutter pub add awesome_notifications ``` -------------------------------- ### MyHomePage State Management Source: https://pub.dev/packages/awesome_notifications_fcm/example Initializes the notification controller listener and sets up the UI to display Firebase and native tokens. It also includes buttons to trigger notification actions. ```dart class _MyHomePageState extends State { @override void initState() { NotificationController().addListener(() => setState(() {})); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Firebase Token:', ), Padding( padding: const EdgeInsets.all(20.0), child: Text( '${NotificationController().firebaseToken}', ), ), SizedBox(height: 20), Text( 'Native Token:', ), Padding( padding: const EdgeInsets.all(20.0), child: Text( '${NotificationController().nativeToken}', ), ), SizedBox(height: 20), Padding( padding: const EdgeInsets.all(20.0), child: const Text( 'Push the button to create a new local notification or reset the badge counter', ), ), ], ), ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ FloatingActionButton( heroTag: '2', onPressed: () => NotificationController.createNewNotification(), tooltip: 'Create New notification', child: const Icon(Icons.outgoing_mail), ), SizedBox(width: 20), FloatingActionButton( heroTag: '1', onPressed: () => NotificationController.resetBadge(), tooltip: 'Reset Badge', child: const Icon(Icons.exposure_zero), ), SizedBox(width: 20), FloatingActionButton( heroTag: '0', onPressed: () => NotificationController.deleteToken(), tooltip: 'Delete token', child: const Icon(CupertinoIcons.trash), ), ], ), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } ``` -------------------------------- ### Configure Awesome Notifications Plugins in pubspec.yaml Source: https://pub.dev/packages/awesome_notifications_core Add all desired awesome notifications plugins, setting their versions to 'any' to allow awesome_notifications_core to manage them. This includes core, local, and remote push notification plugins, along with necessary Firebase dependencies. ```yaml dependencies: # Awesome plugins for local notifications awesome_notifications_core: ^0.10.0 # use the latest core version available awesome_notifications: ^0.10.0 # use the latest version available # Awesome plugins for remote push notifications awesome_notifications_fcm: ^0.10.0 # use the latest version available # Attention: # The firebase_messaging plugin is not necessary. awesome_notifications_fcm is a replacement for it # firebase_messaging: ^X.X.X # Firebase plugins necessary to use Firebase Cloud Messaging with Awesome Notifications firebase_core: ^X.X.X # use the latest available firebase_crashlytics: ^X.X.X # use the latest available ``` -------------------------------- ### Add awesome_notifications_fcm Dependency Source: https://pub.dev/packages/awesome_notifications_fcm/install Use this command to add the package to your Flutter project's dependencies. This command also implicitly runs `flutter pub get`. ```bash $ flutter pub add awesome_notifications_fcm ``` -------------------------------- ### Declare awesome_notifications_core in pubspec.yaml Source: https://pub.dev/packages/awesome_notifications_core/install This is how the dependency will appear in your pubspec.yaml file after running the add command. ```yaml dependencies: awesome_notifications_core: ^0.10.1 ``` -------------------------------- ### Create Notification with Chronometer and Timeout Source: https://pub.dev/packages/awesome_notifications Use `chronometer` to set the start time for Android notification timers and `timeoutAfter` to define an expiration duration. Both are optional `Duration` types. ```dart await AwesomeNotifications().createNotification( content: NotificationContent( id: id, channelKey: 'basic_channel', title: 'Notification with Chronometer and Timeout', body: 'This notification will start with a chronometer and dismiss after 20 seconds', chronometer: Duration.zero, // Chronometer starts to count at 0 seconds timeoutAfter: Duration(seconds: 20) // Notification dismisses after 20 seconds ) ); ``` -------------------------------- ### Schedule Notification at Specific Minute Source: https://pub.dev/packages/awesome_notifications Schedules a notification to repeat precisely at the start of every minute, using the local time zone. This ensures exact timing for recurring events. ```dart await AwesomeNotifications().createNotification( content: NotificationContent( id: id, channelKey: 'scheduled', title: 'Notification at exactly every single minute', body: 'This notification was schedule to repeat at every single minute at clock.', notificationLayout: NotificationLayout.BigPicture, bigPicture: 'asset://assets/images/melted-clock.png'), schedule: NotificationCalendar(second: 0, timeZone: localTimeZone, repeats: true)); ``` -------------------------------- ### Create a Basic Notification Source: https://pub.dev/packages/awesome_notifications Creates and displays a simple local notification with a title and body. Uses a predefined channel key and default action type. ```dart AwesomeNotifications().createNotification( content: NotificationContent( id: 10, channelKey: 'basic_channel', actionType: ActionType.Default, title: 'Hello World!', body: 'This is my first notification!', ) ); ``` -------------------------------- ### Missing Type Annotation Example Source: https://pub.dev/packages/awesome_notifications/score This code snippet highlights a missing type annotation in the `dispose` method, which is flagged during static analysis. Ensure all methods have explicit type annotations for better code clarity and maintainability. ```dart dispose(); ``` -------------------------------- ### Login to Firebase CLI Source: https://pub.dev/packages/awesome_notifications_fcm Run this command to log in to your Firebase account using your Google credentials. This is a prerequisite for using Firebase services. ```bash firebase login ``` -------------------------------- ### Get Current Notification Localization Source: https://pub.dev/packages/awesome_notifications Retrieve the current localization code being used by the plugin with the getLocalization method. This returns a two-letter language code or a combined language and region code. It defaults to the system's language if none is set. ```dart String currentLanguageCode = await AwesomeNotifications().getLocalization(); ``` -------------------------------- ### Configure Foreground Service in AndroidManifest.xml Source: https://pub.dev/packages/awesome_notifications Add the service tag to your AndroidManifest.xml to enable foreground services. Ensure the android:name attribute matches exactly, while other attributes can be configured as needed. ```xml ``` -------------------------------- ### Initialize Local Notifications Source: https://pub.dev/packages/awesome_notifications_fcm/example Configures local notification channels, including channel key, name, description, sound, importance, privacy, and color. Also retrieves the initial notification action if the app was launched by a notification. ```dart static Future initializeLocalNotifications( {required bool debug}) async { await AwesomeNotifications().initialize( null, // 'resource://drawable/res_app_icon',// [ NotificationChannel( channelKey: 'alerts', channelName: 'Alerts', channelDescription: 'Notification tests as alerts', playSound: true, importance: NotificationImportance.High, defaultPrivacy: NotificationPrivacy.Private, defaultColor: Colors.deepPurple, ledColor: Colors.deepPurple) ], debug: debug, languageCode: 'ko', ); // Get initial notification action is optional _instance.initialAction = await AwesomeNotifications() .getInitialNotificationAction(removeFromActionEvents: false); } ``` -------------------------------- ### Add awesome_notifications_core Dependency Source: https://pub.dev/packages/awesome_notifications_core/install Use this command to add the package to your project's dependencies. It automatically updates your pubspec.yaml file. ```bash $ flutter pub add awesome_notifications_core ``` -------------------------------- ### Create New Notification Source: https://pub.dev/packages/awesome_notifications/example Creates and displays a new notification. It checks for notification permissions and handles the display rationale if necessary. ```APIDOC ## createNewNotification ### Description Creates and displays a new notification with a big picture, large icon, and action buttons. It ensures notification permissions are granted before creating the notification. ### Method `static Future createNewNotification()` ### Parameters None ### Returns `Future` ### Request Example ```dart await AwesomeNotifications().createNotification( content: NotificationContent( id: -1, // -1 is replaced by a random number channelKey: 'alerts', title: 'Huston! The eagle has landed!', body: "A small step for a man, but a giant leap to Flutter's community!", bigPicture: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png', largeIcon: 'https://storage.googleapis.com/cms-storage-bucket/0dbfcc7a59cd1cf16282.png', notificationLayout: NotificationLayout.BigPicture, payload: {'notificationId': '1234567890'}) actionButtons: [ NotificationActionButton(key: 'REDIRECT', label: 'Redirect'), NotificationActionButton( key: 'REPLY', label: 'Reply Message', requireInputText: true, actionType: ActionType.SilentAction), NotificationActionButton( key: 'DISMISS', label: 'Dismiss', actionType: ActionType.DismissAction, isDangerousOption: true) ]); ``` ``` -------------------------------- ### Register Plugins for Background Actions in iOS AppDelegate Source: https://pub.dev/packages/awesome_notifications_fcm Manually register plugins within the `didFinishLaunchingWithOptions` method of your iOS project's AppDelegate.m/AppDelegate.swift file to enable their use in background notification actions. This prevents MissingPluginException errors. ```swift import Flutter import awesome_notifications import shared_preferences_ios //import all_other_plugins_that_i_need override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) // This function register the desired plugins to be used within a notification background action SwiftAwesomeNotificationsPlugin.setPluginRegistrantCallback { registry in SwiftAwesomeNotificationsPlugin.register( with: registry.registrar(forPlugin: "io.flutter.plugins.awesomenotifications.AwesomeNotificationsPlugin")!) FLTSharedPreferencesPlugin.register( with: registry.registrar(forPlugin: "io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")!) } // This function register the desired plugins to be used within silent push notifications SwiftAwesomeNotificationsFcmPlugin.setPluginRegistrantCallback { registry in SwiftAwesomeNotificationsPlugin.register( with: registry.registrar(forPlugin: "io.flutter.plugins.awesomenotifications.AwesomeNotificationsPlugin")!) FLTSharedPreferencesPlugin.register( with: registry.registrar(forPlugin: "io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")!) } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } ``` -------------------------------- ### Set Up Notification Listeners in MyApp Source: https://pub.dev/packages/awesome_notifications Initialize static listeners for notification events within the initState method of your main application widget. This ensures that notification actions are captured after the widget is initialized. ```dart class MyApp extends StatefulWidget { static final GlobalKey navigatorKey = GlobalKey(); static const String name = 'Awesome Notifications - Example App'; static const Color mainColor = Colors.deepPurple; @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { @override void initState() { // Only after at least the action method is set, the notification events are delivered AwesomeNotifications().setListeners( onActionReceivedMethod: NotificationController.onActionReceivedMethod, onNotificationCreatedMethod: NotificationController.onNotificationCreatedMethod, onNotificationDisplayedMethod: NotificationController.onNotificationDisplayedMethod, onDismissActionReceivedMethod: NotificationController.onDismissActionReceivedMethod ); super.initState(); } // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // The navigator key is necessary to allow to navigate through static methods navigatorKey: MyApp.navigatorKey, title: MyApp.name, color: MyApp.mainColor, initialRoute: '/', onGenerateRoute: (settings) { switch (settings.name) { case '/': return MaterialPageRoute(builder: (context) => MyHomePage(title: MyApp.name) ); case '/notification-page': return MaterialPageRoute(builder: (context) { final ReceivedAction receivedAction = settings .arguments as ReceivedAction; return MyNotificationPage(receivedAction: receivedAction); }); default: assert(false, 'Page ${settings.name} not found'); return null; } }, theme: ThemeData( primarySwatch: Colors.deepPurple ), ); } } ``` -------------------------------- ### Initialize Isolate Receive Port for Notification Actions Source: https://pub.dev/packages/awesome_notifications/example Sets up a ReceivePort to listen for notification actions from other isolates. This is essential for redirecting notification events to the main isolate for processing. ```dart receivePort = ReceivePort('Notification action port in main isolate') ..listen( (silentData) => onActionReceivedImplementationMethod(silentData)); // This initialization only happens on main isolate IsolateNameServer.registerPortWithName( receivePort!.sendPort, 'notification_action_port'); ``` -------------------------------- ### Home Page Widget Source: https://pub.dev/packages/awesome_notifications/example The main page of the application, displaying a title and buttons to trigger notification actions. It serves as the primary user interface for interacting with the notification features. ```dart class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Text( 'Push the buttons below to create new notifications', ), ], ), ), floatingActionButton: Padding( padding: const EdgeInsets.all(20.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const SizedBox(width: 20), FloatingActionButton( heroTag: '1', onPressed: () => NotificationController.createNewNotification(), tooltip: 'Create New notification', child: const Icon(Icons.outgoing_mail), ), const SizedBox(width: 10), FloatingActionButton( heroTag: '2', onPressed: () => NotificationController.scheduleNewNotification(), tooltip: 'Schedule New notification', child: const Icon(Icons.access_time_outlined), ), const SizedBox(width: 10), FloatingActionButton( heroTag: '3', onPressed: () => NotificationController.resetBadgeCounter(), tooltip: 'Reset badge counter', ``` -------------------------------- ### Handle Notification Creation Source: https://pub.dev/packages/awesome_notifications Callback for when a new notification or schedule is created. Implement custom logic here. ```dart static Future onNotificationCreatedMethod(ReceivedNotification receivedNotification) async { // Your code goes here } ``` -------------------------------- ### Add Android Permissions to Manifest Source: https://pub.dev/packages/awesome_notifications Declare necessary permissions like VIBRATE and RECEIVE_BOOT_COMPLETED in your AndroidManifest.xml to enable notification features. ```xml ... ```