Let’s Implement Local Notifications with Flutter

Clear guidance to implement how to make enable Local Notifications in your mobile app with flutter

Sajeevan Wickramarathna
Level Up Coding

--

GIF by Author

Mobile application notifications are playing a significant role when we deal with them because they are used to make our attention to a particular app when we are away from it. Therefore in that situation, there are 2 major types of notifications when dealing with mobile development.

  1. Local Notification
  2. Push Notification

In this article, I would like to focus on some important points and a way to implement local notifications in your mobile app.

Local Notification — Notifications that are generating the application itself.

Push Notification — Notifications that are triggering through a remote server.

Above mentioned factors are the difference between Local Notifications and Push Notifications.

To be more aware let’s implement some code and observe how Local Notifications deal with mobile applications. Here Flutter is the framework that I used to implement the Push Notifications task because we can easily and effectively do it because Flutter contains an already built package for Flutter Push Notifications.

After your creating your flutter project it is necessary to add the flutter_local_notifications package into your pubspec.yaml file under dependencies. It will help you to effectively deal with the Push Notification tasks.

dependencies:
flutter_local_notifications: ^8.0.0

Then import the package into the necessary place of coding.

import 'package:flutter_local_notifications/
flutter_local_notifications.dart';

Let’s Set Up the Project 😃

  1. Your AndroidManifest file should be edited as follows to take the ability for scheduled notifications:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

Inside the application section:

<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"></action></intent-filter></receiver><receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />

In order to obtain the vibration permission:

<uses-permission android:name="android.permission.VIBRATE" />

Now you have complete the editing section of the AndroidManifest file.

2. Then we need to add a notification icon for when Local Push Notifications. Therefore add an image under the drawable directory and it’s path is flutter_app_name > android > app > src > res > drawable > flutter_devs.png

image by Author

If not, you can avoid adding notification icons by using the app icon that is stored in the mipmap for Android.

3. Adding custom Tone / Music for the Notification

You can skip this step then the tone for the notification is the default tone of your notification.

Under flutter_app_name >android > app > src > res >raw>mixkit-bell-notification-933.wav, make a directory and add a preferred name for it, mine is notification_tone.

image by Author

Store a small size music file inside the created directory

OK Cool , let’s start coding… 😜

  1. Create a Flutter Local Notification object
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =FlutterLocalNotificationsPlugin();

The purpose of creating a Flutter Local Notification object is to perform various operations on that object.

2. Create an initState

void initState() {super.initState();var initializationSettingsAndroid =AndroidInitializationSettings('flutter_devs');var initializationSettingsIOs = IOSInitializationSettings();var initSetttings = InitializationSettings(initializationSettingsAndroid, initializationSettingsIOs);flutterLocalNotificationsPlugin.initialize(initSetttings,onSelectNotification: onSelectNotification);}
  • AndroidInitializationSettings — it is the class to initialize the settings for android devices
  • IOSInitializationSettings — it is the class to initialize the settings for ios devices
  • InitializationSettings — the purpose of this is to initialize the settings for android and ios platforms
  • initialize() method — set the setting according to the platform of the device such that if the device is android your app will perform according to the android specific settings and if ios, it enables ios specific settings.
  • onSelectNotification — this property performs the task given on pressing the notification
Future onSelectNotification(String payload) {Navigator.of(context).push(MaterialPageRoute(builder: (_) {return NewScreen(payload: payload,);
}));
}

The new screen that appears after the user presses the notification will be implemented in a NewScreen Widget as below.

class NewScreen extends StatelessWidget {String payload;NewScreen({@required this.payload,});@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text(payload),),);}}
  1. Simple Notification — a basic notification example
showNotification() async {var android = new AndroidNotificationDetails('id', 'channel ', 'description',priority: Priority.High, importance: Importance.Max);var iOS = new IOSNotificationDetails();var platform = new NotificationDetails(android, iOS);await flutterLocalNotificationsPlugin.show(0, 'Flutter devs', 'Flutter Local Notification Demo', platform,payload: 'Welcome to the Local Notification demo ');}
  • AndroidNotificationDetails — containing details about the notification on android devices

Eg: priority, importance, channel, name, channel description, channel id, sound, vibration

*******************************************************************

It is important to mention that, the sound file that you saved inside the project can be set to the sound parameter under the AndroidNotificationDetails

*******************************************************************

Thus, IOSNotificationDetails contains the ios notification details.

Further, NotificationDetails can be used when your app is specific to either android or ios then you do not need to provide the details of android and ios and you can simply pass null in android or ios.

  • show() — check for availability of the platform whether it is ios and android then if the platform is android, AndroidNotificationDetails sets as the notification details. Hence show() takes the id, title, body, NotificationDetails, payload as a string and then we can pass it as an argument for onSelectionNotification
  • onSelectionNotification — display some text on the new screen based on the type of notification clicked.

2. Schedule Notification — used to perform a scheduled task and implemented notification occurs at a specific time.

Future<void> scheduleNotification() async {var scheduledNotificationDateTime =DateTime.now().add(Duration(seconds: 4));var androidPlatformChannelSpecifics = AndroidNotificationDetails('channel id','channel name','channel description',icon: 'flutter_devs',largeIcon: DrawableResourceAndroidBitmap('flutter_devs'),);var iOSPlatformChannelSpecifics = IOSNotificationDetails();var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);await flutterLocalNotificationsPlugin.schedule(0,'scheduled title','scheduled body',scheduledNotificationDateTime,platformChannelSpecifics);}

3. Big Picture Notification — used to display a larger notification icon

image by Author
Future<void> showBigPictureNotification() async {var bigPictureStyleInformation = BigPictureStyleInformation(DrawableResourceAndroidBitmap("flutter_devs"),largeIcon: DrawableResourceAndroidBitmap("flutter_devs"),contentTitle: 'flutter devs',htmlFormatContentTitle: true,summaryText: 'summaryText',htmlFormatSummaryText: true);var androidPlatformChannelSpecifics = AndroidNotificationDetails('big text channel id','big text channel name','big text channel description',styleInformation: bigPictureStyleInformation);var platformChannelSpecifics =NotificationDetails(androidPlatformChannelSpecifics, null);await flutterLocalNotificationsPlugin.show(0, 'big text title', 'silent body', platformChannelSpecifics,payload: "big image notifications");}

4. Media Notification — notification icon will be displayed in a minimized manner.

image by Author
Future<void> showNotificationMediaStyle() async {var androidPlatformChannelSpecifics = AndroidNotificationDetails('media channel id','media channel name','media channel description',color: Colors.blue,enableLights: true,largeIcon: DrawableResourceAndroidBitmap("flutter_devs"),styleInformation: MediaStyleInformation(),);var platformChannelSpecifics =NotificationDetails(androidPlatformChannelSpecifics, null);await flutterLocalNotificationsPlugin.show(0, 'notification title', 'notification body', platformChannelSpecifics,payload: "show Notification Media Style");}

5. Cancel Notification — removes the notification of the given id

Future<void> cancelNotification() async {await flutterLocalNotificationsPlugin.cancel(0);}

Conclusion

This article provides details about how to handle Local Notification in an efficient manner using Flutter. Local Notification is important because it is the way of generating notifications application itself and no need for a network connection.

I hope this article provides some major opportunities to enhance your knowledge based on implementing local notifications using Flutter with clear guidance and if you think so hit a clap.

GitHub repository for full code …

Thank you for reading! 🙌

--

--

Final Year Undergraduate at Faculty of Information Technology, University of Moratuwa. Tech enthusiast and Dedicated.