Services

Local notifications

Overview

The LocalNotifications class interacts with the flutter_local_notifications package to handle local notifications in a Flutter app. It provides methods to initialize the service, ask for permission, push local notifications, and handle notification events.

Dependencies

Before using the LocalNotifications class, make sure you have the following dependencies set up in your Flutter project:

flutter_local_notifications.dart: Dependency for handling local notifications. timezone.dart: Dependency for working with timezones. Ensure that you have imported these dependencies before using the LocalNotifications class.

Usage

This section explains how to use the LocalNotifications class and its various methods.

Initializing

To initialize the local notification service, call the init method. This method sets up the flutter_local_notifications plugin with the necessary configuration.

await LocalNotifications.init();

This is done in push/notification.dart, so we use PushNotifications class only whenever needed.

Disposing

When you no longer need the local notification service, make sure to dispose of the resources by calling the dispose method.

LocalNotifications.dispose();

Asking Permission

To ask the user for permission to display local notifications, use the askPermission method.

bool? permissionGranted = await LocalNotifications.askPermission();

The method returns a boolean indicating whether the user granted permission for local notifications.

This is also handled by main PushNotifications class, so we don't need to call this method directly.

Pushing Notifications

To send a local notification, use the push method. This method takes a PushNotification object as a parameter.

await LocalNotifications.push(notification: pushNotification);

The notification parameter is a PushNotification object representing the local notification to be sent. Ensure that the id, heading, and content properties are set accordingly.

By default, the notification will be scheduled to appear 5 seconds from the current time if no sendAfter property is provided in the PushNotification object.

Handling Notification Events

The LocalNotifications class provides an internal method, _handleNotification, to handle notification events. This method is called when a notification is tapped or interacted with by the user.

The method receives the notification's payload and action ID as parameters. Customize the _handleNotification method according to your app's requirements to handle the notification event appropriately.


Copyright © 2024