gpt4 book ai didi

android - 如何在 flutter 中将 DateTime 转换为 TZDateTime?

转载 作者:行者123 更新时间:2023-12-03 18:20:40 26 4
gpt4 key购买 nike

我正在尝试使用 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);
}
}
使用该类(class),您就可以开始了。

关于android - 如何在 flutter 中将 DateTime 转换为 TZDateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64305469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com