Enable Dark Mode!
what-are-the-types-of-notifications-in-flutter.jpg
By: Farhana Jahan PT

What are the Types of Notifications in Flutter

Technical Flutter

Flutter offers rich capabilities for implementing notifications in mobile applications. Notifications are a crucial part of user engagement and can inform, alert, or remind users even when the app is in the background or terminated.

In this blog post, we'll explore the types of notifications you can implement in Flutter and the packages commonly used to support them.

Local Notifications:

Local notifications are triggered by the device rather than a server. They are ideal for reminders, scheduled alerts, or alarms within the app.

To implement local notifications in Flutter, start by importing the flutter_local_notifications package:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Next, add the following permission in your AndroidManifest.xml file located at .../android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

Now, initialize the local notifications plugin by declaring a variable:

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

Then, create a function to set up the notification configuration. You can name it anything, for example, _initializeNotification. Here's how it looks:

Future<void> _initializeNotification() async {
    try {
      const AndroidInitializationSettings androidSettings =
      AndroidInitializationSettings('@mipmap/ic_launcher');
      const InitializationSettings initSettings =
      InitializationSettings(android: androidSettings);
      final androidPlugin = flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>();
      final bool? permissionGranted =
      await androidPlugin?.requestNotificationsPermission();
      if (permissionGranted != true) {
        print("Notification permission not granted");
      }
      final bool? initialized =
      await flutterLocalNotificationsPlugin.initialize(initSettings);
      if (initialized == true) {
        print("Notifications initialized successfully");
      } else {
        print("Failed to initialize notifications");
      }
    } catch (e) {
      print("Error initializing notifications: $e");
    }
  }
  1. const AndroidInitializationSettings androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
    • This line sets up Android-specific notification initialization settings.
    • The icon '@mipmap/ic_launcher' is used as the default notification icon.
  2. const InitializationSettings initSettings = InitializationSettings(android: androidSettings);
    • Combines the platform-specific settings into a general InitializationSettings object.
    • In this case, only Android settings are provided.
  3. final androidPlugin = flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>();
    • This resolves the Android-specific implementation of the notifications plugin.
    • This is useful to access Android-only features like requesting notification permissions on Android 13+.
  4. final bool? permissionGranted = await androidPlugin?.requestNotificationsPermission();
    • Request runtime permission to post notifications (required for Android 13 and above).
    • permissionGranted will be true if permission is granted, otherwise false.
  5. final bool? initialized = await flutterLocalNotificationsPlugin.initialize(initSettings);
    • This line initializes the plugin with the settings defined earlier.
    • Returns true if successfully initialized, false otherwise.

You can define a function to display local notifications, where you set the channel ID, name, description, and other properties. You can call this function wherever you need to show a notification, for example, in initState() if you want it to appear when the page loads.

Here's the sample implementation:

  Future<void> _showNotification() async {
    try {
      const AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
        'general_channel',
        'General Notifications',
        channelDescription: 'Notifications for general updates',
        importance: Importance.max,
        priority: Priority.high,
        playSound: true,
      );
      const NotificationDetails notificationDetails =
      NotificationDetails(android: androidDetails);
      await flutterLocalNotificationsPlugin.show(
        0,
        'Hello!',
        'This is a simple local notification.',
        notificationDetails,
      );
      print("Notification shown");
    } catch (e) {
      print("Error showing notification: $e");
    }
  }

1. const AndroidNotificationDetails androidDetails = AndroidNotificationDetails

('general_channel', 

'General Notifications', 

channelDescription: 'Notifications for general updates', 

importance: Importance.max, 

priority: Priority.high, 

playSound: true, );

Creates a constant instance of AndroidNotificationDetails, which defines how the notification behaves on Android.

  • 'General_channel' – Unique ID for the notification channel.
  • 'General Notifications' – User-visible name of the channel.
  • channelDescription – Description of the channel's purpose.
  • importance: Importance.max – Notification will make noise and appear as a heads-up alert.
  • priority: Priority.high – Ensures the notification is shown prominently.
  • playSound: true – Plays the default notification sound.

2. const NotificationDetails notificationDetails = NotificationDetails(android: androidDetails);

  • Wraps the Android-specific notification settings into a platform-independent object (NotificationDetails), allowing support for multiple platforms (Android, iOS, etc.).

3. await flutterLocalNotificationsPlugin.show( 0, 'Hello!', 'This is a simple local notification.', notificationDetails, );

  • Displays the notification.

The output of the code is given below:

What are the Types of Notifications in Flutter-cybrosys

Push Notifications (Remote Notifications):

Push notifications are messages delivered from a remote server to a user's device, even when the application is not running. They are mainly used to provide timely updates and important alerts.

Key Components for Push Notifications in Flutter:

  1. Firebase Cloud Messaging (FCM) – Free, scalable solution by Google for sending push notifications.
  2. Flutter Local Notifications Plugin – Used to display notifications when the app is in the foreground.
  3. Firebase Messaging Plugin – Handles receiving messages from FCM.

So you need to import following:

import 'package:firebase_messaging/firebase_messaging.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Create a new project in Firebase and connect it to your Flutter project by adding the following configuration:

  • In the project-level build.gradle.kts file, add:
plugins {  id("com.google.gms.google-services") version "4.4.3" apply false}dependencies {    implementation(platform("com.google.firebase:firebase-bom:33.16.0"))    implementation("com.google.firebase:firebase-analytics")}

This setup enables Firebase services, including analytics, in your Flutter project.

