Local Notifications

Abubakar Saddique
10 min readJan 24, 2024

--

What is Notification ?? :

A notification is a message that Android displays outside your app’s UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.

To include local notification’s in your project you have to import the dependencies of the following package .

flutter pub add flutter_local_notifications

For all of the code of local notification’s i make a class of the name local notification service .


class LocalNotificationService {

}

In this class you have to write the code to manage the local notification’s .

First of all you have to initialize the local notification plugin and call it’s constructor .

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

According to the official documentation

The flutter local notification plugin Provides cross-platform functionality for displaying local notifications.

The plugin will check the platform that is running on to use the appropriate platform-specific implementation of the plugin.

Now it’s time to initialize the setting of android , ios and other platform’s .

For the initialization of the of the platform’s i make a function named as initialize settings .

  void initializeSettings( ) {

}

Now initialize the setting’s of all platform’s one by one .

 var androidInitializationSettings =
const AndroidInitializationSettings("@mipmap/ic_launcher");

Android Initialization Settings is used to initialize the settings of the android . In the parameter’s you have to provide the the app icon name .

  android:icon="@mipmap/ic_launcher">

The default icon of the flutter app .

You can find this string inside the android > app > src > main > android manifest file .

That’s all for the android initialization settings .

Now it’s time to add the initialization’s of other platforms .

The darwin initialization settings is used for ios settings .

var initializeIOSSettings = const DarwinInitializationSettings();

Linux initialization setting is used for the initialization of the settings of the linux based operating system’s .

  LinuxInitializationSettings initializeLinuxSettings =
const LinuxInitializationSettings(
defaultActionName: 'Open notification');

You have to provide a lot of properties and permission’s for ios notification that you can find in the package

In this article i only write detail about the android notification’s .

Initialize settings is used to initialize the setting’s for all of the platform’s . Here you can initialize the all of the platform’s settings that you will want’s .

  var initializeSettings = InitializationSettings(
android: androidInitializationSettings,
iOS: initializeIOSSettings,
linux: initializeLinuxSettings);

Now add the initialization setting in flutter local notification’s plugin .

Now pass the initialization settings in in the initialize method of the flutter local notifications plugin .

 flutterLocalNotificationsPlugin.initialize(
initializeSettings,

);

The initialization method of the flutter local notification plugin have some of the optional parameter’s .

Future<bool?> initialize(
InitializationSettings initializationSettings, {
void Function(NotificationResponse)? onDidReceiveNotificationResponse,
void Function(NotificationResponse)? onDidReceiveBackgroundNotificationResponse,
})

on Did Receive Background Notification Response :

Signature of callback triggered on background isolate when a user taps on a notification or a notification action.

onDidReceiveBackgroundNotificationResponse will run when you tap the notification while the app is in the background or terminated.

This will called when your app is not working or in the foreground .

Like daily reminder of your app . Messages when you are not using the app .

On Did Receive Notification Response :

Signature of callback triggered on main isolate when a user taps on a notification or a notification action.

OnDidReceiveNotificationResponse will run when you tap the notification while the app is in the foreground.

This will call when your app is running or you are working on the app .

 onDidReceiveNotificationResponse: (details) {

const String data = "Data Achieved from foreground notifications";
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const DataPage(data: data),
));


},

The above code is used to navigate the user to the screen and display the above data in it .


void initializeSettings(BuildContext context) {

var androidInitializationSettings =
const AndroidInitializationSettings("@mipmap/ic_launcher");

var initializeIOSSettings = const DarwinInitializationSettings();

LinuxInitializationSettings initializeLinuxSettings =
const LinuxInitializationSettings(
defaultActionName: 'Open notification');

var initializeSettings = InitializationSettings(
android: androidInitializationSettings,
iOS: initializeIOSSettings,
linux: initializeLinuxSettings);


flutterLocalNotificationsPlugin.initialize(
initializeSettings,

onDidReceiveNotificationResponse: (details) {

const String data = "Data Achieved from foreground notifications";
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const DataPage(data: data),
));


},
);


}

That’s all for the platform setting’s to be initialize .

Now it’s time to write code for the notification to be displayed .



