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

Flutter AwesomeNotifications:无法为NotificationContent传入网络图标

问题解决:AwesomeNotifications 远程图片作为通知图标报错

错误原因

AwesomeNotifications 的 NotificationContent.icon 参数不支持直接传入网络URL,它仅接受本地资源(如项目内置的drawable资源名、本地文件路径),直接传远程链接会触发"Small icon must be a valid media native resource type"错误。

解决方案

需要先将远程图片下载到本地存储,再使用本地文件路径作为通知图标。

步骤1:添加依赖

确保pubspec.yaml中包含以下依赖:

dependencies:
  path_provider: ^2.1.2
  http: ^1.2.1

步骤2:实现图片下载函数

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

Future<String> downloadImage(String url) async {
  final response = await http.get(Uri.parse(url));
  final directory = await getTemporaryDirectory();
  final file = File('${directory.path}/notification_icon.jpg');
  await file.writeAsBytes(response.bodyBytes);
  return file.path;
}

步骤3:修改通知创建代码

先下载图片,再传入本地路径作为icon:

// 先下载远程图片
final localIconPath = await downloadImage("https://prod-ripcut-delivery.disney-plus.net/v1/variant/disney/174C605829DEB3C79C2F6993EFA97B2ECBF21D6A152E6BB0CA00DDA987E94BAC/scale?width=1200&aspectRatio=1.78&format=jpeg");

// 创建通知
AwesomeNotifications().createNotification(
  content: NotificationContent(
    id: ID.generateRandomInt(3),
    groupKey: group.key,
    channelKey: channel.key,
    icon: localIconPath, // 使用本地文件路径
    title: title,
    body: body,
  ),
  actionButtons: [
    NotificationActionButton(key: "markAsRead", label: "Mark As Read"),
    NotificationActionButton(key: "reply", label: "Reply")
  ],
);

额外注意事项

  • Android端:Android 10及以上无需额外存储权限,Android 9及以下需申请WRITE_EXTERNAL_STORAGE权限
  • iOS端:临时文件会在应用重启或系统清理时被删除,若需持久化可改用getApplicationDocumentsDirectory()
  • 可添加图片缓存逻辑,避免重复下载相同URL的图片

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:27:16