Flutter:如何安排一个通知来替换上次安排的通知

问题描述 投票:0回答:1

我正在开发一个应用程序,其中所有通知都提前安排。每个通知都设置为一天中的不同时间,并且应替换之前的通知。

即上午 9 点、下午 1 点、下午 5 点等

我正在使用包https://pub.dev/packages/flutter_local_notifications和下面的代码:

for (var interval in [1, 3, 4, 7, 7.5, 8]) {
      var time = (appStart).add(Duration(hours: interval));

       scheludeNotification(notifications,
                    title: "Title",
                    body: "Body"
                    time: time,
                    id: 0, // OR unique id
                    payload: '');
        
}

Future scheludeNotification(
  FlutterLocalNotificationsPlugin notifications, {
  @required String title,
  @required String body,
  @required DateTime time,
  @required String payload,
  int id = 0,
}) =>
    _scheduleNotification(notifications,
        title: title,
        body: body,
        id: id,
        time: time,
        type: _ongoing,
        payload: payload);

Future _scheduleNotification(
  FlutterLocalNotificationsPlugin notifications, {
  @required String title,
  @required String body,
  @required DateTime time,
  @required NotificationDetails type,
  @required String payload,
  int id = 0,
}) =>
    notifications.schedule(id, title, body, time, type, payload: payload);

虽然我遇到的问题是我希望每个新通知替换以前的通知,如果用户还没有看到该通知。因此,当用户返回手机时,他们不会收到 20 条新通知。如果我对每个通知使用相同的 ID,那么它会替换以前的通知,但由于通知都是同时安排的(即当用户首次打开应用程序时),而不是创建多个安排的通知,在显示后替换各自的前任通知。它只是删除所有预定的通知,并仅删除最后的安排。如果我为每个通知使用唯一的 ID,那么它会创建一个新的通知,而不删除以前的通知。我也无法使用

notifications.cancel(id);
功能,因为当通知用户时应用程序可能无法打开。

任何想法,谢谢。

android flutter notifications android-notifications
1个回答
0
投票

您需要跟踪通知 ID 并在安排更换之前取消它们。您可以使用cancelAllNotifications(),如果您知道特定的通知ID,请使用cancelNotifiation()并提供ID。

© www.soinside.com 2019 - 2024. All rights reserved.