Flutter local notification explained for android

Today I’ll tell you that how you can set up a Local Notification Plugin on Flutter App. Using Plugin in flutter is not difficult but in the case of Flutter Local Notification. We need to set up some configuration before start using it.


Step 1 : Add flutter_local_notifications dependency in your pubspec.yaml file


dependencies:
flutter:
sdk: flutter
flutter_local_notifications: ^11.0.0


Step 2 : Add VIBRATE and RECEIVE_BOOT_COMPLETED permission to your AndroidManifest.xml [ Optional ]


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.notificationsdemo">

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

<application
android:label="notificationsdemo"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>


import 'package:flutter/material.dart';
import 'package:notificationsdemo/homescreen.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: 'Flutter Demo',
theme: ThemeData(

primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}


import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationServices {
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
final AndroidInitializationSettings _androidInitializationSettings =AndroidInitializationSettings('logo');

void initialiseNotifications() async
{
InitializationSettings initializationSettings =InitializationSettings(android: _androidInitializationSettings);

await _flutterLocalNotificationsPlugin.initialize(initializationSettings);

}
void sendNotification(String title,body)async{
AndroidNotificationDetails androidNotificationDetails =AndroidNotificationDetails(
"channelId", "channelName",
importance: Importance.max,
priority: Priority.high,
playSound: true,
//sound: RawResourceAndroidNotificationSound('1.mp3'),



);
NotificationDetails notificationDetails =NotificationDetails(android: androidNotificationDetails);

await _flutterLocalNotificationsPlugin.show(1, title, body, notificationDetails);

}
void scheduleNotification(String title,body)async{
AndroidNotificationDetails androidNotificationDetails =AndroidNotificationDetails(
"channelId", "channelName",
importance: Importance.max,
priority: Priority.high,
playSound: true,
//sound: RawResourceAndroidNotificationSound('1.mp3'),



);
NotificationDetails notificationDetails =NotificationDetails(android: androidNotificationDetails);

await _flutterLocalNotificationsPlugin.periodicallyShow(
0, title, body,
RepeatInterval.everyMinute,
notificationDetails);

}
void stopNotification()async{
_flutterLocalNotificationsPlugin.cancel(0);

}
}

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:notificationsdemo/NotificationService.dart';

class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);

@override
State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
NotificationServices notificationServices =NotificationServices();
@override
void initState() {
// TODO: implement initState
super.initState();
notificationServices.initialiseNotifications();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,

children: [
SizedBox(height: 200,),
ElevatedButton(onPressed: (){
notificationServices.sendNotification("title", "this is body");
}, child: Text("Send Notification")),
SizedBox(height: 20,),
ElevatedButton(onPressed: (){
notificationServices.scheduleNotification("Title", "ScheduleNotification");

}, child: Text("Schedule Notification")),
SizedBox(height: 20,),
ElevatedButton(onPressed: (){
notificationServices.stopNotification();

}, child: Text("Stop Notification")),
],
),
),
);
}
}





Comments

Popular posts from this blog

Unlocking the Power of OOP: A Beginner's Guide to Objects, Encapsulation, Inheritance, Abstraction, and Polymorphism

HTTP GET Response in Flutter

Building a Flutter Firebase Firestore CRUD App