feat:增加待办提醒功能
This commit is contained in:
3
lib/utils/common.dart
Normal file
3
lib/utils/common.dart
Normal file
@@ -0,0 +1,3 @@
|
||||
bool isSameDate(DateTime a, DateTime b) {
|
||||
return a.year == b.year && a.month == b.month && a.day == b.day;
|
||||
}
|
||||
82
lib/utils/notice.dart
Normal file
82
lib/utils/notice.dart
Normal file
@@ -0,0 +1,82 @@
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:hive/hive.dart';
|
||||
import 'package:timezone/timezone.dart' as tz;
|
||||
|
||||
import '../models/task.dart';
|
||||
import 'common.dart';
|
||||
|
||||
// 初始化通知
|
||||
Future<void> initNotify() async {
|
||||
final notify = FlutterLocalNotificationsPlugin();
|
||||
await notify.initialize(
|
||||
const InitializationSettings(
|
||||
windows: WindowsInitializationSettings(
|
||||
appName: 'TaskHub',
|
||||
appUserModelId: 'com.cxx.task',
|
||||
guid: 'f47ac10b-58cc-4372-a567-0e02b2c3d479',
|
||||
iconPath: 'assets/icons/app_icon.ico',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> showNotify(String title, String body) async {
|
||||
final notify = FlutterLocalNotificationsPlugin();
|
||||
final id = DateTime.now().millisecondsSinceEpoch.remainder(10000);
|
||||
|
||||
await notify.show(
|
||||
id,
|
||||
title,
|
||||
body,
|
||||
const NotificationDetails(windows: WindowsNotificationDetails()),
|
||||
);
|
||||
}
|
||||
|
||||
// 发送通知
|
||||
Future<void> scheduleNotification(
|
||||
int id,
|
||||
String title,
|
||||
String body,
|
||||
DateTime scheduleTime,
|
||||
) async {
|
||||
final notify = FlutterLocalNotificationsPlugin();
|
||||
|
||||
final local = tz.getLocation('Asia/Shanghai');
|
||||
final tzTime = tz.TZDateTime.from(scheduleTime, local);
|
||||
|
||||
await notify.zonedSchedule(
|
||||
id,
|
||||
title,
|
||||
body,
|
||||
tzTime,
|
||||
const NotificationDetails(windows: WindowsNotificationDetails()),
|
||||
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
|
||||
);
|
||||
}
|
||||
|
||||
// 取消通知
|
||||
Future<void> cancelAllSchedule() async {
|
||||
final notify = FlutterLocalNotificationsPlugin();
|
||||
|
||||
await notify.cancelAll();
|
||||
}
|
||||
|
||||
void checkScheduleTime() {
|
||||
final taskBox = Hive.box<Task>('taskBox');
|
||||
final now = DateTime.now();
|
||||
|
||||
cancelAllSchedule();
|
||||
for (var task in taskBox.values) {
|
||||
if (task.scheduleTime != null &&
|
||||
!task.isCompleted &&
|
||||
isSameDate(task.scheduleTime!, DateTime.now()) &&
|
||||
task.scheduleTime!.isAfter(now)) {
|
||||
scheduleNotification(
|
||||
task.id,
|
||||
task.title,
|
||||
task.desc ?? '',
|
||||
task.scheduleTime!,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user