Vipin Vijayan
Published in

Vipin Vijayan

Local Notifications in Flutter

Local Notifications in Flutter
Local Notifications in Flutter
  • Show Simple notifications
  • Show Repeated Notifications
  • Show Scheduled Notifications
  • Show Notifications at a particular time and day of a week
  • Show Notification with an attachment
  • Show Notifications with HTML content
  • Cancel a Notification.
  • Cancel all Notifications
  • Deal with Notification Taps.

Watch Video Tutorial

Local Notification in Flutter

Add Dependencies

flutter_local_notifications: ^1.4.4+1
// Add below dependencies based on your requirement
rxdart: ^0.24.1
path_provider: ^1.6.11
http: ^0.12.1
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

Get Permission from the User

_requestIOSPermission() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
.requestPermissions(
alert: false,
badge: true,
sound: true,
);
}
Notification Permission in iOS using Flutter
Notification Permission in iOS using Flutter
initializePlatformSpecifics() {
var initializationSettingsAndroid =
AndroidInitializationSettings('app_notf_icon');
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: false,
onDidReceiveLocalNotification: (id, title, body, payload) async {
// your call back to the UI
},
);
initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
}
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String payload) async {
onNotificationClick(payload); // your call back to the UI
});

Simple Notification

Future<void> showNotification() async {
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID',
'CHANNEL_NAME',
"CHANNEL_DESCRIPTION",
importance: Importance.Max,
priority: Priority.High,
playSound: true,
timeoutAfter: 5000,
styleInformation: DefaultStyleInformation(true, true),
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, // Notification ID
'Test Title', // Notification Title
'Test Body', // Notification Body, set as null to remove the body
platformChannelSpecifics,
payload: 'New Payload', // Notification Payload
);
}
importance: Importance.Max,
priority: Priority.High,
A Simple Notification using Flutter
A Simple Notification using Flutter

Schedule a Notification

Future<void> scheduleNotification() async {
var scheduleNotificationDateTime = DateTime.now().add(Duration(seconds: 5));
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 1',
'CHANNEL_NAME 1',
"CHANNEL_DESCRIPTION 1",
icon: 'secondary_icon',
sound: RawResourceAndroidNotificationSound('my_sound'),
largeIcon: DrawableResourceAndroidBitmap('large_notf_icon'),
enableLights: true,
color: const Color.fromARGB(255, 255, 0, 0),
ledColor: const Color.fromARGB(255, 255, 0, 0),
ledOnMs: 1000,
ledOffMs: 500,
importance: Importance.Max,
priority: Priority.High,
playSound: true,
timeoutAfter: 5000,
styleInformation: DefaultStyleInformation(true, true),
);
var iosChannelSpecifics = IOSNotificationDetails(
sound: 'my_sound.aiff',
);
var platformChannelSpecifics = NotificationDetails(
androidChannelSpecifics,
iosChannelSpecifics,
);
await flutterLocalNotificationsPlugin.schedule(
0,
'Test Title',
'Test Body',
scheduleNotificationDateTime,
platformChannelSpecifics,
payload: 'Test Payload',
);
}

Show Notification Daily at a time

Future<void> showDailyAtTime() async {
var time = Time(18, 0, 0);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 4',
'CHANNEL_NAME 4',
"CHANNEL_DESCRIPTION 4",
importance: Importance.Max,
priority: Priority.High,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.showDailyAtTime(
0,
'Test Title at ${time.hour}:${time.minute}.${time.second}',
'Test Body', //null
time,
platformChannelSpecifics,
payload: 'Test Payload',
);
}

Show Weekly at Day and Time

Future<void> showWeeklyAtDayTime() async {
var time = Time(10, 0, 0);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 5',
'CHANNEL_NAME 5',
"CHANNEL_DESCRIPTION 5",
importance: Importance.Max,
priority: Priority.High,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
0,
'Test Title at ${time.hour}:${time.minute}.${time.second}',
'Test Body', //null
Day.Saturday,
time,
platformChannelSpecifics,
payload: 'Test Payload',
);
}

Repeated Notifications

