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

如何为Flutter应用的FCM通知添加用户头像?

Flutter FCM通知添加用户头像解决方案

你之前使用image字段实现的是FCM默认的大图片通知样式(Big Picture Style),该配置会将图片作为通知内容的可展开大图展示,和你需要的用户头像(通知大图标/附件)属于不同的通知组件,以下是完整实现方案:

1. 调整FCM消息Payload结构

不要使用FCM自带的notification.image配置,改用数据消息+端上自构建通知的方案,服务端下发的Payload参考如下:

{
  "token": "用户设备的FCM唯一标识",
  "data": {
    "notice_title": "XX关注了你",
    "notice_body": "你可能认识的人刚刚关注了你",
    "user_avatar": "用户头像的公网直链地址"
  },
  "android": {
    "priority": "high"
  },
  "apns": {
    "payload": {
      "aps": {
        "content-available": 1
      }
    }
  }
}

该方案会将所有通知参数放在data字段中,由端上接收后自行构建通知,可完全控制样式。

2. 端上依赖引入

使用Flutter生态最成熟的通知构建插件flutter_local_notifications实现自定义通知,在pubspec.yaml中添加依赖:

dependencies:
  flutter_local_notifications: ^16.1.0
  firebase_messaging: ^14.6.1
  http: ^1.1.0
  path_provider: ^2.1.0

3. 各端实现逻辑

Android端

Android端的用户头像对应通知的largeIcon属性,需要先下载头像图片转为Bitmap后传入配置:

// 接收FCM消息回调
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
  // 从data字段取出头像地址
  final avatarUrl = message.data['user_avatar'];
  // 下载头像到内存
  final avatarBytes = await http.get(Uri.parse(avatarUrl)).then((res) => res.bodyBytes);
  final avatarIcon = ByteArrayAndroidBitmap(avatarBytes);

  // 构建Android通知配置
  final androidConfig = AndroidNotificationDetails(
    '自定义通知渠道ID',
    '自定义通知渠道名称',
    largeIcon: avatarIcon,
    // 不设置bigPicture即可避免出现可展开大图
    styleInformation: const DefaultStyleInformation(true, true),
  );

  // 弹出通知
  await FlutterLocalNotificationsPlugin().show(
    DateTime.now().millisecond,
    message.data['notice_title'],
    message.data['notice_body'],
    NotificationDetails(android: androidConfig),
  );
});

如果需要实现圆形头像效果,可在下载完成后对Bitmap进行圆形裁剪后再传入。

iOS端

iOS端的用户头像对应通知的附件属性,需要先将头像下载到本地沙盒后作为附件传入:

// 接收到FCM消息后的同回调中,追加iOS配置
final tempDir = await getTemporaryDirectory();
final savePath = '${tempDir.path}/temp_avatar.jpg';
await File(savePath).writeAsBytes(avatarBytes);

final iosConfig = IOSNotificationDetails(
  attachments: [IOSNotificationAttachment(identifier: 'avatar', filePath: savePath)],
);

// 弹出通知时传入iOS配置
await FlutterLocalNotificationsPlugin().show(
  DateTime.now().millisecond,
  message.data['notice_title'],
  message.data['notice_body'],
  NotificationDetails(android: androidConfig, iOS: iosConfig),
);

注意事项

  • 需提前申请Android 13+的通知权限、iOS 10+的通知权限,否则通知无法正常弹出
  • 用户头像地址需要是公网可直接访问的直链,不能有登录鉴权等拦截逻辑,否则会下载失败导致头像不显示
  • 后台/杀死状态下的FCM消息回调需要额外配置FirebaseMessaging.onBackgroundMessage监听,逻辑和前台消息一致

实现效果参考:
效果示例图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:24:02