vijaycreations
Published in

vijaycreations

Local Push Notifications in Flutter (both android and iOS)

In this article we will discuss about how to implement local push notification in our flutter app.

→ Let’s start by creating a separate dart file and write the core logic of initializing local notifications for both android and iOS devices.

For AndroidInitializationSettings pass the image file name (flutter_logo) and make sure to add this image file inside android/app/src/main/res/drawable folder.

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationService {
final FlutterLocalNotificationsPlugin notificationsPlugin =
FlutterLocalNotificationsPlugin();

Future<void> initNotification() async {
AndroidInitializationSettings initializationSettingsAndroid =
const AndroidInitializationSettings('flutter_logo');

var initializationSettingsIOS = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification:
(int id, String? title, String? body, String? payload) async {});

var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
await notificationsPlugin.initialize(initializationSettings,
onDidReceiveNotificationResponse:
(NotificationResponse notificationResponse) async {});
}
}

Now try calling this initialization method right from the main method as follows.,

void main() {
WidgetsFlutterBinding.ensureInitialized();
NotificationService().initNotification();
runApp(const MyApp());
}

With this we complete initializing the notification service for both android and iOS.

→ In order to complete the iOS setup for getting notification, we need to add the following lines inside iOS/Runner/ApDelegate.swift file

import UIKit
import Flutter

//----------#1----------
import flutter_local_notifications
//----------------------

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {

//----------#2----------
FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
GeneratedPluginRegistrant.register(with: registry)}
//----------------------
GeneratedPluginRegistrant.register(with: self)

//----------#3----------
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
//----------------------

return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}

→ Now we have completed the setup process for receiving notification in our device. Let’s try building up the UI containing an elevated button which when pressed will trigger the 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: Center(
child: ElevatedButton(
child: const Text('Show notifications'),
onPressed: () {
NotificationService()
.showNotification(title: 'Sample title', body: 'It works!');
},
)),
);
}
}

The showNotification() method is as follows ., Try adding this inside the separate dart file that contains core logic of initializing local notifications for both android and iOS devices (defined in the very beginning of this article).

  notificationDetails() {
return const NotificationDetails(
android: AndroidNotificationDetails('channelId', 'channelName',
importance: Importance.max),
iOS: DarwinNotificationDetails());
}

Future showNotification(
{int id = 0, String? title, String? body, String? payLoad}) async {
return notificationsPlugin.show(
id, title, body, await notificationDetails());
}

Well that’s it. 🎉 Run the code to see it in action.🥳

Refer my video tutorial for complete guide:👉 https://www.youtube.com/watch?v=26TTYlwc6FM

Get the complete source code here:👉 https://github.com/vijayinyoutube/local_notification_app_demo

--

--

A list of Flutter Tutorials and app templates

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vijay R

Hai👋 I’m a flutter developer experienced in designing and developing stunning mobile apps. Reach out for freelance projects: vijaycreations02@gmail.com