Reputation: 931
I want to make a Notification Helper which schedules notifications. Everything works perfect but scheduling notifications does not work. I print the scheduled date, it is after DateTime.now() but still receiving that error:
E/flutter ( 9512): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Invalid argument (scheduledDate): Must be a date in the future: Instance of 'TZDateTime'
This is my function:
static Future<void> setNotification(
DateTime dateTime, int id, String title, String body) async {
var now = DateTime.now();
Duration duration = dateTime.difference(now);
print(dateTime.toString());
print(dateTime.toUtc());
print(" tz : ${tz.TZDateTime.now(tz.local).add(duration)}");
print("tz local: ${tz.local}");
await _flutterLocalNotificationsPlugin.zonedSchedule(
id,
'$title',
'$body',
tz.TZDateTime.now(tz.local).add(duration),
_notificationDetails,
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
);
}
How can I convert DateTime to TZDateTime properly?
Upvotes: 0
Views: 1821
Reputation: 713
The FlutterLocalNotifications package uses TimeZone sensitive DateTime, the FlutterLocalNotifications docs suggest us to use TimeZone package so to use it in your code first you must import it and initialize it
import 'package:timezone/timezone.dart' as tz;
tz.initializeTimeZones();
then you must get the location using zone = tz.getLocation('Africa/Algiers');
note that Africa/Algiers is a timezone example
then you can simply get TZDateTime from DateTime like this
tz.TZDateTime.from(DateTime.now(), zone),
zone is the location we got earlier
this will work like charm,
Upvotes: 2