How to Add Local Notifications in Flutter?
Last Updated :
24 Apr, 2025
A push notification is a short message that appears as a pop-up on your desktop browser, mobile home screen, or in your device notification center from a mobile app. For receiving and showcasing push notifications in flutter using local_notifications. There are 3 conditions when we receive notifications
- When the app is closed.
- When the app is opened and the user is using it.
- When the app is not opened not it is completely closed. It is running in the background.
Here we will handle all the notifications.
Step By Step Implementation
Step 1: Create a Flutter project
flutter create .
Step 2: Add local notification package
// Add in dependencies in pubspec.yaml file
flutter_local_notifications:
Step 3: Create 1 class for adding all local notifications functions and add an Instance of local notification in it
Dart
class LocalNotificationService {
static final FlutterLocalNotificationsPlugin _notificationsPlugin =
FlutterLocalNotificationsPlugin();
}
|
Step 4: Add initialize function in this class
Dart
static void initialize() {
const InitializationSettings initializationSettingsAndroid =
InitializationSettings(
android: AndroidInitializationSettings( "@drawable/ic_launcher" ));
_notificationsPlugin.initialize(
initializationSettingsAndroid,
onDidReceiveNotificationResponse: (details) {
if (details.input != null) {}
},
);
}
|
Step 5: Call this function in the Widget you are putting in the runApp function like this
Dart
Future main() async {
runApp( const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
LocalNotificationService.initialize();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo' ,
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const MyHomePage(title: 'Flutter Demo Home Page' ),
);
}
}
|
Step 6: For handling all these conditions we have to add firebase messaging and for this add firebase to your flutter project
To add firebase to your project read this article How to Add Firebase to Flutter App.
Step 7: To handle background notifications add this to the main function
Dart
Future main() async {
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
runApp( const MyApp());
}
Future backgroundHandler(RemoteMessage msg) async {}
|
Step 8: Now to handle the other 2 conditions add this in the init function below initialization of local notification
Dart
@override
void initState() {
super.initState();
LocalNotificationService.initialize();
FirebaseMessaging.instance.getInitialMessage().then((message) {
});
FirebaseMessaging.onMessage.listen((message) {
if (message.notification != null) {
LocalNotificationService.display(message);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
print( "on message opened app" );
});
}
|
Step 9: To display notifications you have to add this function in the local notification
Dart
static Future< void > display(RemoteMessage message) async {
try {
print(message.notification!.android!.sound);
final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
NotificationDetails notificationDetails = NotificationDetails(
android: AndroidNotificationDetails(
message.notification!.android!.sound ?? "Channel Id" ,
message.notification!.android!.sound ?? "Main Channel" ,
groupKey: "gfg" ,
color: Colors.green,
importance: Importance.max,
sound: RawResourceAndroidNotificationSound(
message.notification!.android!.sound ?? "gfg" ),
playSound: true ,
priority: Priority.high),
);
await _notificationsPlugin.show(id, message.notification?.title,
message.notification?.body, notificationDetails,
payload: message.data[ 'route' ]);
} catch (e) {
debugPrint(e.toString());
}
|
Also, add these settings to the android folder
1. Create a file named colors.xml in android/app/src/main/res/values and add these codes to this file
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< color name = "green" >#00FF00</ color >
</ resources >
|
2. Add this code in android/app/src/main/AndroidManifest.xml
XML
< meta-data android:name = "com.google.firebase.messaging.default_notification_icon"
android:resource = "@drawable/ic_launcher" >
< meta-data android:name = "com.google.firebase.messaging.default_notification_color"
android:resource = "@color/green" >
|
Note:
If you want to receive notifications you need 1 token which is unique for every phone and may expire in some time. You need to store this token in your server if you want to send notifications to individual people To get the token you can use this function of firebase messaging
Dart
var notifyToken = FirebaseMessaging.instance.isSupported()
? await FirebaseMessaging.instance
.getToken()
: "notifyToken" ;
|
Now you can receive notifications on your android phone. For receiving notifications on the web you have to do the following settings. Create this file in the web folder and named as firebase-messaging-sw.js
Javascript
const firebaseConfig = {
apiKey: "YOur Key-EW_U6NZU-A" ,
authDomain: "flutter-notification-test-gfg.firebaseapp.com" ,
projectId: "flutter-notification-tes-fec9d" ,
storageBucket: "flutter-dsd-tes-fec9d.gfg.com" ,
messagingSenderId: "263307381024" ,
appId: "1:263307381024:web:dsds" ,
measurementId: "G-dsada"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage( function (payload) {
console.log( 'Received background message ' , payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
|
3. Do the following changes in index.html
HTML
<!DOCTYPE html>
< html >
< head >
< meta charset = "UTF-8" >
< title >flutter_notification_test</ title >
</ head >
< body >
< script >
const firebaseConfig = {
apiKey: "your key-EW_U6NZU-A",
authDomain: "flutter-notification-temp-fec9d.gfg.com",
projectId: "flutter-notification-tes-fec9d",
storageBucket: "flutter-dasdadas-tes-fec9d.appspot.com",
messagingSenderId: "dasdsa",
appId: "1:263307381024:web:dsadads",
measurementId: "G-dsadsa"
};
firebase.initializeApp(firebaseConfig);
</ script >
< script src = "main.dart.js" type = "application/javascript" ></ script >
< script >
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</ script >
</ body >
</ html >
|
4. Add this function in location_notification_service.dart file in the lib folder
Dart
void messageListener(BuildContext context) {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print( 'Got a message in the foreground!' );
print( 'Message data: ${message.data}' );
if (message.notification != null) {
print(
'Message also contained a notification: so it will pop up ${message.notification.body}' );
showDialog(
context: context,
builder: ((BuildContext context) {
return DynamicDialog(
title: message.notification.title,
body: message.notification.body);
}));
}
});
}
|
For dynamic dialog either add this code below localnotificationservice class file or create a new file
Dart
import 'package:flutter/material.dart' ;
class DynamicDialog extends StatefulWidget {
final title;
final body;
const DynamicDialog({ this .title, this .body});
@override
_DynamicDialogState createState() => _DynamicDialogState();
}
class _DynamicDialogState extends State<DynamicDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(widget.title),
actions: <Widget>[
OutlinedButton.icon(
label: const Text( 'Close' ),
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(Icons.close))
],
content: Text(widget.body),
);
}
}
|
Call these functions below the initialization of the local_notification service like this
Dart
@override
void initState() {
super.initState();
LocalNotificationService.initialize();
LocalNotificationService.messageListener(context);
FirebaseMessaging.onBackgroundMessage(backgroundHandler);
FirebaseMessaging.instance.getInitialMessage().then((message) {
print( "Initial Message ${message.toString()}" );
});
FirebaseMessaging.onMessageOpenedApp.listen((event) {
print( "Message on App opened ${event.toString()}" );
});
FirebaseMessaging.onMessage.listen((event) {
print( "Message when it is termination mode ${event.toString()}" );
if (event.notification != null) {
LocalNotificationService.display(event);
}
});
}
|

Similar Reads
Background local notifications in Flutter
Sometimes user wants some essential features like the latest news updates, latest articles updates, weather condition alert, complete his/her profile update, future events update and much more in his/ her Android or iOS device without opening App and if you would like to develop this kind of Android
6 min read
Flutter - Schedule Local Notification using Timezone
In this article, we will explore the process of scheduling local notifications using the Timezone package in Flutter. Local Notification:Flutter Local Notification is a cross-platform plugin used to show notifications in the Flutter application. These notifications can be simple, scheduled, or perio
6 min read
NotificationListener Widget in Flutter
In Flutter, every Scrollable sends Notifications that contain information about the current scroll state. So to catch these notifications we use NotificationListener Widget. NotificationListener Widget will listen for Notifications bubbling up the tree. In this, article we will learn about Notificat
4 min read
How to Add Splash Screen in Flutter App?
We all have heard of Flutter right, it's a cross-platform application development tool. Flutter can be used to make Android, IOS, and Web applications with just one code base (Dart programming language). In this article let's see how we can add a splash screen to our applications. What is Splash Scr
3 min read
How to Install Packages in Flutter?
In this article, we will look into the process of installing packages in flutter. Before we start incorporating a package, first let's understand briefly what are Flutter Packages. Flutter packages are open source libraries of code written and maintained by someone else, which we can incorporate in
3 min read
How to Install Flutter on Linux?
In this article, we will learn how to install Flutter in Linux Flutter is an open-source UI software development kit created by Google. It is used to develop cross-platform applications for Android, iOS, Linux, Mac, Windows, Google Fuchsia, and the web from a single codebase. Installing Flutter on L
2 min read
Application Localization in Flutter
In mobile applications, Localization is the process of adapting an application to support multiple languages and regional settings. This allows your app to be more accessible to users from different parts of the world. In Flutter, for implementing Localization flutter_localization is a package used
4 min read
How to Get MAC Address of Device in Flutter?
Flutter SDK is an open-source software development kit by Google to develop applications for multiple platforms from a single codebase. Sometimes, your app needs to know the MAC address of the device. MAC (Media Access Control) address is the unique identifier of a device on a LAN network. Approach:
2 min read
How to Add Multiple Markers on Google Map in Flutter?
Google Maps is one of the popular apps used nowadays for navigation or locating markers on Google Maps. We have seen markers on Google Maps for various locations. In this article, we are going to see how to implement multiple markers on Google Maps in Flutter. Step By Step ImplementationStep 1: Crea
4 min read
How to Change Package Name in Flutter?
Every Flutter app has a package name that uniquely identifies your app on the Google Play Store and Apple App Store. In this article, we will learn how to change the package name with a simple and easy method. The package name is basically a unique identity to identify that app on App Store, Play St
2 min read