Flutter schedule local notification does not work - flutter

I am trying to create a notification at a certain time but it is not working. The code does not throw any error but no notification is displayed on the device.
I am using flutter_local_notifications
Code that generates the notification:
Future<void> showNotification(
int hour, int id, String title, String body) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
_convertTime(hour),
const NotificationDetails(
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
iOS: IOSNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
);
}
_converTime function code:
TZDateTime _convertTime(int hour) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduleDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, 47);
return scheduleDate;
}
The result of the function is correct and is as follows: 2022-07-14 12:47:00.000Z
However, if instead of using this function, I change it to
Future<void> showNotification(
int hour, int id, String title, String body) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
// _convertTime(hour), // this does not work
tz.TZDateTime.now(tz.local).add(Duration(seconds: 1)), // this work
const NotificationDetails(
android: AndroidNotificationDetails('main_channel', 'Main Channel',
channelDescription: "ashwin",
importance: Importance.max,
priority: Priority.max),
// iOS details
iOS: IOSNotificationDetails(
sound: 'default.wav',
presentAlert: true,
presentBadge: true,
presentSound: true,
),
),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
);
}
I don't understand what could be happening.
I appreciate any help in advance.

try this one, remove some properties if you don't want them...
Future zonedScheduleNotification(String note, DateTime date, occ) async {
// tz.TZDateTime.parse(location, formattedString)
int id = math.Random().nextInt(10000);
log(date.toString());
log(tz.TZDateTime.parse(tz.getLocation("Asia/Kolkata"), date.toString())
.toString());
try {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
occ,
note,
tz.TZDateTime.parse(tz.getLocation("Asia/Kolkata"), date.toString()),
NotificationDetails(
android: AndroidNotificationDetails(
'your channel id', 'your channel name',
channelDescription: 'your channel description',
largeIcon: DrawableResourceAndroidBitmap("logo"),
icon: "ic_launcher",
playSound: true,
sound: RawResourceAndroidNotificationSound('bell_sound')),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
return id;
} catch (e) {
log("Error at zonedScheduleNotification----------------------------$e");
if (e ==
"Invalid argument (scheduledDate): Must be a date in the future: Instance of 'TZDateTime'") {
Fluttertoast.showToast(msg: "Select future date");
}
return -1;
}
}

Try this again.
tz.TZDateTime _convertTime(int hour) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduleDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, 47);
return scheduleDate;
}

Related

Problem in flutter local notification grouping

I'm using flutter_local_notification to rended the incoming chat notifications from FCM trying to group messsages from one conversation. The grouping working properly but on receiving a new notification from a different conversation, it overrides and dismiss the previous group.
showNotification({
required int id,
required AndroidNotificationChannel channel,
required String title,
required String body,
required Map<String, dynamic> payload,
}) async {
final androidNotificationDetails = AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
groupKey: channel.groupId,
importance: Importance.max,
priority: Priority.max,
icon: '#mipmap/launcher_icon',
);
final iosNotificationDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
threadIdentifier: channel.groupId, // Notifications with the same threadIdentifier grouped automatically
);
final notificationDetails = NotificationDetails(
android: androidNotificationDetails,
iOS: iosNotificationDetails,
);
_flutterLocalNotificationsPlugin.show(
id,
title,
body,
notificationDetails,
payload: jsonEncode(payload),
);
if (channel.groupId == null) {
return;
}
//* Grouping Messages
List<ActiveNotification> activeNotifications = await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()!
.getActiveNotifications();
if (!activeNotifications.any((element) => element.groupKey == channel.groupId)) {
return;
}
if (activeNotifications.isNotEmpty) {
// For Android Versions >= 7.0
List<String> lines = activeNotifications.map((e) => e.body.toString()).toList();
InboxStyleInformation inboxStyleInformation = InboxStyleInformation(
lines,
contentTitle: '${lines.length - 1} messages',
summaryText: "${payload["name"].trim()} (${lines.length - 1} messages)",
);
AndroidNotificationDetails androupGroupDetails = AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
groupKey: channel.groupId,
styleInformation: inboxStyleInformation,
setAsGroupSummary: true,
);
NotificationDetails groupDetails = NotificationDetails(android: androupGroupDetails);
await _flutterLocalNotificationsPlugin.show(0, "", "", groupDetails, payload: jsonEncode(payload));
}
}
}
I've tried to group the same conversation messages in one notification but later on, the group disappeared on receiving a new notification from another user.

Combine periodically and zoneschedule in flutter local notification,

