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

Flutter中使用awesome_notifications后台处理通知按钮点击

在Flutter中使用awesome_notifications实现后台通知动作修改SharedPreferences

可行性说明

完全可行,无需依赖Firebase,awesome_notifications本身支持通过Dart后台处理器实现该需求。你之前遇到的错误是因为未正确注册后台可访问的Dart处理函数。

核心解决方案

1. 定义顶级/静态后台处理函数

后台Dart隔离无法访问main函数内的匿名函数,必须将动作处理逻辑抽为顶级函数或静态函数:

import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:awesome_notifications/awesome_notifications.dart';

// 顶级函数:后台可直接调用
Future<void> onNotificationActionReceived(ReceivedAction action) async {
  // 后台环境需手动初始化Flutter绑定
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化SharedPreferences
  final prefs = await SharedPreferences.getInstance();
  
  // 根据动作按钮的key执行对应逻辑
  if (action.buttonKey == 'key') {
    // 修改SharedPreferences值
    await prefs.setString('last_action_triggered', 'silent_background_action');
    await prefs.setInt('action_count', (prefs.getInt('action_count') ?? 0) + 1);
    
    // 后台日志可通过Android logcat或iOS控制台查看
    print('SharedPreferences updated in background: ${action.buttonKey}');
  }
}

2. 正确初始化AwesomeNotifications

在main函数中初始化时,指定上述后台处理函数,同时配置通知渠道:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  await AwesomeNotifications().initialize(
    // 替换为你的应用图标路径
    'asset://assets/iconPhoto.png',
    [
      NotificationChannel(
        channelKey: 'important_channel',
        channelName: '重要通知',
        channelDescription: '用于展示带动作按钮的通知',
        importance: NotificationImportance.High,
        defaultColor: const Color(0xFF0000FF),
      )
    ],
    // 关键:绑定后台动作处理函数
    onActionReceivedMethod: onNotificationActionReceived,
  );
  
  // 处理应用从通知动作启动的场景
  ReceivedAction? initialAction = await AwesomeNotifications().getInitialNotificationAction(
    removeFromActionEvents: false
  );
  if (initialAction != null) {
    await onNotificationActionReceived(initialAction);
  }
  
  runApp(const MyApp());
}

3. 平台权限配置

Android(AndroidManifest.xml)

确保添加必要权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>

iOS(Info.plist)

开启后台通知模式并添加权限说明:

<key>UIBackgroundModes</key>
<array>
  <string>remote-notification</string>
</array>
<key>NSNotificationSettingsUsageDescription</key>
<string>需要通知权限来接收和处理通知动作</string>

4. 通知创建代码验证

你现有的通知创建代码已经正确使用了ActionType.SilentBackgroundAction,无需修改:

static Future<void> createSimpleNotification() async {
  await AwesomeNotifications().createNotification(
    content: NotificationContent(
        id: 1,
        channelKey: 'important_channel',
        title: 'Title',
        body: 'Test',
        largeIcon: 'asset://assets/iconPhoto.png'),
    actionButtons: [
      NotificationActionButton(
          key:'key',
          label: 'label',
          actionType: ActionType.SilentBackgroundAction)]
  );
}

常见问题说明

  • 之前的错误提示A background message could not be handled in Dart because there is no dart background handler registered:因为你使用了main内的匿名函数作为处理器,后台隔离无法识别,必须改用顶级/静态函数。
  • 后台日志查看:Android可通过adb logcat过滤Flutter日志,iOS可通过Xcode控制台查看。
  • SharedPreferences初始化:后台环境没有自动初始化Flutter绑定,必须手动调用WidgetsFlutterBinding.ensureInitialized()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:55:12