import 'dart:io'; import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import '../../main.dart'; class SmartImageContainer extends StatefulWidget { final String imageUrl; const SmartImageContainer({super.key, required this.imageUrl}); @override State createState() => _SmartImageContainerState(); } class _SmartImageContainerState extends State { Size? _imageSize; ImageStream? _imageStream; ImageStreamListener? _imageListener; @override void initState() { super.initState(); _loadCachedImageDimensions(); } void _loadCachedImageDimensions() async { try { final response = await imageCacheManager.getFileFromCache(widget.imageUrl); if (response is FileInfo && mounted) { final image = Image.file(File(response.file.path)); _processImage(image); } else if (response is DownloadProgress) { // Handle download progress if needed } } catch (e) { if (mounted) { setState(() => _imageSize = null); } } } void _processImage(Image image) { _imageStream = image.image.resolve(ImageConfiguration.empty); _imageListener = ImageStreamListener((ImageInfo info, _) { if (!mounted) return; setState(() { _imageSize = Size( info.image.width.toDouble(), info.image.height.toDouble(), ); }); }); _imageStream!.addListener(_imageListener!); } @override void dispose() { _imageStream?.removeListener(_imageListener!); super.dispose(); } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { final maxWidth = constraints.maxWidth; double calculatedWidth = maxWidth; double calculatedHeight = maxWidth; if (_imageSize != null) { if (_imageSize!.width > maxWidth) { final ratio = _imageSize!.height / _imageSize!.width; calculatedHeight = maxWidth * ratio; } else { calculatedWidth = _imageSize!.width; calculatedHeight = _imageSize!.height; } } return AnimatedContainer( duration: const Duration(milliseconds: 300), width: calculatedWidth, height: calculatedHeight, child: CachedNetworkImage( cacheManager: imageCacheManager, imageUrl: widget.imageUrl, fit: BoxFit.contain, placeholder: (context, url) => _buildLoadingPlaceholder(maxWidth), errorWidget: (context, url, error) => _buildErrorPlaceholder(maxWidth), ), ); }, ); } Widget _buildLoadingPlaceholder(double maxWidth) { return Container( width: maxWidth, height: maxWidth * 0.75, color: Colors.grey[200], child: const Center(child: CircularProgressIndicator()), ); } Widget _buildErrorPlaceholder(double maxWidth) { return Container( width: maxWidth, height: maxWidth * 0.75, color: Colors.red[100], child: const Icon(Icons.error_outline, color: Colors.red), ); } }