I am trying to use a local notification flutter and try to combine periodicallyshow and zonescheduled,
Can anyone give a link or example reference?
Thank you
PERIODICALLYSHOW CODE
void scheduleNotification(String title, String body) async {
AndroidNotificationDetails androidNotificationDetails =
const AndroidNotificationDetails(
'channelIs',
'channelName',
importance: Importance.max,
priority: Priority.high,
);
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails,
);
await _flutterLocalNotificationsPlugin.periodicallyShow(
0,
title,
body,
RepeatInterval.daily,//NOTE - repeat daily datetime(now) when press
notificationDetails,
);
}
ZONESCHEDULLED
static Future scheduleNotification({
int id = 0,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async =>
_notification.zonedSchedule(
id,
title,
body,
_scheduleDaily(const Time(07, 30)),//NOTE - SCHEDULE SPECIFIC TIME
await _notificationDetails(),
payload: payload,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.time,
);
static tz.TZDateTime _scheduleDaily(Time time) {
final now = tz.TZDateTime.now(tz.local);
final scheduledDate = tz.TZDateTime(
tz.local,
now.year,
now.month,
now.day,
time.hour,
time.minute,
time.second,
);
return scheduledDate.isBefore(now)
? scheduledDate.add(const Duration(days: 1))
: scheduledDate;
}
When I run the function, it will run the notification repeatedly at the specific at 10:00 that I have determined

Flutter - Where to call showScheduledNotification method to show daily random notification out of defined set

I have created NotificationService class which contain method showScheduledNotification() as defined below. I want to call this method to show daily notification at 8 AM with some set of notification subjects but not sure where to call showScheduledNotification method. Here is the Notificaiton Service Class for your reference. Please let me know if additional details are needed.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
import 'package:rxdart/subjects.dart';
class NotificationService {
static final NotificationService _notificationService =
NotificationService._internal();
final _localNotificationService = FlutterLocalNotificationsPlugin();
final BehaviorSubject<String> onNotificationClick = BehaviorSubject();
factory NotificationService() {
return _notificationService;
}
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
NotificationService._internal();
Future<void> initNotification() async {
final AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('#drawable/ic_launcher');
final InitializationSettings initializationSettings =
InitializationSettings(android: initializationSettingsAndroid);
tz.initializeTimeZones();
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: (payload) => {},
);
}
Future<void> showNotificaiton(
int id, String title, String body, int seconds) async {
tz.setLocalLocation(tz.getLocation('Asia/Kolkata'));
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
tz.TZDateTime.now(tz.local).add(Duration(seconds: seconds)),
const NotificationDetails(
android: AndroidNotificationDetails('main_channel', 'main_channel',
importance: Importance.max,
priority: Priority.max,
icon: '#drawable/ic_launcher')),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true);
}
//Show Scheduled LocalNotification
Future<void> showScheduledNotificaitonV2(
int id,
String title,
String body,
) async {
tz.setLocalLocation(tz.getLocation('Asia/Kolkata'));
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(DateTime.now().add(Duration(days: 1)), tz.local),
const NotificationDetails(
android: AndroidNotificationDetails('main_channel', 'main_channel',
importance: Importance.max,
priority: Priority.max,
icon: '#drawable/ic_launcher')),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true);
}
Future<void> showScheduledNotification(
{int id, String title, String body, int seconds}) async {
final details = await _notificationDetails();
await _localNotificationService.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(
DateTime.now().add(Duration(seconds: seconds)),
tz.local,
),
details,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
Future<NotificationDetails> _notificationDetails() async {
const AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails('channel_id', 'channel_name',
channelDescription: 'description',
importance: Importance.max,
priority: Priority.max,
playSound: true);
const IOSNotificationDetails iosNotificationDetails =
IOSNotificationDetails();
return const NotificationDetails(
android: androidNotificationDetails,
iOS: iosNotificationDetails,
);
}
}

How to call a function when the notification arrives? In flutter

I am using the plugin flutter_local_notifications 6.0.0, where the user schedules a specific time to send the database.db file
I was able to carry out the daily notification with the respective programming but I don't know where to call the function to execute it, even if the app is closed.
use the following code for local notification programming, but I need to call a function to send the .db file.
Future<void> _scheduleDailyTenAMNotification(int hour, int minute) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'Send Backup','',
_nextInstanceOfTenAM(hour, minute),
const NotificationDetails(
android: AndroidNotificationDetails(
'indeterminate progress channel',
'indeterminate progress channel',
'indeterminate progress channel description',
channelShowBadge: false,
importance: Importance.max,
priority: Priority.high,
onlyAlertOnce: true,
showProgress: true,
indeterminate: true)
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.time);
}
tz.TZDateTime _nextInstanceOfTenAM(int hour, int minute) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduledDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, minute);
if (scheduledDate.isBefore(now)) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}

Repeating notification - Flutter

How can I schedule a monthly or weekly notification in flutter? The purpose is for it to act as a reminder for the user about something...
here is my code
void showMonthlyAtDayTime() async {
//var scheduledNotificationDateTime = DateTime.now().add(Duration(seconds: 10));
var time = Time(12, 6, 0);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'alarm_notif',
'Scheduled notification', // name of the notif channel
'A scheduled notification', // description of the notif channel
icon: 'question',
largeIcon: DrawableResourceAndroidBitmap('question'),
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true);
var platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.showMonthlyAtDayTime(
0,
'Title',
'Body',
Day.Tuesday,
time,
platformChannelSpecifics);
}
The code has (red) underline beneath the showMonthlyAtDayTime in the
'wait flutterLocalNotificationsPlugin.showMonthlyAtDayTime' line
and the 'Day.Tuesday' line...
How should I modify the above code? so that the user will get notification once per each month of every year about something.
Some methods have been removed in the latest versions.
This is the code I found to repeat a notification weekly using flutter_local_notifications.
Future<void> _scheduleWeeklyTenAMNotification() async {
await notificationsPlugin.zonedSchedule(
0,
'weekly scheduled notification title',
'weekly scheduled notification body',
_nextInstanceOfTenAM(),
const NotificationDetails(
android: AndroidNotificationDetails(
'weekly notification channel id',
'weekly notification channel name',
'weekly notificationdescription'),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.dayOfWeekAndTime);
}
tz.TZDateTime _nextInstanceOfTenAM() {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduledDate =
tz.TZDateTime(tz.local, now.year, now.month, now.day, 10);
if (scheduledDate.isBefore(now)) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}
this code is copied from the example app provided by https://pub.dev/packages/flutter_local_notifications
here is the git hub link click Here