scheduleNotificationForTask method

Future<void> scheduleNotificationForTask(
  1. CropTask task
)

Schedule notification for a specific task, 15 minutes before the task time

Implementation

Future<void> scheduleNotificationForTask(CropTask task) async {
  try {
    final DateTime notifyTime = task.date.subtract(const Duration(minutes: 15));

    if (notifyTime.isBefore(DateTime.now())) {
      debugPrint('Notification time already passed for task: ${task.id}');
      return;
    }

    final tz.TZDateTime scheduledDate = tz.TZDateTime.from(notifyTime, tz.local);

    await AwesomeNotifications().createNotification(
      content: NotificationContent(
        id: task.id.hashCode,
        channelKey: 'daily_tasks',
        title: 'Upcoming Task: ${task.cropName}',
        body: '${task.taskDescription} at ${task.date.hour.toString().padLeft(2, '0')}:${task.date.minute.toString().padLeft(2, '0')}',
        notificationLayout: NotificationLayout.Default,
        payload: {'taskId': task.id},
      ),
      schedule: NotificationCalendar.fromDate(date: scheduledDate, allowWhileIdle: true),
    );

    debugPrint('Scheduled notification for task: ${task.id} at $notifyTime');
  } catch (e) {
    debugPrint('Error scheduling notification for task: $e');
  }
}