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

Flutter应用退至后台时无法通过flutter_local_notifications显示本地通知求解

解决思路
  • 首先确认生命周期回调正常触发
    在didChangeAppLifecycleState方法中添加打印日志,确认应用切后台时确实走到了state == AppLifecycleState.paused的分支,排除Observer添加失效、生命周期状态判断错误的问题。注意部分场景下应用切后台会先触发inactive状态再进入paused,如果paused分支确实没走到,可以尝试监听inactive状态作为兜底触发时机。
  • 修复异步方法执行被中断的问题
    这是最常见的故障原因:displayNotification是异步方法,而应用进入paused状态后Dart Runtime会很快被系统挂起,异步任务还没执行完成就被中断,导致通知没有真正发出去。
    修复方案:调用通知方法时使用最高优先级的调度任务,保证应用暂停前完成通知发送逻辑:
    import 'package:flutter/scheduler.dart';
    
    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
      super.didChangeAppLifecycleState(state);
      if (state == AppLifecycleState.paused) {
        SchedulerBinding.instance.scheduleTask(() async {
          await displayNotification("AppName","App has gone into the background",null);
        }, Priority.urgent);
      }
    }
    
  • 检查flutter_local_notifications的基础配置
    1. 安卓端确认已经动态申请了POST_NOTIFICATIONS权限(安卓13及以上必填),且已经正确创建了高优先级的通知渠道,优先级设置为NotificationImportance.max,避免后台通知被系统拦截
    2. iOS端确认已经申请了通知权限,用户已经同意接收通知,不需要额外开启后台模式即可发送本地通知
  • 可选兜底方案
    如果上述方案都不生效,可以在原生层监听应用切后台的生命周期回调,直接用原生API发送通知,规避Dart层被挂起的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 00:06:04