You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

集成flutter_app_badger与OneSignal后通知触发桌面角标不显示问题

Flutter 搭配 flutter_app_badger 与 OneSignal 角标不生效解决方案

1. 前置配置校验

  • 确认平台权限配置:
    Android端需在AndroidManifest.xml中添加对应厂商的角标访问权限,小米、华为、OPPO、vivo等国内厂商均有独立的角标权限声明要求;iOS端需在Xcode项目中开启Push Notifications能力,同时在Background Modes中勾选Remote notifications选项,且需确保用户已授予应用通知权限,角标功能与通知权限绑定。
  • 确认OneSignal后台配置:需关闭OneSignal自带的角标自动增量功能,将角标控制策略设置为None,避免云端配置覆盖本地代码设置的角标数值。
  • 确认回调触发场景:setNotificationReceivedHandler仅在应用处于前台运行状态时会被触发,应用在后台、被杀死状态下收到推送时该回调不会执行,本地角标更新逻辑自然不会运行。

2. 代码优化方案

Future<void> configOneSignal() async {
    if (!mounted) {
      return;
    }
    // 提前校验当前设备是否支持角标功能,避免无效调用
    bool isBadgeSupported = await FlutterAppBadger.isAppBadgeSupported();
    if (!isBadgeSupported) {
      print('当前设备不支持应用角标功能');
      return;
    }
    try {
      // 此处替换为你自己的OneSignal App ID
      await OneSignal.shared.init('xxxxxxxxx');
      OneSignal.shared.setInFocusDisplayType(
        OSNotificationDisplayType.notification,
      );
      await OneSignal.shared.promptUserForPushNotificationPermission(
        fallbackToSettings: true,
      );

      OneSignal.shared.setNotificationReceivedHandler((notification) async {
        print(notification.jsonRepresentation().replaceAll('\\n', '\n'));
        // 新增await等待角标更新执行完成,避免异步任务丢失
        await FlutterAppBadger.updateBadgeCount(1);
      });

      OneSignal.shared.setNotificationOpenedHandler((openedResult) {
        print('Notification Opened');
        FlutterAppBadger.removeBadge();
      });
    } catch (e) {
      print('OneSignal Exception : ${e.toString()}');
    }
}

3. 后台/进程杀死场景角标适配

  • Android端:国内厂商ROM的角标识别依赖推送Payload中的厂商特殊字段,在OneSignal发起推送时,需在附加参数中补充对应厂商的角标配置,例如小米的extra.badgetype、extra.badge字段,华为的badge字段。
  • iOS端:系统会自动读取推送Payload中aps节点下的badge字段设置角标,需在OneSignal推送配置中添加该字段,后台场景无需本地代码处理即可自动更新角标。
  • 新增应用生命周期监听:通过WidgetsBindingObserver监听应用进入前台的生命周期事件,每次应用回到前台时主动拉取用户未读消息数量,调用FlutterAppBadger.updateBadgeCount()同步角标数值,保证角标准确性。

内容的提问来源于stack exchange,提问作者x86

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:39:02