elysia/lib/plugin/CacheBackgroundImage.dart
2025-11-04 09:53:47 +08:00

47 lines
1.5 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
import 'package:cached_network_image/cached_network_image.dart';
class CacheBackgroundImage extends StatefulWidget {
final String url;
const CacheBackgroundImage({super.key, required this.url});
@override
State<CacheBackgroundImage> createState() => _CacheBackgroundImageState();
}
class _CacheBackgroundImageState extends State<CacheBackgroundImage> {
// 从URL中提取文件名
String _getFileNameFromUrl(String url) {
try {
Uri uri = Uri.parse(url);
List<String> pathSegments = uri.pathSegments;
if (pathSegments.isNotEmpty) {
return pathSegments.last;
}
} catch (e) {
print('Error parsing URL: $e');
}
// 如果无法解析URL使用哈希值作为文件名
return '${url.hashCode}.jpg';
}
@override
Widget build(BuildContext context) {
return CachedNetworkImage(
imageUrl: widget.url,
fit: BoxFit.cover,
cacheKey: _getFileNameFromUrl(widget.url), // 使用文件名作为缓存key
placeholder: (context, url) => Shimmer.fromColors(
baseColor: Colors.grey.shade300,
highlightColor: Colors.grey.shade100,
child: Container(color: Colors.white),
),
errorWidget: (context, url, error) => Container(
color: Colors.grey.shade200,
child: const Icon(Icons.error_outline, color: Colors.grey),
),
);
}
}