var androidNotificationDetails = const AndroidNotificationDetails(
// The channel id must be unique for all of the notification's .
// Required for Android 8.0 or newer.
"channel_Id_1",
// channel name
// Required for Android 8.0 or newer.
"notification_channel_Name",

// The priority is the enum that is used to set the priority of the notification .
// /// Priority for notifications on Android 7.1 and lower.
priority: Priority.max,
// For detailed information about these topics kindly read it from the official documentation .
importance: Importance.max,
// Whether the notification sound will be played when the notification received .
// Indicates if a sound should be played when the notification is displayed.

// For Android 8.0 or newer, this is tied to the specified channel and cannot be changed after the channel has been created for the first time.
playSound: true,

// Specifies if the notification should automatically dismissed upon tapping on it.
autoCancel: false,

// Category property is used to set the category of the notification which mean's that it belong's to which category like it is alrm notification , call notification , email or message etc .
// For detailed information or categories kindly read the android notification category enum
// https://pub.dev/documentation/flutter_local_notifications/latest/flutter_local_notifications/AndroidNotificationCategory.html

// category: AndroidNotificationCategory.message ,

// color: Colors.red

channelDescription: "channel_description");

Here you have to set the detail’s that will be displayed on all of the platform’s .

Only the channel id and the channel name is required and all other properties are optional .

var iosNotificationDetails = const DarwinNotificationDetails();

In the same way you have to add the detail’s for the other platform’s .

Now set all of the platform notification detail’s in notification details class .

    var notificationDetails = NotificationDetails(
android: androidNotificationDetails, iOS: iosNotificationDetails

);

Now it’s time to call the shoe method of the flutter local notifications plugin .

    flutterLocalNotificationsPlugin.show(
0, "notification_title", "notifications _ body", notificationDetails,
payload: "Data received using payload of notification");

Here you can provide’s the detail’s that will be displayed on the notification and the optional payload if you want’s display the data using payload in onDidReceiveNotificationResponse method .

That’s all for the notification to be displayed .


void showSimpleNotification() {
// Here you have to set the detail's that will be displayed on all of the app's .

var androidNotificationDetails = const AndroidNotificationDetails(
// The channel id must be unique for all of the notification's .
// Required for Android 8.0 or newer.
"channel_Id_1",
// channel name
// Required for Android 8.0 or newer.
"notification_channel_Name",

// The priority is the enum that is used to set the priority of the notification .
// /// Priority for notifications on Android 7.1 and lower.
priority: Priority.max,
// For detailed information about these topics kindly read it from the official documentation .
importance: Importance.max,
// Whether the notification sound will be played when the notification received .
// Indicates if a sound should be played when the notification is displayed.

// For Android 8.0 or newer, this is tied to the specified channel and cannot be changed after the channel has been created for the first time.
playSound: true,

// Specifies if the notification should automatically dismissed upon tapping on it.
autoCancel: false,

// Category property is used to set the category of the notification which mean's that it belong's to which category like it is alrm notification , call notification , email or message etc .
// For detailed information or categories kindly read the android notification category enum
// https://pub.dev/documentation/flutter_local_notifications/latest/flutter_local_notifications/AndroidNotificationCategory.html

// category: AndroidNotificationCategory.message ,

// color: Colors.red

channelDescription: "channel_description");

// In the same way you have to add the detail's for the other platform's .

var iosNotificationDetails = const DarwinNotificationDetails();

// Now set all of the platform notification detail's in notification details class .
//
var notificationDetails = NotificationDetails(
android: androidNotificationDetails, iOS: iosNotificationDetails
// In the same way you have to add the notification for all of the platform you want's notification .
);

flutterLocalNotificationsPlugin.show(
0, "notification_title", "notifications _ body", notificationDetails,
payload: "Data received using payload of notification");
}

Now it’s time to get the permission from the device or the operating system to enable the notification for that specific app .

For that purpose you have to add the dependencies of following project in your app .


Future<void> checkNotificationPermission() async {
Future<PermissionStatus> permissionStatus =
NotificationPermissions.requestNotificationPermissions();
}

Now request the operating system for the permission of the notification .

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_notifications_f12_practice/data_page.dart';
import 'package:notification_permissions/notification_permissions.dart';

