如何在flutter中调度多个时间特定的本地通知

wa7juj8i  于 2023-02-25  发布在  Flutter
关注(0)|答案(3)|浏览(194)

我正在开发与Flutter饮水提醒应用程序。我想调度一个时间指定的本地通知列表,用户可以添加到此列表中,并从此列表中删除。like this
任何帮助都将不胜感激,谢谢。

hivapdat

hivapdat1#

经过几个小时的研究,我已经解决了这个问题。完整的代码如下。

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

class NotificationHelper {
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  /// Initialize notification
  initializeNotification() async {
    _configureLocalTimeZone();
    const IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings();

    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings("ic_launcher");

    const InitializationSettings initializationSettings = InitializationSettings(
      iOS: initializationSettingsIOS,
      android: initializationSettingsAndroid,
    );
    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  /// Set right date and time for notifications
  tz.TZDateTime _convertTime(int hour, int minutes) {
    final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
    tz.TZDateTime scheduleDate = tz.TZDateTime(
      tz.local,
      now.year,
      now.month,
      now.day,
      hour,
      minutes,
    );
    if (scheduleDate.isBefore(now)) {
      scheduleDate = scheduleDate.add(const Duration(days: 1));
    }
    return scheduleDate;
  }

  Future<void> _configureLocalTimeZone() async {
    tz.initializeTimeZones();
    final String timeZone = await FlutterNativeTimezone.getLocalTimezone();
    tz.setLocalLocation(tz.getLocation(timeZone));
  }

  /// Scheduled Notification
  scheduledNotification({
    required int hour,
    required int minutes,
    required int id,
    required String sound,
  }) async {
    await flutterLocalNotificationsPlugin.zonedSchedule(
      id,
      'It\'s time to drink water!',
      'After drinking, touch the cup to confirm',
      _convertTime(hour, minutes),
      NotificationDetails(
        android: AndroidNotificationDetails(
          'your channel id $sound',
          'your channel name',
          channelDescription: 'your channel description',
          importance: Importance.max,
          priority: Priority.high,
          sound: RawResourceAndroidNotificationSound(sound),
        ),
        iOS: IOSNotificationDetails(sound: '$sound.mp3'),
      ),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time,
      payload: 'It could be anything you pass',
    );
  }

  /// Request IOS permissions
  void requestIOSPermissions() {
    flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
        ?.requestPermissions(
          alert: true,
          badge: true,
          sound: true,
        );
  }

  cancelAll() async => await flutterLocalNotificationsPlugin.cancelAll();
  cancel(id) async => await flutterLocalNotificationsPlugin.cancel(id);
}

像这样添加你的自定义时间

for (int i = 0; i < _provider.getScheduleRecords.length; i++) {
  _notificationHelper.scheduledNotification(
    hour: int.parse(_provider.getScheduleRecords[i].time.split(":")[0]),
    minutes: int.parse(_provider.getScheduleRecords[i].time.split(":")[1]),
    id: _provider.getScheduleRecords[i].id,
    sound: 'sound0',
  );
}
anauzrmj

anauzrmj2#

你可以使用flutter_local_notifications插件,它可以发送预定,即时和重复通知

await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
    android: AndroidNotificationDetails(
        'your channel id', 'your channel name',
        channelDescription: 'your channel description')),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
    UILocalNotificationDateInterpretation.absoluteTime);

此示例将计划在5秒钟后显示通知。

oewdyzsn

oewdyzsn3#

尝试Awesome Notifications
它有许多功能,包括秒精度预定通知。

示例代码段:

Future<void> scheduleNewNotification() async {
    
        await AwesomeNotifications().createNotification(
            content: NotificationContent(
                id: -1, // -1 is replaced by a random number
                channelKey: 'alerts',
                title: "Huston! The eagle has landed!",
                body:
                    "A small step for a man, but a giant leap to Flutter's community!",
                bigPicture: 'https://storage.googleapis.com/cms-storage-bucket/d406c736e7c4c57f5f61.png',
                largeIcon: 'https://storage.googleapis.com/cms-storage-bucket/0dbfcc7a59cd1cf16282.png',
                //'asset://assets/images/balloons-in-sky.jpg',
                notificationLayout: NotificationLayout.BigPicture,
                payload: {
                  'notificationId': '1234567890'
                }),
            actionButtons: [
              NotificationActionButton(key: 'REDIRECT', label: 'Redirect'),
              NotificationActionButton(
                  key: 'DISMISS',
                  label: 'Dismiss',
                  actionType: ActionType.DismissAction,
                  isDangerousOption: true)
            ],
            schedule: NotificationCalendar.fromDate(
                date: DateTime.now().add(const Duration(seconds: 10))));
      }

相关问题