Future<void> repeatNotification() async {
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 3',
'CHANNEL_NAME 3',
"CHANNEL_DESCRIPTION 3",
importance: Importance.Max,
priority: Priority.High,
styleInformation: DefaultStyleInformation(true, true),
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.periodicallyShow(
0,
'Repeating Test Title',
'Repeating Test Body',
RepeatInterval.EveryMinute,
platformChannelSpecifics,
payload: 'Test Payload',
);
}
Future<void> showNotificationWithAttachment() async {
var attachmentPicturePath = await _downloadAndSaveFile(
'https://via.placeholder.com/800x200', 'attachment_img.jpg');
var iOSPlatformSpecifics = IOSNotificationDetails(
attachments: [IOSNotificationAttachment(attachmentPicturePath)],
);
var bigPictureStyleInformation = BigPictureStyleInformation(
FilePathAndroidBitmap(attachmentPicturePath),
contentTitle: '<b>Attached Image</b>',
htmlFormatContentTitle: true,
summaryText: 'Test Image',
htmlFormatSummaryText: true,
);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL ID 2',
'CHANNEL NAME 2',
'CHANNEL DESCRIPTION 2',
importance: Importance.High,
priority: Priority.High,
styleInformation: bigPictureStyleInformation,
);
var notificationDetails =
NotificationDetails(androidChannelSpecifics, iOSPlatformSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Title with attachment',
'Body with Attachment',
notificationDetails,
);
}
_downloadAndSaveFile(String url, String fileName) async {
var directory = await getApplicationDocumentsDirectory();
var filePath = '${directory.path}/$fileName';
var response = await http.get(url);
var file = File(filePath);
await file.writeAsBytes(response.bodyBytes);
return filePath;
}
Notification with Attachment (Unexpanded)
Notification with Attachment (Expanded)

Get Pending Notifications

Future<int> getPendingNotificationCount() async {
List<PendingNotificationRequest> p =
await flutterLocalNotificationsPlugin.pendingNotificationRequests();
return p.length;
}

Cancelling Notifications

