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

Flutter中如何实现无声音的FCM通知展示

问题原因

你写的配置不生效有两个核心原因:

  1. Android通知渠道的持久化机制限制:Android 8.0(API 26)及以上版本的通知渠道一旦创建完成,所有配置(声音、优先级、震动等)就由系统接管持久存储,后续代码中动态修改同ID渠道的playSound、sound等参数不会生效,除非先删除旧渠道再重新创建。
  2. 逻辑写法错误:你代码里的三目运算逻辑写反了,当getNotiSettings() == "false"(也就是用户关闭通知声音)时,你反而把playSound设为了true,逻辑完全颠倒。且你无论开关状态都传入了sound参数,部分安卓ROM下即使playSound为false,只要绑定了音频资源还是会触发提示音播放。
推荐实现方案

优先使用双渠道分流方案,兼容性最好、无系统提示、切换无延迟:

  • 初始化阶段提前创建两个配置固定、ID独立的通知渠道,两个渠道的配置初始化后永远不做动态修改
    • 有声渠道:固定开启声音、绑定自定义提示音、优先级设为Importance.max,保证通知正常弹出带提示音
    • 静默渠道:固定关闭声音、不绑定任何音频资源、优先级设为Importance.high,保证通知能正常弹出展示但不播放提示音
  • 每次发送通知前先读取用户的声音开关配置,开关开启时调用有声渠道发通知,开关关闭时调用静默渠道发通知

参考代码

1. 初始化双渠道(在应用启动初始化通知插件时调用,只执行一次即可)

Future<void> initNotiChannels() async {
  final androidPlugin = FlutterLocalNotificationsPlugin()
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
  // 初始化有声渠道
  final soundChannel = AndroidNotificationChannel(
    'app_noti_sound', // 固定渠道ID,不要动态修改
    '应用通知',
    importance: Importance.max,
    playSound: true,
    sound: RawResourceAndroidNotificationSound('your_custom_sound_name'.split('.').first),
  );
  // 初始化静默渠道
  final silentChannel = AndroidNotificationChannel(
    'app_noti_silent', // 独立的渠道ID,和有声渠道区分
    '应用静默通知',
    importance: Importance.high, // 高优先级保证通知正常弹出,不会被系统收纳为低优先级通知
    playSound: false,
    // 不要传入sound参数
  );
  // 注册两个渠道到系统
  await androidPlugin?.createNotificationChannel(soundChannel);
  await androidPlugin?.createNotificationChannel(silentChannel);
}

2. 发送通知时根据配置选择渠道

// 读取用户设置,注意修正原来的逻辑判断
bool enableNotiSound = settingsHive.getNotiSettings() != "false";
await FlutterLocalNotificationsPlugin().show(
  notiId,
  title,
  content,
  NotificationDetails(
    android: AndroidNotificationDetails(
      enableNotiSound ? 'app_noti_sound' : 'app_noti_silent',
      enableNotiSound ? '应用通知' : '应用静默通知',
      // 不需要在这里重复配置playSound和sound,以渠道固定配置为准,避免ROM兼容问题
    ),
  ),
);
备选方案(不推荐)

如果一定要使用同一个渠道ID实现,需要在用户每次修改通知声音开关时,先调用deleteNotificationChannel(旧渠道ID)方法删除系统中已存在的旧渠道,再根据最新开关配置重新创建同ID的渠道。但这个方案有两个明显缺陷:

  • 删除旧渠道时部分安卓系统会弹出"应用已修改通知设置"的系统提示,体验很差
  • 部分厂商ROM对渠道删除重建有缓存延迟,会出现配置不及时生效的问题

内容的提问来源于stack exchange,提问作者Muhammad Umair Saqib

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:54:27