import 'package:flutter/material.dart'; import 'package:image_preview/preview.dart'; import 'package:image_preview/preview_data.dart'; import 'package:shared/utils/date_time_utils.dart'; import 'package:shared/utils/util.dart'; import '../directory/directory_util.dart'; class ImagePreviewEngine { /// 单图的预览 static void singleImagePreview( BuildContext context, String url, { String? heroTag, void Function(String? url)? onLongPressAction, Widget? Function(int index)? tipWidget, }) { String path; // 根据URL类型处理路径 if (isNetworkUrl(url)) { // 从URL中提取文件名 String fileName = extractFileName(url); // 生成保存路径 path = DirectoryUtil.getTempPath(category: 'Pictures', fileName: fileName) ?? ""; } else { // 如果是本地路径,直接使用URL作为路径 path = url; } // 调用预览页面 openPreviewPage( Navigator.of(context), data: PreviewData( type: Type.image, heroTag: heroTag ?? '', image: ImageData( url: url, path: path, ), ), tipWidget: tipWidget, onLongPressHandler: (context, data) { onLongPressAction?.call(data.image?.url); }, ); } /// 多图的预览 static void multipleImagePreview( BuildContext context, List urls, { List? heroes, void Function(String? url)? onLongPressAction, void Function(int index)? onPageChanged, Widget? Function(int index)? tipWidget, }) { // 过滤掉 null 值的 URL List filteredUrls = urls.where((url) => url != null).cast().toList(); List previewDataList = filteredUrls.asMap().entries.map((entry) { int index = entry.key; String url = entry.value; String path; if (isNetworkUrl(url)) { String fileName = extractFileName(url); path = DirectoryUtil.getTempPath(category: 'Pictures', fileName: fileName) ?? ""; } else { path = url; } return PreviewData( type: Type.image, heroTag: heroes != null && heroes.length > index ? heroes[index] : index.toString(), image: ImageData( url: url, path: path, ), ); }).toList(); // 调用预览页面 openPreviewPages( Navigator.of(context), data: previewDataList, tipWidget: tipWidget, onPageChanged: onPageChanged, onLongPressHandler: (context, data) { onLongPressAction?.call(data.image?.url); }, ); } /// 工具函数:从URL提取文件名 static String extractFileName(String url) { // 检查是否包含 '/' if (!url.contains('/')) { return DateTimeUtils.getNowDateMs().toString(); } // 获取最后一个 '/' 后的部分 String fileName = url.split('/').last; // 检查是否包含 '.' if (Utils.isEmpty(fileName)) { return DateTimeUtils.getNowDateMs().toString(); } return fileName; } /// 工具函数:判断是否为网络URL static bool isNetworkUrl(String url) { return url.startsWith('http://') || url.startsWith('https://'); } }