Future<void> cancelNotification() async {
await flutterLocalNotificationsPlugin.cancel(0);
}
Future<void> cancelAllNotification() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io' show File, Platform;
import 'package:http/http.dart' as http;
import 'package:rxdart/subjects.dart';class NotificationPlugin {
//
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
final BehaviorSubject<ReceivedNotification>
didReceivedLocalNotificationSubject =
BehaviorSubject<ReceivedNotification>();
var initializationSettings;
NotificationPlugin._() {
init();
}
init() async {
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (Platform.isIOS) {
_requestIOSPermission();
}
initializePlatformSpecifics();
}
initializePlatformSpecifics() {
var initializationSettingsAndroid =
AndroidInitializationSettings('app_notf_icon');
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: false,
onDidReceiveLocalNotification: (id, title, body, payload) async {
ReceivedNotification receivedNotification = ReceivedNotification(
id: id, title: title, body: body, payload: payload);
didReceivedLocalNotificationSubject.add(receivedNotification);
},
);
initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
}
_requestIOSPermission() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
.requestPermissions(
alert: false,
badge: true,
sound: true,
);
}
setListenerForLowerVersions(Function onNotificationInLowerVersions) {
didReceivedLocalNotificationSubject.listen((receivedNotification) {
onNotificationInLowerVersions(receivedNotification);
});
}
setOnNotificationClick(Function onNotificationClick) async {
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String payload) async {
onNotificationClick(payload);
});
}
Future<void> showNotification() async {
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID',
'CHANNEL_NAME',
"CHANNEL_DESCRIPTION",
importance: Importance.Max,
priority: Priority.High,
playSound: true,
timeoutAfter: 5000,
styleInformation: DefaultStyleInformation(true, true),
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Test Title',
'Test Body', //null
platformChannelSpecifics,
payload: 'New Payload',
);
}
Future<void> showDailyAtTime() async {
var time = Time(21, 3, 0);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 4',
'CHANNEL_NAME 4',
"CHANNEL_DESCRIPTION 4",
importance: Importance.Max,
priority: Priority.High,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.showDailyAtTime(
0,
'Test Title at ${time.hour}:${time.minute}.${time.second}',
'Test Body', //null
time,
platformChannelSpecifics,
payload: 'Test Payload',
);
}
Future<void> showWeeklyAtDayTime() async {
var time = Time(21, 5, 0);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 5',
'CHANNEL_NAME 5',
"CHANNEL_DESCRIPTION 5",
importance: Importance.Max,
priority: Priority.High,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
0,
'Test Title at ${time.hour}:${time.minute}.${time.second}',
'Test Body', //null
Day.Saturday,
time,
platformChannelSpecifics,
payload: 'Test Payload',
);
}
Future<void> repeatNotification() async {
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 3',
'CHANNEL_NAME 3',
"CHANNEL_DESCRIPTION 3",
importance: Importance.Max,
priority: Priority.High,
styleInformation: DefaultStyleInformation(true, true),
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(androidChannelSpecifics, iosChannelSpecifics);
await flutterLocalNotificationsPlugin.periodicallyShow(
0,
'Repeating Test Title',
'Repeating Test Body',
RepeatInterval.EveryMinute,
platformChannelSpecifics,
payload: 'Test Payload',
);
}
Future<void> scheduleNotification() async {
var scheduleNotificationDateTime = DateTime.now().add(Duration(seconds: 5));
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL_ID 1',
'CHANNEL_NAME 1',
"CHANNEL_DESCRIPTION 1",
icon: 'secondary_icon',
sound: RawResourceAndroidNotificationSound('my_sound'),
largeIcon: DrawableResourceAndroidBitmap('large_notf_icon'),
enableLights: true,
color: const Color.fromARGB(255, 255, 0, 0),
ledColor: const Color.fromARGB(255, 255, 0, 0),
ledOnMs: 1000,
ledOffMs: 500,
importance: Importance.Max,
priority: Priority.High,
playSound: true,
timeoutAfter: 5000,
styleInformation: DefaultStyleInformation(true, true),
);
var iosChannelSpecifics = IOSNotificationDetails(
sound: 'my_sound.aiff',
);
var platformChannelSpecifics = NotificationDetails(
androidChannelSpecifics,
iosChannelSpecifics,
);
await flutterLocalNotificationsPlugin.schedule(
0,
'Test Title',
'Test Body',
scheduleNotificationDateTime,
platformChannelSpecifics,
payload: 'Test Payload',
);
}
Future<void> showNotificationWithAttachment() async {
var attachmentPicturePath = await _downloadAndSaveFile(
'https://via.placeholder.com/800x200', 'attachment_img.jpg');
var iOSPlatformSpecifics = IOSNotificationDetails(
attachments: [IOSNotificationAttachment(attachmentPicturePath)],
);
var bigPictureStyleInformation = BigPictureStyleInformation(
FilePathAndroidBitmap(attachmentPicturePath),
contentTitle: '<b>Attached Image</b>',
htmlFormatContentTitle: true,
summaryText: 'Test Image',
htmlFormatSummaryText: true,
);
var androidChannelSpecifics = AndroidNotificationDetails(
'CHANNEL ID 2',
'CHANNEL NAME 2',
'CHANNEL DESCRIPTION 2',
importance: Importance.High,
priority: Priority.High,
styleInformation: bigPictureStyleInformation,
);
var notificationDetails =
NotificationDetails(androidChannelSpecifics, iOSPlatformSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Title with attachment',
'Body with Attachment',
notificationDetails,
);
}
_downloadAndSaveFile(String url, String fileName) async {
var directory = await getApplicationDocumentsDirectory();
var filePath = '${directory.path}/$fileName';
var response = await http.get(url);
var file = File(filePath);
await file.writeAsBytes(response.bodyBytes);
return filePath;
}
Future<int> getPendingNotificationCount() async {
List<PendingNotificationRequest> p =
await flutterLocalNotificationsPlugin.pendingNotificationRequests();
return p.length;
}
Future<void> cancelNotification() async {
await flutterLocalNotificationsPlugin.cancel(0);
}
Future<void> cancelAllNotification() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
}
NotificationPlugin notificationPlugin = NotificationPlugin._();class ReceivedNotification {
final int id;
final String title;
final String body;
final String payload;
ReceivedNotification({
@required this.id,
@required this.title,
@required this.body,
@required this.payload,
});
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store