Skip to content

Instantly share code, notes, and snippets.

@nooralibutt
Created December 23, 2020 06:23
Show Gist options
  • Save nooralibutt/3e089f50c0d0ef0d2b4bfba54211fd1b to your computer and use it in GitHub Desktop.
Save nooralibutt/3e089f50c0d0ef0d2b4bfba54211fd1b to your computer and use it in GitHub Desktop.
Integration guide of local notifications in Flutter

Integrating Notifcation Manager

1. Integrate plugin

Go to pubspec.yaml and add dependency from here

2. Add icon

app_icon needs to be a added as a drawable resource to the Android head project. Path should be as follows

project-name/android/app/src/main/res/drawable/app_icon.png

Note: Icon should be a material icon for android. It will be grayed out.

3. Integrate Notification Manager class

Notification manager class depends on Strings.dart which is mainly being used for two strings mentioned here

Strings.package and Strings.app_name

You can either use strings class or just replace these two with your app name and package name

4. Initialize notificationn class

Initialize notification manager in your first screen. If your first screen is stateful widget then integrate it in init method else initialize in build method if its a stateless widget

NotificationManager.instance.init()

4. Schedule notifications

Now in order to schedule notifications there are many methods inside notifcations class but we are use following code block right now

scheduleAllNotifications(List<NotificationModel> data) async {
    await _cancelAllNotifications();

    var days = 1;
    data.forEach((item) {
      _scheduleNotificationDaily(item, Duration(days: days));
      days += 7;
    });
}

I am cancelling all the notifications scheduled before and scheduling it again. You can use your own logic to implement this method.

In order to send it data we are using season class as follows:

NotificationManager.instance.scheduleAllNotifications(Season.data()
        .map((e) => NotificationModel(
            id: e.hashCode, title: e.title, body: e.description))
        .toList());

I am building notification model and sending all the notifications at once.

and Voila. You are done.

import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'strings.dart';
class NotificationManager {
static final NotificationManager _instance = NotificationManager._internal();
static NotificationManager get instance => _instance;
factory NotificationManager() {
return _instance;
}
NotificationManager._internal();
static const androidDetails = AndroidNotificationDetails(Strings.package,
Strings.app_name, 'Our notifications will be displayed here',
importance: Importance.max, priority: Priority.high, showWhen: false);
final _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
init() async {
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const androidSettings = AndroidInitializationSettings('app_icon');
final iOSSettings = IOSInitializationSettings(
onDidReceiveLocalNotification: _onDidReceiveLocalNotification);
final settings =
InitializationSettings(android: androidSettings, iOS: iOSSettings);
_flutterLocalNotificationsPlugin.initialize(settings,
onSelectNotification: _onSelectNotification);
tz.initializeTimeZones();
}
Future _onDidReceiveLocalNotification(
int id, String title, String body, String payload) async {
print('NAB $payload');
}
Future _onSelectNotification(String payload) async {
if (payload != null) {
print('notification payload: $payload');
}
print('NAB $payload');
}
scheduleAllNotifications(List<NotificationModel> data) async {
await _cancelAllNotifications();
var days = 1;
data.forEach((item) {
_scheduleNotificationDaily(item, Duration(days: days));
days += 7;
});
}
Future<void> _scheduleNotificationDaily(
NotificationModel model, Duration duration) async {
await _flutterLocalNotificationsPlugin.zonedSchedule(
model.id,
model.title,
model.body,
tz.TZDateTime.now(tz.local).add(duration),
const NotificationDetails(android: androidDetails),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
}
Future<void> _scheduleNotificationPeriodically(
NotificationModel model) async {
await _flutterLocalNotificationsPlugin.periodicallyShow(
model.id,
model.title,
model.body,
RepeatInterval.daily,
const NotificationDetails(android: androidDetails),
androidAllowWhileIdle: true);
}
Future<void> _cancelAllNotifications() =>
_flutterLocalNotificationsPlugin.cancelAll();
}
class NotificationModel {
NotificationModel({
@required this.id,
@required this.title,
@required this.body,
this.payload,
});
final int id;
final String title;
final String body;
final String payload;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment