Local Notifications in Flutter
Everything you need to get started with local notifications in flutter(Android/iOS)
Table of contents
No headings in the article.
Being a developer and a user, I think notifications are a very important part of our lives.
We as developers use notifications in 2 ways
To gain the user's attention.
To notify users about something, for example, download completed, order placed, etc.
In this blog, we will use notifications to notify users about something happening in the app and for this we will use " Local Notifications ".
we will start by creating a new flutter project.
we will use the flutter_local_notifications 13.0.0
package in this project for local notifications.
You can use the below link to get this package and add it to your pubspec.yaml file in your project.
After adding this package to your pubspec.yaml
file. Run the "flutter pub get" command from the terminal to use this package in your project.
Now, main.dart
looks like this,
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Local Notifications',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Local Notifications'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: const Center(),
);
}
}
Now we need to start coding for our local notifications.
we need to add this code at the top level in main.dart
.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin(); // instance of flutterLocalNotificationsPlugin
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@mipmap/ic_launcher'); // for android
const DarwinInitializationSettings darwinInitializationSettings =
DarwinInitializationSettings(); // for iOS
InitializationSettings initializationSettings = const InitializationSettings(
android: androidInitializationSettings,
iOS: darwinInitializationSettings,
);
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
this line is used to instantiate the flutterlocalnotificationplugin.
const AndroidInitializationSettings androidInitializationSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
this is for initializing notifications settings in android with the app icon. This @mipmap/ic_launcher
is the app icon.
const DarwinInitializationSettings darwinInitializationSettings = DarwinInitializationSettings();
this is for initializing notification settings in iOS.
InitializationSettings initializationSettings = const InitializationSettings( android: androidInitializationSettings, iOS: darwinInitializationSettings, );
now to initialize everything together for notifications, we set all of these settings to InitializationSettings
. Now we will use this in main
function to initialize our flutterlocalnotificationsPlugin
instance.
This is how our main
function looks
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
runApp(const MyApp());
}
WidgetsFlutterBinding.ensureInitialized();
it is used to bind the whole widget tree and to run the async functions in the main function.
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
it is used to initialize our flutterLocalNotificationsPlugin
instance with the settings of android and iOS notifications.
After all these additions out main.dart
looks like
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'homepage.dart';
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin(); // instance of flutterLocalNotificationsPlugin
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('@mipmap/ic_launcher'); // for android
const DarwinInitializationSettings darwinInitializationSettings =
DarwinInitializationSettings(); // for iOS
InitializationSettings initializationSettings = const InitializationSettings(
android: androidInitializationSettings,
iOS: darwinInitializationSettings,
);
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Local Notifications',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Local Notifications'),
);
}
}
Now we will create a simple UI and will write some more code to send the notification.
our homepage.dart
look like this,
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
},
child: const Text("Send Notification")),
),
);
}
}
UI looks like,
Now in onPressed
function of the button we will write the code to send the notifications.
int id = Random().nextInt(10000);
AndroidNotificationDetails androidNotificationDetails =
const AndroidNotificationDetails(
"Local Notification", "Local Notification",
importance: Importance.max,
priority: Priority.max,
onlyAlertOnce: true,
enableVibration: true,
playSound: true);
DarwinNotificationDetails darwinNotificationDetails =
const DarwinNotificationDetails();
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails,
iOS: darwinNotificationDetails);
await flutterLocalNotificationsPlugin.show(id, "Hello everyone",
"I am a notification", notificationDetails);
},
int id = Random().nextInt(10000);
this is to get a random number between (0-10000) for the unique id of the notification.
Every notification should have it's unique id.
Next are the specific notification details of each platform Android and iOS respectively.
await flutterLocalNotificationsPlugin.show(id, "Hello everyone", "I am a notification", notificationDetails); },
here we are using flutterLocalNotificationsPlugin
instance to show the notification with unique id
, title
, sub subtitle
and notification details
of each platform.
now after adding all the code homepage.dart
looks like
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'main.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
int id = Random().nextInt(10000);
AndroidNotificationDetails androidNotificationDetails =
const AndroidNotificationDetails(
"Local Notification", "Local Notification",
importance: Importance.max,
priority: Priority.max,
onlyAlertOnce: true,
enableVibration: true,
playSound: true);
DarwinNotificationDetails darwinNotificationDetails =
const DarwinNotificationDetails();
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails,
iOS: darwinNotificationDetails);
await flutterLocalNotificationsPlugin.show(id, "Hello everyone",
"I am a notification", notificationDetails);
},
child: const Text("Send Notification")),
),
);
}
}
This is it for the android
part now you can start sending notifications from your app to the user.
But for iOS, you have to add some more code to AppDelegate.swift
inside the override function application.
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
After adding this to AppDelegate.swift
it looks like this,
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
This is it. We are done!!!
UI looks like this.
Now you can send notifications at any point from your app to the user.
The whole source code is present in the GitHub link below
If you want to connect these are my profiles
LinkedIn :- linkedin.com/in/priyanshupaliwal078 Github :- github.com/Priyanshu078