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
Related
I have updated the pods in my app. And now I have some errors. I have been able to fix few of them, but I still have two where I do not find what I should do. Please, can you help? Thank you.
I am using flutter_local_notifications: ^10.0.0
The other errors have been fixed. I guess that I should not have updated the files, but my objective was to fix a buffer overflow problem.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();
static Future _notificationDetails() async {
const sound = 'notification_sound.wav';
return NotificationDetails(
android: AndroidNotificationDetails(
'channel id 8',
'channel name',
channelDescription: 'channel description',
importance: Importance.max,
//playSound: false,
sound: RawResourceAndroidNotificationSound(sound.split('.').first),
enableVibration: false,
// styleInformation: styleInformation,
),
iOS: const DarwinNotificationDetails(
presentSound: false,
sound: sound,
),
);
}
static Future init({bool initScheduled = false}) async {
const android = AndroidInitializationSettings('#mipmap/ic_launcher');
const iOS = DarwinInitializationSettings();
const settings = InitializationSettings(android: android, iOS: iOS);
/// Handle payload when app is closed
final details = await _notifications.getNotificationAppLaunchDetails();
if (details != null && details.didNotificationLaunchApp) {
onNotifications.add(details.payload); ///ERROR (The named parameter 'onSelectNotification' isn't defined.)
}
await _notifications.initialize(
settings,
onSelectNotification: (payload) async {
onNotifications.add(payload); ///ERROR (The getter 'payload' isn't defined for the type 'NotificationAppLaunchDetails'.)
},
);
if (initScheduled) {
tz.initializeTimeZones();
final locationName = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(locationName));
}
}
/// Direct Notification
static Future showNotification({
int id = 0,
String? title,
String? body,
String? payload,
}) async =>
_notifications.show(
id,
title,
body,
await _notificationDetails(),
payload: payload,
);
/// Notification for specific DateTime
static void showScheduledNotification({
int? id ,
String? title,
String? body,
String? payload,
required DateTime scheduledDate,
}) async =>
_notifications.zonedSchedule(
id!,
title,
body,
tz.TZDateTime.from(scheduledDate, tz.local),
await _notificationDetails(),
payload: payload,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
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;
}
static List<tz.TZDateTime> _scheduleWeekly(Time time,
{required List<int> days}) {
return days.map((day) {
tz.TZDateTime scheduledDate = _scheduleDaily(time);
while (day != scheduledDate.weekday) {
scheduledDate = scheduledDate.add(const Duration(days: 1));
}
return scheduledDate;
}).toList();
}
static void cancel(int id) => _notifications.cancel(id);
static void cancelAll() => _notifications.cancelAll();
static int convertStringToHash (String id) {
int notificationId = id.hashCode;
return notificationId;
}
}
i can managed to implement time,but year and month note working or should i use some library to run my application in background?
Please Help!
packages i used
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:local_notification_johannas/model.dart';
import 'package:timezone/timezone.dart' as tz;
import 'package:timezone/data/latest.dart' as tz;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
Notification class
class NotifyClass {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
NotificInitializer() async {
_confitLocTime();
final AndroidInitializationSettings initSettingAndroid =
AndroidInitializationSettings('send_icon');
final IOSInitializationSettings iniSettingiOS = IOSInitializationSettings();
final InitializationSettings initializationSettings =
InitializationSettings(android: initSettingAndroid, iOS: iniSettingiOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: myOnSelectFuncion);
}
Future myOnSelectFuncion(
String? payload,
) async {
if (payload != null)
print('noti payload :$payload');
else
print('Done');
}
Show Notification Function
Future showNotific({required String title, required String body}) async {
var androidPlatSpecific = new AndroidNotificationDetails(
'channelId', 'channelName',
playSound: true, importance: Importance.max, priority: Priority.high);
var iosPlatSpecific = new IOSNotificationDetails();
var platformSpecific = new NotificationDetails(
android: androidPlatSpecific, iOS: iosPlatSpecific);
await flutterLocalNotificationsPlugin.show(0, title, body, platformSpecific,
payload: 'Default_Sound');
}
This is ScheduledNotification funcion i used.
it only works on minutes or seconds with the same day
even i pass different date.
Future<void> scheduledNotification(
{
required int hour,
required int minutes,
required int day,
required int month,
required int year,
required MyModel obj}) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
obj.id!,
obj.title,
obj.startTime,
_convertTime(year, month, day, hour, minutes),
NotificationDetails(
android: AndroidNotificationDetails('your id', 'your channel'),
),
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.time,
androidAllowWhileIdle: true,
);
}
tz.TZDateTime _convertTime(
int year, int month, int day, int hour, int minutes) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduleDate =
tz.TZDateTime(tz.local, year, month, day, hour, minutes);
if (scheduleDate.isBefore(now)) {
scheduleDate = scheduleDate.add(Duration(days: 1));
print(scheduleDate);
}
return scheduleDate;
}
Future<void> _confitLocTime() async {
tz.initializeTimeZones();
final String timeZone = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZone));
}
}
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,
);
}
}
I've been trying to get Flutter local notifications to work since a week but can't get it to work.
Basically the issue is whenever i create a daily notification, it works only for the first time and then it doesn't show notifications every next day.
Suppose if i set daily scheduled notification at 12:20 PM, it will show notification at 12:20 PM for first time, then the next day it won't show. And when i see the list of pending notifications i can see the notification still present.
here's all my notification code
class NotificationService {
// Singleton pattern
static final NotificationService _notificationService =
NotificationService._internal();
factory NotificationService() {
return _notificationService;
}
NotificationService._internal();
static const channelId = "1";
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
static const AndroidNotificationDetails _androidNotificationDetails =
AndroidNotificationDetails(
channelId,
"thecodexhub",
channelDescription:
"This channel is responsible for all the local notifications",
playSound: true,
priority: Priority.high,
importance: Importance.high,
);
static const IOSNotificationDetails _iOSNotificationDetails =
IOSNotificationDetails();
final NotificationDetails notificationDetails = const NotificationDetails(
android: _androidNotificationDetails,
iOS: _iOSNotificationDetails,
);
Future<void> init() async {
const AndroidInitializationSettings androidInitializationSettings =
AndroidInitializationSettings('#mipmap/ic_launcher');
const IOSInitializationSettings iOSInitializationSettings =
IOSInitializationSettings(
defaultPresentAlert: false,
defaultPresentBadge: false,
defaultPresentSound: false,
);
const InitializationSettings initializationSettings =
InitializationSettings(
android: androidInitializationSettings,
iOS: iOSInitializationSettings,
);
// *** Initialize timezone here ***
tz.initializeTimeZones();
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onSelectNotification: onSelectNotification,
);
}
Future<void> requestIOSPermissions() async {
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
Future<void> showNotification(
int id, String title, String body, String payload) async {
await flutterLocalNotificationsPlugin.show(
id,
title,
body,
notificationDetails,
payload: payload,
);
}
Future<void> scheduleNotification(int id, String title, String body,
DateTime eventDate, TimeOfDay eventTime, String payload,
[DateTimeComponents? dateTimeComponents]) async {
final scheduledTime = eventDate.add(Duration(
hours: eventTime.hour,
minutes: eventTime.minute,
));
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
tz.TZDateTime.from(scheduledTime, tz.local),
notificationDetails,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
payload: payload,
matchDateTimeComponents: dateTimeComponents,
);
}
Future<void> cancelNotification(int id) async {
await flutterLocalNotificationsPlugin.cancel(id);
}
Future<void> cancelAllNotifications() async {
await flutterLocalNotificationsPlugin.cancelAll();
}
Future getNotifications() async {
final List<PendingNotificationRequest> pendingNotificationRequests =
await FlutterLocalNotificationsPlugin().pendingNotificationRequests();
return pendingNotificationRequests;
}
}
Future<void> onSelectNotification(String? payload) async {
// await navigatorKey.currentState
// ?.push(MaterialPageRoute(builder: (_) => DetailsPage(payload: payload)));
}
and here's how i'm calling it.
await notificationService.scheduleNotification(
1,
_textEditingController.text,
"Reminder for your scheduled event at ${eventTime!.format(context)}",
eventDate!,
eventTime!,
jsonEncode({
"title": _textEditingController.text,
"eventDate": DateFormat("EEEE, d MMM y").format(eventDate!),
"eventTime": eventTime!.format(context),
}),
getDateTimeComponents(),
);
}
here is getDateTimeComponents if it matters
DateTimeComponents? getDateTimeComponents() {
if (segmentedControlGroupValue == 1) {
return DateTimeComponents.time;
} else if (segmentedControlGroupValue == 2) {
return DateTimeComponents.dayOfWeekAndTime;
}
}
it's been week since i'm trying to fix this issue.
Thank you for reading.
Here it says
Use zonedSchedule instead by passing a date in the future with the
same time and pass DateTimeComponents.matchTime as the value of the
matchDateTimeComponents parameter.
You seem to use DateTimeComponents.time correctly but I guess your date is not in the future. Can you try adding like a thousand years to your date and see? Maybe because after the first firing, the date is now in the past and it will not fire on the next day because of it.
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;
}