首页 > 解决方案 > Flutter - 如何对通知进行分组

问题描述

我正在使用 Flutter firebase 消息接收来自后端的通知,如何对 android https://developer.android.com/training/notify-user/group等通知进行分组?

标签: flutter

解决方案


要在 Flutter 中对通知进行分组,您可以使用flutter_local_notifications。这个包有很多功能,其中之一是([Android] 群组通知)。并这样做。

  1. 首先,您应该设置软件包配置。
  2. 在您设置包配置的同一位置创建 GroupChannel。
AndroidNotificationChannelGroup channelGroup = AndroidNotificationChannelGroup('com.my.app.alert1', 'mychannel1');
await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannelGroup(channelGroup);
  1. 创建一种方法来检查是否有多个活动通知。
void groupNotifications() async {
  List<ActiveNotification>? activeNotifications = await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.getActiveNotifications();

  if (activeNotifications != null && activeNotifications.length > 0) {
    List<String> lines = activeNotifications.map((e) => e.title.toString()).toList();
    InboxStyleInformation inboxStyleInformation = InboxStyleInformation(
      lines,
      contentTitle: "${activeNotifications.length - 1} Updates",
      summaryText: "${activeNotifications.length - 1} Updates",
    );
    AndroidNotificationDetails groupNotificationDetails = AndroidNotificationDetails(
      channel.id,
      channel.name,
      channel.description,
      styleInformation: inboxStyleInformation,
      setAsGroupSummary: true,
      groupKey: channel.groupId,
      // onlyAlertOnce: true,
    );
    NotificationDetails groupNotificationDetailsPlatformSpefics = NotificationDetails(android: groupNotificationDetails);
    await flutterLocalNotificationsPlugin.show(0, '', '', groupNotificationDetailsPlatformSpefics);
  }
}

注意:每次收到通知时都应该调用 groupNotifications()


推荐阅读