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

Flutter:能否直接用AndroidNotification通过flutter_local_notifications展示通知?

问题解答

不行,没办法直接传入RemoteNotification或AndroidNotification对象给flutter_local_notifications来展示通知。

flutter_local_notifications有自己独立的类型体系,必须使用它提供的AndroidNotificationDetails(针对Android平台)和NotificationDetails(统一包装平台配置)对象来配置通知样式、行为等参数,才能调用展示方法。

你需要从Firebase的RemoteMessage里提取通知的相关字段(比如标题、内容、图标路径等),手动映射到AndroidNotificationDetails的对应属性中,再包装成NotificationDetails传入。举个简单的示例:

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('Got a message whilst in the foreground!');
  print('Message data: ${message.data}');

  if (message.notification != null) {
    final RemoteNotification? notification = message.notification;
    final AndroidNotification? android = message.notification?.android;

    // 仅当Android端有通知数据时展示
    if (notification != null && android != null) {
      // 创建flutter_local_notifications所需的Android配置
      AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
        'your_channel_id', // 通知渠道ID,需提前创建
        'your_channel_name',
        channelDescription: 'your_channel_description',
        icon: android.smallIcon, // 使用Firebase通知里的小图标
        priority: Priority.high,
        importance: Importance.max,
      );

      // 包装成统一的NotificationDetails
      NotificationDetails notificationDetails = NotificationDetails(android: androidDetails);

      // 展示通知
      flutterLocalNotificationsPlugin.show(
        notification.hashCode, // 通知ID
        notification.title,
        notification.body,
        notificationDetails,
        payload: message.data['payload'], // 可选的自定义数据
      );
    }
  }
});

简单来说,两个库的通知对象是不同类型,没有直接的兼容转换,必须手动提取字段构建目标对象才能完成展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:10:35