Unlock the Power of Local Notifications in Your Mobile App
What Are Local Notifications?
Local notifications are a crucial aspect of mobile app development, designed to enhance user experience and drive engagement. Unlike push notifications, local notifications are scheduled by the app itself and don’t require an internet connection. Apps like Reminder and to-do apps rely heavily on local notifications to keep users informed and on track.
Implementing Local Notifications with Flutter
To get started, we’ll use the flutter_local_notifications
package to implement local notifications in both Android and iOS platforms. This package provides a simple and efficient way to schedule and manage local notifications.
Adding Dependencies and Configuring Initialization Settings
First, add the flutter_local_notifications
package to your pubspec.yaml
file:
dependencies:
flutter_local_notifications: ^9.4.0
Create a new Dart file called notification_service.dart
. This file will contain the logic for handling notifications.
Configuring Android Initialization Settings
To configure Android initialization settings, pass in a single required argument, which is the app icon that will be displayed in the notification bar:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future _configureAndroidInitialization() async {
await FlutterLocalNotificationsPlugin().initialize(
onSelectNotification: onSelectNotification,
android: AndroidInitializationSettings('com.example.app'),
);
}
Add your icon as a drawable resource to the Android head project.
Configuring iOS Initialization Settings
Configuring iOS initialization settings is a bit more complex, as you need to consider different versions of the iOS operating system:
// AppDelegate.swift
import UIKit
import FlutterLocalNotificationsPlugin
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
//...
let ios = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
FlutterLocalNotificationsPlugin().initialize(
onSelectNotification: onSelectNotification,
iOS: ios,
);
return true;
}
}
Creating the InitializationSettings Object
Create an InitializationSettings
object, which takes in three named optional parameters: android
, iOS
, and macOS
. These parameters contain the corresponding platform initialization settings arguments:
Future _configureInitializationSettings() async {
await FlutterLocalNotificationsPlugin().initialize(
onSelectNotification: onSelectNotification,
initializationSettings: InitializationSettings(
android: AndroidInitializationSettings('com.example.app'),
iOS: IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
),
),
);
}
Displaying a Notification
To display a notification, create a platform-specific NotificationDetails
instance, which takes in arguments unique to each platform:
Future _showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your channel id', 'your channel name',
channelDescription: 'your channel description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker');
const IOSNotificationDetails iosPlatformChannelSpecifics =
IOSNotificationDetails(presentAlert: true, presentBadge: true, presentSound: true);
const NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iosPlatformChannelSpecifics,
);
await FlutterLocalNotificationsPlugin().show(
0,
'plain title',
'plain body',
platformChannelSpecifics,
payload: 'item x',
);
}
Scheduling a Local Notification
To schedule a local notification, call the zoneSchedule
method of the FlutterLocalNotificationsPlugin
. This method takes in several arguments, including the scheduled date and notification details:
Future _scheduleNotification() async {
await FlutterLocalNotificationsPlugin().zoneSchedule(
0,
'cheduled title',
'cheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
android: AndroidNotificationDetails('channel id', 'channel name'),
iOS: IOSNotificationDetails(presentAlert: true, presentBadge: true, presentSound: true),
),
payload: 'item x',
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
);
}
Canceling a Local Notification
To cancel a local notification, you can either cancel a specific notification or cancel all pending notifications:
Future _cancelNotification() async {
await FlutterLocalNotificationsPlugin().cancel(0);
}
Future _cancelAllNotifications() async {
await FlutterLocalNotificationsPlugin().cancelAll();
}