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

如何为Flutter Awesome Notifications的通知按钮添加点击功能

给Awesome Notifications按钮添加点击事件的实现方法

要给Approve和Edit按钮添加不同的点击逻辑,你可以通过监听Awesome Notifications的动作流来实现,具体步骤如下:

1. 注册事件监听器

在项目初始化的地方(比如main函数)或者页面的initState里,设置监听来捕获通知按钮的点击动作:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化Awesome Notifications,记得配置好你的通知渠道
  await AwesomeNotifications().initialize(
    '@mipmap/ic_launcher', // 替换成你的应用图标路径
    [
      NotificationChannel(
        channelKey: 'basic_channel',
        channelName: '基础通知',
        channelDescription: '用于常规通知的渠道',
        defaultColor: Colors.blue,
        ledColor: Colors.white,
      )
    ]
  );

  // 监听通知按钮点击事件
  AwesomeNotifications().actionStream.listen((ReceivedNotificationAction action) {
    // 根据按钮的key区分处理逻辑
    switch(action.buttonKeyPressed) {
      case 'Approve':
        // 执行Approve的逻辑
        _handleApprove(action);
        break;
      case 'Edit':
        // 执行Edit的逻辑
        _handleEdit(action);
        break;
    }
  });

  runApp(const MyApp());
}

2. 编写按钮对应的处理函数

分别实现两个按钮的具体功能:

// 处理Approve按钮点击
void _handleApprove(ReceivedNotificationAction action) {
  // 这里写你需要的Approve逻辑,比如记录操作、更新本地数据等
  print('点击了Approve按钮,通知ID:${action.id}');
  // 如果通知带了额外数据,可以通过action.payload获取
  // 比如 action.payload?['amount']
}

// 处理Edit按钮点击
void _handleEdit(ReceivedNotificationAction action) {
  // 这里写Edit的逻辑,比如跳转到编辑页面、弹出编辑弹窗
  print('点击了Edit按钮,通知ID:${action.id}');
  
  // 要是需要跳转页面,得确保在UI线程执行
  WidgetsBinding.instance.addPostFrameCallback((_) {
    // 这里需要上下文,你可以根据实际情况传递或者用全局上下文
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const EditTransactionPage()),
    );
  });
}

3. 额外提示

  • 如果需要给通知传递额外数据,创建通知时可以在NotificationContent里加payload参数:
    content: NotificationContent(
      // ... 原有参数
      payload: {
        'amount': jsonObject['amount'],
        'vendor': jsonObject['vendor'],
        'category': jsonObject['category']
      }
    )
    
    之后在处理函数里通过action.payload就能拿到这些数据。
  • 要是你是在页面的initState里注册的监听,记得在页面销毁时取消订阅,避免内存泄漏:
    StreamSubscription? _notificationSub;
    
    @override
    void initState() {
      super.initState();
      _notificationSub = AwesomeNotifications().actionStream.listen((action) {
        // 处理逻辑
      });
    }
    
    @override
    void dispose() {
      _notificationSub?.cancel();
      super.dispose();
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:27:33