How local notifications work on the Flutter Application

local notification Flutter
local notification Flutter

We all know what notifications are and how they look on our devices. It does not matter whether you have an android phone or an ios phone, they look somewhat similar in both. In this post we will discuss Flutter Local Notification and how it works and how you can implement it on your flutter application.

There are two types of notifications in any application: first is a push notification and the other is a local notification. We are not looking at push notification because this article is about local notification.  The difference between them is that the local notification originated from the device itself and the push notification came from the server.

Enough talking let’s start working on the coding part:

Step 1: Create a new project

First, create a flutter project. In order to create a flutter project, you can use this command.

flutter create notification_example_app

Inside your terminal or command prompt

Step 2: Installing dependencies

In your projects pubspec.yaml file add these lines inside dependencies

dependencies:
  flutter:
    sdk: flutter
 
 
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  flutter_local_notifications: ^9.5.3+1

Or you can add a plugin via terminal and paste these commands

flutter pub add flutter_local_notifications

To use the flutter local notification package you should give some Permissions inside your

android > app > source > main > res > Androidmanifest.xml file.

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

And add the following receivers in the same file

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

Step 3: Creating Show Notification File

Now create a file and name it show_notification.dart. This file will be our home page for the app. Now create a stateless class and name it ShowNotification just like follow

import 'package:flutter/material.dart';
 
class ShowNotification extends StatelessWidget {
  const ShowNotification({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

Now create a button like a screenshot. When we click on this button it will show a notification.

import 'package:flutter/material.dart';
 
class ShowNotification extends StatelessWidget {
  const ShowNotification({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Notification example'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('show notification'),
          onPressed: () {},
        ),
      ),
    );
  }
}
local notification Flutter
local notification Flutter

Step 4: Importing Package and Using it

Import the package in shownotification file 

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Now create a function showNotification make it async because it will take some time to show a notification.

 showNotification()async{

}

Also, create a variable type of Flutter Local Notification Plugin just like this

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();

To show notifications this plugin needs some android and IOS settings which we will do inside this function. Android needs a setting for icons to show on notifications for that just copy this code

  const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

For the Ios setting copy this code

const IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );

All this code is self-explanatory. Now we have to initialize all the two settings that we describe above

const InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
 
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
    );

We need to set AndroidNotificationChannel to show the notification it takes two mandatory arguments first is the id and the second is the name(channel name)  both are string types of variables.

 AndroidNotificationChannel channel = const AndroidNotificationChannel(
      '01',
      'Local notification',
    );

Now the last thing, the flutterLocalNotificationPlugin has a show method that will help us to show notification it’s an asynchronous process so don’t forget to wait for it.

await flutterLocalNotificationsPlugin.show(
      1,
      'my first notification',
      'a very long message for the user of app',
      NotificationDetails(
        android: AndroidNotificationDetails(channel.id, channel.name,
            channelDescription: channel.description),
      ),
    );

For the notification details, you can write the same as I wrote above. And now when our app is ready when you click on the button it will send the notification to our app just like this

local notification Flutter
local notification Flutter

The flutterLocalNotificationPlugin has several more methods for sending local notification we will discuss that in another post. I hope now you know how you can show notification to your users in your app if you have any doubt about implementing it you can connect with me or just leave a comment we will definitely get in touch with you as soon as possible.

Full Code

Main.dart File

import 'package:flutter/material.dart';
import 'package:notification_example_app/show_notification.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const ShowNotification(),
    );
  }
}

For show_notification.dart

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
 
class ShowNotification extends StatelessWidget {
  const ShowNotification({Key? key}) : super(key: key);
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Notification example'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('show notification'),
          onPressed: () async {
            showNotification();
          },
        ),
      ),
    );
  }
 
  showNotification() async {
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
 
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
 
    const IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );
    const InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
 
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
    );
 
    AndroidNotificationChannel channel = const AndroidNotificationChannel(
      'high channel',
      'Very important notification!!',
      description: 'the first notification',
      importance: Importance.max,
    );
 
    await flutterLocalNotificationsPlugin.show(
      1,
      'my first notification',
      'a very long message for the user of app',
      NotificationDetails(
        android: AndroidNotificationDetails(channel.id, channel.name,
            channelDescription: channel.description),
      ),
    );
  }
}

For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

3 thoughts on “How local notifications work on the Flutter Application”

  1. An imprеѕsive share! I hɑve just forwarded this onto a co-worker who had been conducting a little
    research on this. And he in fact bought me lunch due to the
    fact that I discovered it for him… lol.
    So let me rewоrd this…. Thank YOU for the meɑl!!
    But үeah, thanx for spending time to discuss this subject here on your web page.

  2. It’s impresѕive that you are getting thoughts from this article as well as
    from our dialogue mɑde here.

  3. What’s up to every bօdy, it’s my first go to see of this web site;
    this blog includes remarkable and truly good information dеsigned for visitors.

Comments are closed.