class LocalNotificationService {
// first of all you have to initialize the local notification plugin and call it's constructor .

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

// According to the official documentation
// The flutter local notification plugin Provides cross-platform functionality for displaying local notifications.
// The plugin will check the platform that is running on to use the appropriate platform-specific implementation of the plugin.

// Now it's time to initialize the setting of android , ios and other platform's .

void initializeSettings(BuildContext context) {
// In the parameter's of android initialization settings you have to provide .the following strings .
// @mipmap/ic_launcher
// The default icon of the flutter app .
// You can find this string in android > app > src > main > android manifest .

var androidInitializationSettings =
const AndroidInitializationSettings("@mipmap/ic_launcher");

// That's all for the android initialization settings .
// Now it's time to add the initialization s of other platforms .
// The darwin initialization settings is used for ios settings .
var initializeIOSSettings = const DarwinInitializationSettings();

LinuxInitializationSettings initializeLinuxSettings =
const LinuxInitializationSettings(
defaultActionName: 'Open notification');

// You have to provide a lot of properties and permission's for ios notification that you can find in the package
// In this article i only write detail about the android notification's .

// Initialize settings is used to initialize the setting's for all of the platform's . Here you can initialize the all of the platform's settings that you will want's .

var initializeSettings = InitializationSettings(
android: androidInitializationSettings,
iOS: initializeIOSSettings,
linux: initializeLinuxSettings);

// now add the initialization setting in flutter local notification's plugin .

// Now pass the initializations settings in in the initialize method of the flutter local notifications plugin .

flutterLocalNotificationsPlugin.initialize(
initializeSettings,

onDidReceiveNotificationResponse: (details) {

const String data = "Data Achieved from foreground notifications";
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const DataPage(data: data),
));

},
);

// That's all for the platform setting's to be initialize .
}

// Now it's time to show the notification .

void showSimpleNotification() {
// Here you have to set the detail's that will be displayed on all of the app's .

var androidNotificationDetails = const AndroidNotificationDetails(
// The channel id must be unique for all of the notification's .
// Required for Android 8.0 or newer.
"channel_Id_1",
// channel name
// Required for Android 8.0 or newer.
"notification_channel_Name",

// The priority is the enum that is used to set the priority of the notification .
// /// Priority for notifications on Android 7.1 and lower.
priority: Priority.max,
// For detailed information about these topics kindly read it from the official documentation .
importance: Importance.max,
// Whether the notification sound will be played when the notification received .
// Indicates if a sound should be played when the notification is displayed.

// For Android 8.0 or newer, this is tied to the specified channel and cannot be changed after the channel has been created for the first time.
playSound: true,

// Specifies if the notification should automatically dismissed upon tapping on it.
autoCancel: false,

// Category property is used to set the category of the notification which mean's that it belong's to which category like it is alrm notification , call notification , email or message etc .
// For detailed information or categories kindly read the android notification category enum
// https://pub.dev/documentation/flutter_local_notifications/latest/flutter_local_notifications/AndroidNotificationCategory.html

// category: AndroidNotificationCategory.message ,

// color: Colors.red

channelDescription: "channel_description");

// In the same way you have to add the detail's for the other platform's .

var iosNotificationDetails = const DarwinNotificationDetails();

// Now set all of the platform notification detail's in notification details class .
//
var notificationDetails = NotificationDetails(
android: androidNotificationDetails, iOS: iosNotificationDetails
// In the same way you have to add the notification for all of the platform you want's notification .
);

flutterLocalNotificationsPlugin.show(
0, "notification_title", "notifications _ body", notificationDetails,
payload: "Data received using payload of notification");
}


Future<void> checkNotificationPermission() async {
Future<PermissionStatus> permissionStatus =
NotificationPermissions.requestNotificationPermissions();
}
}

Now that’s all for the local notification service class . Now you only have to call these method’s on the click event or any where you want’s inside your app .

 void sendNotification() {
final LocalNotificationService _localNotificationService =
LocalNotificationService();
_localNotificationService.checkNotificationPermission();
_localNotificationService.initializeSettings(context);
_localNotificationService.showSimpleNotification();
}

That’s all for the local notification . In my case i call the above function on the click event of the floating action button .

// To include local notification's you have to import the dependencies of the following package .

// flutter pub add flutter_local_notifications
// For all of the code of local notification's i make a class of the name local notification service .

// Add the following package for the permission of the notifications to be displayed in your device .
// flutter pub add notification_permissions

import 'package:flutter/material.dart';
import 'package:flutter_notifications_f12_practice/local_notifications_service.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void sendNotification() {
final LocalNotificationService _localNotificationService =
LocalNotificationService();
_localNotificationService.checkNotificationPermission();
_localNotificationService.initializeSettings(context);
_localNotificationService.showSimpleNotification();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: sendNotification,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}

That’s for the local notifications .

I hope you have learned a lot of new thing’s 😊

Thanks for reading 📚

--

--