Background local notifications in Flutter

 It is a cross-platform plugin that displays local alerts in a Flutter application. It provides a variety of capabilities, such as scheduling when notifications should appear, periodically showing a notice, handling when a user taps on a notification when the app is in the foreground, background of Mobile application

Step 1:  Add the below line in dependencies to your pubspec.yaml file.
 dependencies:
fluttertoast: ^8.2.5
Step 2:  Add using terminal, Open terminal and write below code.

 Flutter pub add intl

Step 3 :  import intl package in dart code. 
 import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Step 4: Create a NotificationService.dart file in lib 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 {});
}

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());
}
}
Step 5:Below code write in button click event on dart file

 void _submit() {

   NotificationService()
.showNotification(title: 'Test Title', body: 'Test Body');

}
Step 6: Output of above example



Happy coding!

365Bloggy June 4, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive