Flutter Set specific days of the week notifications - flutter

I want to be notified on certain days of the week at a specific time using the local notices package.
Certain days of the week can be notified. But I don't know how to be notified on certain days of the week.
The Day.Monday part contains only the value, but no array.
I'd like to add more than two days of the week to this part.
Please help me with how to solve this problem.
Thank you.
Package Example Source ( https://pub.dev/packages/flutter_local_notifications/example ) :
Future<void> _showWeeklyAtDayAndTime() async {
var time = Time(20, 24, 0);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'show weekly channel id',
'show weekly channel name',
'show weekly description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
0,
'show weekly title',
'Weekly notification shown on Monday at approximately ${_toTwoDigitString(time.hour)}:${_toTwoDigitString(time.minute)}:${_toTwoDigitString(time.second)}',
Day.Monday,
time,
platformChannelSpecifics);
}

There is no way to schedule weekly notifications for some specific days in this package. The only thing you can do is to schedule same notification for each day separately.

Related

Notification not showing when app is closed - Flutter

I have built a todo list app where users can schedule notifications based on certain dates and hours, the notifications show up without problems when the app is in the foreground but when the app is in the background or the app is closed, they do not show up, and I cannot understand why, any reason why, Thank you.
This is my code
late FlutterLocalNotificationsPlugin _localNotificationsPlugin;
List<Task> _list = [];
late MoorController moorController;
#override
void initState() {
super.initState();
moorController = Get.put(MoorController());
createNotification();
//showNotification();
}
void createNotification(){
_localNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = const AndroidInitializationSettings("#mipmap/ic_launcher");
var initializationSettingsIOs = const IOSInitializationSettings();
var initSettings = InitializationSettings(android: initializationSettingsAndroid,iOS: initializationSettingsIOs);
_localNotificationsPlugin.initialize(initSettings);
}
void showNotification() async {
var android = const AndroidNotificationDetails(
Utils.CHANNEL_ID,
Utils.CHANNEL_NAME,
channelDescription: Utils.DESCRIPTION,
priority: Priority.high,
importance: Importance.max);
var iOS = const IOSNotificationDetails();
var platform = NotificationDetails(android: android,iOS: iOS);
for (var element in moorController.tasks) {
if(element.date == getCurrentDate() && element.time == getCurrentTime()){
await _localNotificationsPlugin.schedule(
0,element.date,element.time,DateTime.now(),platform, payload : 'Welcome to todo app',androidAllowWhileIdle: true);
//0, element.date,element.time,platform, payload: 'Simple Payload'
}
}
}
Receiver Manifest File
Permissions
I believe you need an instance of the TZDateTime from the timezone package in order to schedule a notification.
This is a snippet from the documentation:
Starting in version 2.0 of the plugin, scheduling notifications now requires developers to specify a date and time relative to a specific time zone. This is to solve issues with daylight savings that existed in the schedule method that is now deprecated. A new zonedSchedule method is provided that expects an instance TZDateTime class provided by the timezone package. As the flutter_local_notifications plugin already depends on the timezone package, it's not necessary for developers to add the timezone package as a direct dependency. In other words, the timezone package will be a transitive dependency after you add the flutter_local_notifications plugin as a dependency in your application.
So now in your code, import the package
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
Initialize the timezone database:
tz.initializeTimeZones();
Once the time zone database has been initialised, developers may optionally want to set a default local location/time zone
tz.setLocalLocation(tz.getLocation(timeZoneName));
Now you should be able to call it like this:
await _localNotificationsPlugin.zonedSchedule(
0,
'title',
'body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
platform,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
More info can be found in the docs here
Let us know if this helps!
You should check if your payload contains the click_action with FLUTTER_NOTIFICATION_CLICK :
{
"notification": {
"body": "this is a body",
"title": "this is a title",
},
"data": {
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"sound": "default",
"status": "done",
"screen": "screenA",
},
"to": "<FCM TOKEN>"
}'
Did you add these permissions in your AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Inside the application section:
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"><intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action></intent-filter></receiver>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />

Notifications every day for a particular date range

So, I have an app where users are reminded to take medicines every day at a particular time for a certain interval of dates. For example, the user can choose to get a notification from September 16,2020 to September 18,2020 at some time of the day
My approach : I schedule a notification using the flutter_local_notifications package with showDailyAtTime() function. However, the problem I face is that, suppose I don't open the app again, there is no way to cancel the scheduled notification and thus, the notification pops up even after the specified date range. I would like the notifications to be offline, so Firebase doesn't seem to be an option.
You can solve the problem with FlutterLocalNotificationsPlugin.
The approach would be to call the method rescheduleNotifications every time you start the app. In the method all notifications are removed and the next notifications are set. In calculateNotificationTimes for example you calculate all notifications for the next 30 days. For example, all notifications on September 16, 2020 to September 18, 2020 each day at a time of your choice.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future<void> rescheduleNotifications() async {
final localNotificationsPlugin = FlutterLocalNotificationsPlugin();
const initializationSettings = InitializationSettings(AndroidInitializationSettings('app_icon'), IOSInitializationSettings());
const androidChannelSpecifics = AndroidNotificationDetails('your channel id', 'your channel name', 'your channel description');
const iOSNotificationDetails = IOSNotificationDetails();
const notificationsDetails = NotificationDetails(androidChannelSpecifics, iOSNotificationDetails);
await localNotificationsPlugin.initialize(initializationSettings);
await localNotificationsPlugin.cancelAll();
// Calculate the next notifications.
final notificationTimes = calculateNotificationTimes();
var _currentNotificationId = 0;
for (final time in notificationTimes) {
localNotificationsPlugin.schedule(
_currentNotificationId++,
"It's time to take your medicine.",
'Take the red pill',
time,
notificationsDetails,
androidAllowWhileIdle: true,
);
}
}
On iOS there is a limit that you can only have 64 notifications enabled. The disadvantage of this method on iOS is that if the user does not open the app after 64 notifications, no notification will be displayed. Which is fine, I think, because it seems that the user does not use the app anymore.
Did not test the code.

Daily recurring notifications in flutter

I am trying to use the plugin, flutter_local_notifications to send recurring notifications to the user, every day but the resource available for the plugin consists of only code and is incomprehensible, I have done the setup for the plugin as follows:
added the dependency of flutter_local_notifications
added the permission code for iOS in the AppDelegate.swift
I did this much by referring to numerous resources like medium and a few other sites, so can someone please write a method which sends the user (android & iOS) a recurring notification everyday? Thank you!
After writing that comment I did a bit of research and this is working for me so far:
Future<void> showAlertNotification() async {
var time = Time(8, 0, 0);
var androidChannel = AndroidNotificationDetails(
'channelID', 'channelName', 'channelDescription',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
playSound: true);
var iosChannel = IOSNotificationDetails();
var platformChannel =
NotificationDetails(android: androidChannel, iOS: iosChannel);
await flutterLocalNotificationsPlugin.showDailyAtTime(2, 'notification title',
'message here', time, platformChannel,
payload: 'new payload'));
}
You should not use showDailyAtTime as of now it has quite a number of problems like syncing up with local time zones. So instead you should use the zoned schedule but you should first initialize it with your local time zone it can be done with another package called flutter_native_timezone. This is the workflow I used:
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
Future<void> showNotif() async {
tz.initializeTimeZones();
String dtz = await FlutterNativeTimezone.getLocalTimezone();
if (dtz == "Asia/Calcutta") {
dtz = "Asia/Kolkata";
}
final localTimeZone = tz.getLocation(dtz);
tz.setLocalLocation(localTimeZone);
await _flutterLocalNotificationsPlugin.zonedSchedule(..., matchDateTimeComponents: DateTimeComponents.time);
}
// The ... above is the usual parameters that I didn't write.

How to set Local Notification for multiple day in weekdays in Flutter?

I am working on a flutter app, In which using flutter_local_notifications for the local notification. Weekly notification is working fine for selecting the only day on weekdays. Now I want to pick multiple days on weekdays like (Monday, Thursday, and Saturday). I couldn't find any solution to implement. Sharing my sample code.
showNotificationWeekly() {
var time = Time(10, 0, 0);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'id',
'name',
'description',
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
0,
'show weekly title',
'Weekly notification',
Day.Monday,
time,
platformChannelSpecifics,
);
}
Please let me know, If any solution for this so that I can set one notification for multiple days
I think you will need to schedule multiple Notifications, one for each day :/
Thanks, It require unique notification ID for each notification.

Ionic 3/4 - Daily Local Notifications not working

Local notifications don't work properly (tried it with ionic 3 & 4).
The user can set a time in the app and turn the notifications on or off.
When using the following code, I always get a notification at 01:00 am although I've set it to 17:30 or something else.
I tried many variations, this is the last one:
const time = setsub.task_reminder_time.split(':');
const now = new Date();
console.log('now is', now);
const pushDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), +time[0], +time[1], 0);
const options = {
id: 1,
title: 'Time to plan your day!',
text: `Hey you! It's time to get productive by planning your day!\nTap here to open DoDay! 🤓`,
trigger: { firstAt: pushDate, every: ELocalNotificationTriggerUnit.DAY }
};
if (setsub.task_reminder) {
this.notification.requestPermission();
this.notification.schedule(options);
} else {
this.notification.clearAll();
}
time is just a string containing the notification time in HH:mm
I'm using an iOS device for testing.
So I found the solution to this one by myself. It's an error in the typings file of LocalNotifications package.
The correct usage for the options look like this:
{
id: 1,
title: 'Notification Title',
text: 'Your notification text',
foreground: true,
trigger: {
every: {
hour: 8,
minute: 15
}
}
}
Just go into your node_modules/#ionic-native/local-notifications find the index.d.ts and find the line which says every?: ELocalNotificationTriggerUnit and change it to every?: any; now it should work perfectly.