Flutter Local Scheduled Notifications
Flutter Local Notifications is a powerful plugin that enables you to create and display native-looking local notifications on both Android and iOS platforms. This means you can send alerts, reminders, or messages to users even when your app is closed or minimized. Flutter_local_notifications plugin to display local notifications on Android, iOS, macOS, and Linux devices. Some of the features of the plugin include the ability to display basic notifications, schedule notifications, and show notifications periodically. The plugin also allows users to customize the appearance of notifications, such as the title, body, and icon. Additionally, users can specify the sound that should be played when a notification is received. Overall, the flutter_local_notifications plugin is a useful tool for developers who want to add local notification functionality to their Flutter apps.
1). First of all, add the flutter_local_notification Package to Your pubspec.yaml File.
cupertino_icons: ^1.0.6
flutter_local_notifications:
dev_dependencies:
flutter_test:
sdk: flutter
2). To add the required permissions to your AndroidManifest.xml file:
-
Locate the file:
- Navigate to the
android/app/src/main
directory. - Open the
AndroidManifest.xml
file.
- Navigate to the
-
Add the permissions:
- Paste the following lines within the
<manifest>
tag, but outside of the<application>
tag:
- Paste the following lines within the
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
<application
Explanation of permissions:
android.permission.WAKE_LOCK
: This permission allows your app to prevent the device from sleeping, which is necessary for reliable notification delivery.android.permission.VIBRATE
: This permission enables your app to vibrate the device when a notification is received.
By adding these permissions, you're ensuring that your app has the necessary capabilities to effectively display local notifications.
3. Add receivers before application tag:
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
</application>
3). Create a file notification_helper.dart and inside it create a class named NotificationHelper, where we Initialize the notification, and write all notification functions.
Here's a basic structure for your notification_helper.dart
file:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest_all.dart' as tz;
class NotificationHelper {
static final _notification = FlutterLocalNotificationsPlugin();
static init() async {
await _notification.initialize(
const InitializationSettings(
android: AndroidInitializationSettings("@mipmap/ic_launcher"),
));
tz.initializeTimeZones();
}
static scheduleNotification(
String title,
String body,
int userDayInput,
) async {
var androidDetails = const AndroidNotificationDetails(
"important_notification",
"My Channel",
importance: Importance.max,
priority: Priority.high,
);
var notificationDetails = NotificationDetails(android: androidDetails);
await _notification.zonedSchedule(
0,
title,
body,
tz.TZDateTime.now(tz.local).add(Duration(
seconds: userDayInput,
)
),
notificationDetails,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
);
}
cancelAllNotifications() {
_notification.cancelAll();
}
}
4). In your main.dart file, add WidgetsFlutterBinding.ensureInitialized() before initializing the notification system. Add an elevated button to the UI that, when pressed, triggers the scheduleNotification function, allowing users to input the notification's title, body, and desired time duration in my case, I set it for 5 seconds. Create another elevated button that, when pressed, triggers a cancelNotification function to cancel a previously scheduled notification.
Here's a basic structure for your main.dart
file:
import 'package:flutter/material.dart';
import 'package:myapp/notification_helper.dart';
main(){
WidgetsFlutterBinding.ensureInitialized();
NotificationHelper.init();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Local Schedule Notification'),
);
}
}
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(
backgroundColor: Colors.amber,
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () {
NotificationHelper.scheduleNotification(
"Notification test",
"my app Notification",
5,
);
},
child: const Text("Set Notification")),
ElevatedButton(
onPressed: () {
NotificationHelper().cancelAllNotifications();
},
child: const Text("Remove Notification")),
],
),
),
);
}
}
Comments
Post a Comment