如何在Flutter中通过字符串图片路径实现带小图的Android通知
实现方案
你要实现的带小图通知不需要用到BigPictureStyleInformation,只需要配置Android通知的大图标参数即可,流程分为两步:
第一步:下载网络图片到本地缓存
你需要先把服务端的图片下载到Android本地的缓存目录,拿到本地文件路径,示例实现如下:
import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:http/http.dart' as http; Future<String> downloadNetworkImage(String imageUrl) async { // 发起网络请求获取图片二进制数据 final response = await http.get(Uri.parse(imageUrl)); // 获取应用临时缓存目录 final tempDirectory = await getTemporaryDirectory(); // 构造本地缓存文件对象 final cacheFile = File('${tempDirectory.path}/notification_large_icon.png'); // 写入图片数据到本地文件 await cacheFile.writeAsBytes(response.bodyBytes); // 返回本地文件路径 return cacheFile.path; }
第二步:构造带小图的通知配置
拿到本地图片路径后,将FilePathAndroidBitmap实例传给AndroidNotificationDetails的largeIcon参数,即可实现通知右侧带小图的效果:
// 先调用下载方法拿到图片本地路径 final localImagePath = await downloadNetworkImage("替换为你的服务端图片URL"); // 构造Android通知配置 final androidDetails = AndroidNotificationDetails( "your_channel_id", "通知渠道名称", channelDescription: "通知渠道描述", importance: Importance.high, priority: Priority.high, // 配置通知小图 largeIcon: FilePathAndroidBitmap(localImagePath), ); // 后续正常调用通知发送方法即可 await flutterLocalNotificationsPlugin.show( 0, "通知标题", "通知内容", NotificationDetails(android: androidDetails), );
注意:使用前需要提前申请网络权限、本地存储权限,同时确保依赖了
http、path_provider、flutter_local_notifications相关包。
内容的提问来源于stack exchange,提问作者Agung
相关产品推荐
相关产品推荐

