Flutter 中如何实现类似 Android 系统的通知分组功能
Flutter Firebase Messaging Android 通知分组实现步骤
1. 前置准备
- 确保已经集成
firebase_messaging插件,若需要本地构建通知,还需集成flutter_local_notifications插件 - Android 8.0及以上版本必须先创建通知渠道,分组配置需绑定对应通知渠道使用
2. 不同场景实现方案
场景1:后端直接下发FCM通知消息
在后端构造推送payload时,添加Android专属配置参数:
- 所有属于同一分组的通知,
android/group字段填写相同的自定义分组标识(例如"com.yourapp.chat_group") - 单独指定一条通知作为分组摘要,将其
android/group_summary字段设为true
payload示例:
{ "notification": { "title": "新消息", "body": "你有3条未读消息" }, "android": { "group": "com.yourapp.chat_group", "group_summary": true }, "tokens": ["用户设备token"] }
其余同组子通知仅需填写相同group字段,group_summary设为false即可。
场景2:前端收到数据消息后本地弹出通知
使用flutter_local_notifications构造通知时添加分组参数:
- 同组所有子通知设置相同
groupKey - 单独构造一条摘要通知,设置相同
groupKey的同时,将isGroupSummary设为true
代码示例:
// 弹出分组内的子通知 await flutterLocalNotificationsPlugin.show( 1, // 子通知id,不同子通知id需不同 "张三", "晚上一起吃饭吗?", NotificationDetails( android: AndroidNotificationDetails( "channel_id", // 已创建的通知渠道id "聊天消息", groupKey: "com.yourapp.chat_group", // 相同分组key ), ), ); // 弹出分组摘要通知,每组仅需一条 await flutterLocalNotificationsPlugin.show( 0, // 摘要通知固定id "聊天消息", "你有2条未读消息", NotificationDetails( android: AndroidNotificationDetails( "channel_id", "聊天消息", groupKey: "com.yourapp.chat_group", isGroupSummary: true, // 标记为分组摘要 ), ), );
3. 优化配置
- 同组通知数量小于2时,可取消弹出摘要通知,避免单条通知也展示分组样式
- 可通过
tag参数标记同组内不同来源的通知,实现同来源消息覆盖更新,避免通知栏内容冗余 - Android 7.0及以上系统支持该特性,更低版本系统会自动忽略分组参数,单独展示所有通知
内容的提问来源于stack exchange,提问作者achoo254
相关产品推荐
相关产品推荐