Create a new class to initialize notifications and retrieve the Firebase Cloud Messaging (FCM) token. Once the token is obtained, it can be used to send push notifications to the device through Firebase.

class FirebaseApi {  final _firebaseMessaging = FirebaseMessaging.instance;  Future<void> initPushNotification() async {    await _firebaseMessaging.requestPermission();    final token = await _firebaseMessaging.getToken();    print("FCM Token: $token");    }}

Using this code, you will receive the FCM token as shown in the image below:

What are the Types of Notifications in Flutter-cybrosys

Navigate to Cloud Messaging and click on the Create your first campaign button.

On the next screen, select Firebase Notification Message and then click the Create button as image below:

What are the Types of Notifications in Flutter-cybrosys

You will then be directed to the Compose Notification page, where you can enter the Notification Title and Notification Text as shown below, then click on Send text message button:

What are the Types of Notifications in Flutter-cybrosys

Before clicking the Send test message button, you need to configure local notifications to display the push notification on the device.

You can do this by adding the following code:

Future<void> initPushNotification() async {
    await _firebaseMessaging.requestPermission();
    final token = await _firebaseMessaging.getToken();
    print("?? FCM Token: $token");
    const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
    const initSettings = InitializationSettings(android: androidSettings);
    await _localNotifications.initialize(initSettings);
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      const androidDetails = AndroidNotificationDetails(
        'push_channel',
        'Push Notifications',
        channelDescription: 'For displaying push notifications',
        importance: Importance.max,
        priority: Priority.high,
        playSound: true,
      );
      const notificationDetails = NotificationDetails(android: androidDetails);
      _localNotifications.show(
        0,
        message.notification?.title ?? 'No Title',
        message.notification?.body ?? 'No Body',
        notificationDetails,
      );
    });
  }

Now, you click on the Send test message button, and the screen shown below will appear. Enter the Token Key in the provided field, then click on the Test button.

What are the Types of Notifications in Flutter-cybrosys

Once you press the test button, you will be alerted on your device as shown in the accompanying image:

What are the Types of Notifications in Flutter-cybrosys

Actionable Notifications:

Users can perform actions directly from notifications, such as replying to a message or marking a task as done.

Create a function named _showActionableNotification to display an actionable notification. In this function, configure the notification details and include the actions: [] parameter to define the notification actions such as reply, mark as read, or any custom behavior as below code:

Future<void> _showActionableNotification() async {
    const AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
      'action_channel',
      'Action Channel',
      channelDescription: 'Channel with action buttons',
      importance: Importance.max,
      priority: Priority.high,
      playSound: true,
      actions: <AndroidNotificationAction>[
        AndroidNotificationAction(
          'REPLY',
          'Reply',
          inputs: <AndroidNotificationActionInput>[
            AndroidNotificationActionInput(
              label: 'Type your reply here',
            ),
          ],
        ),
        AndroidNotificationAction('MARK_READ', 'Mark as Read'),
      ],
    );
    const NotificationDetails notificationDetails =
    NotificationDetails(android: androidDetails);
    await flutterLocalNotificationsPlugin.show(
      0,
      'New Message',
      'You have a new message',
      notificationDetails,
    );
  }

1. actions: <AndroidNotificationAction> AndroidNotificationAction

    ('REPLY',

    'Reply',

    inputs: <AndroidNotificationActionInput>[

      AndroidNotificationActionInput(

        label: 'Type your reply here',

      ),

    ],

  ),

  AndroidNotificationAction('MARK_READ', 'Mark as Read'),

],


  • actions: A list of buttons that appear on the notification.
  • First Action - REPLY:
    • ID: 'REPLY'
    • Label: 'Reply'
    • Input Field: Allows the user to type a reply (inline in the notification).
    • Input Label: "Type your reply here"
  • Second Action - MARK_READ:
    • ID: 'MARK_READ'
    • Label: 'Mark as Read'
    • A simple tap button with no text input.

2. const NotificationDetails notificationDetails = NotificationDetails(android: androidDetails);

  • Wraps the Android-specific notification config into a unified NotificationDetails object.

3. await flutterLocalNotificationsPlugin.show

(  0,

  'New Message',

  'You have a new message',

  notificationDetails,

);


  • ID: 0 — unique ID for this notification (useful if you want to update or cancel it).
  • Title: 'New Message'
  • Body: 'You have a new message'
  • notificationDetails: Includes all the Android settings and actions.

The result of the above code will display a notification, as shown in the image below, where you can enter text by tapping the Reply button.

What are the Types of Notifications in Flutter-cybrosys

Notifications are a vital aspect of mobile application development, enhancing user engagement and improving the overall user experience. With Flutter, you have the flexibility to implement a variety of notification types tailored to your app’s needs:

  • Local Notifications are perfect for reminders, scheduled tasks, or alerts triggered within the device.
  • Push Notifications are messages delivered from a remote server to a user's device, even when the application is not running. They are mainly used to provide timely updates and important alerts.
  • Actionable Notifications bring interactivity to your alerts, allowing users to take quick actions like replying or marking tasks as done, all without opening the app.

By leveraging powerful packages like flutter_local_notifications and firebase_messaging, Flutter developers can create seamless and engaging notification experiences across Android and iOS platforms.

Whether you’re building a to-do app, chat application, or e-commerce platform, integrating the right type of notifications can significantly boost user retention and app usability.

To read more about How to Download & View a PDF File by Clicking the Notification in Flutter, refer to our blog How to Download & View a PDF File by Clicking the Notification in Flutter.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message