android - 如何在颤动中将 DateTime 转换为 TZDateTime?
问题描述
我正在尝试使用 flutter_local_notifications 包通过我的应用程序推送本地通知,并且在 FlutterNotificationsPlugin 上,“.schedule”已被弃用,我尝试使用“.zonedSchedule”,但它需要 TZDateTime 值。
var androidDetails = AndroidNotificationDetails(t.id, "Task Notifier",
"Notifies if you have a task scheduled at a particular time");
var generalNotificationDetails =
NotificationDetails(android: androidDetails);
var now = DateTime.now();
var scheduledTime = DateTime(
now.year, now.month, _dayTasks.date.day, t.time.hour, t.time.minute)
.subtract(Duration(minutes: 5));
//use zonedSchedule once you figure out how to convert datetime to TZdatetime
// await notifications.zonedSchedule(
// 0, "Task", t.description, scheduledTime, generalNotificationDetails,
// androidAllowWhileIdle: true,
// uiLocalNotificationDateInterpretation:
// UILocalNotificationDateInterpretation.wallClockTime);
await notifications.schedule(0, "Ideal Day Task", t.description,
scheduledTime, generalNotificationDetails);
解决方案
实际上, zonedSchedule() 需要 TZDateTime 值。我采用的方法是利用另一个包将原始 DateTime 值转换为 TZDateTime 值。下面是我使用的一个实现的摘录。看到第五行了吗?它涉及函数 TZDateTime.from()。它采用您最初可能使用的 DateTime 并将其转换为 TZDateTime。但是,它需要您当前的位置。这就是 TimeZone 类的用武之地。
import 'package:timezone/timezone.dart' as tz;
:
:
:
final timeZone = TimeZone();
// The device's timezone.
String timeZoneName = await timeZone.getTimeZoneName();
// Find the 'current location'
final location = await timeZone.getLocation(timeZoneName);
final scheduledDate = tz.TZDateTime.from(dateTime, location);
try {
await _flutterLocalNotificationsPlugin.zonedSchedule(
id,
title,
body,
scheduledDate,
platformChannelSpecifics,
androidAllowWhileIdle: androidAllowWhileIdle,
payload: payload,
uiLocalNotificationDateInterpretation:
uiLocalNotificationDateInterpretation,
);
} catch (ex) {
id = -1;
}
return id;
我很快写了课,TimeZone。此类与另一个插件(flutter_native_timezone)一起使用,该插件查找设备的“当前位置”并提供该语言环境的标准名称:
import 'package:timezone/data/latest.dart';
import 'package:timezone/timezone.dart' as t;
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
class TimeZone {
factory TimeZone() => _this ?? TimeZone._();
TimeZone._() {
initializeTimeZones();
}
static TimeZone _this;
Future<String> getTimeZoneName() async => FlutterNativeTimezone.getLocalTimezone();
Future<t.Location> getLocation([String timeZoneName]) async {
if(timeZoneName == null || timeZoneName.isEmpty){
timeZoneName = await getTimeZoneName();
}
return t.getLocation(timeZoneName);
}
}
使用该课程,您就可以开始了。
推荐阅读
- python - 查找两个数据帧之间的差异
- html - 聚焦时如何更改兄弟元素的字体粗细?
- linux - 从两种不同方法构建的 libsqlite3.so.0.8.6 的大小
- scala - 如何在 spark Scala 的 foldLeft 中使用条件?
- sql - 如何在 Netezza 中用双引号将列括起来
- pyspark - .isin() 带有来自数据框的列
- docker - Docker - 无法通过脚本删除容器内的文件
- oracle - AWS RDS 分配的存储大小
- bash - 如何计算日志文件中两行之间的时间差?
- google-sheets - 用于计算电子表格中用 , 或 / 分隔的名称的公式