smart_image_container.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import 'package:flutter/material.dart';
  2. class SmartImageContainer extends StatefulWidget {
  3. final String imageUrl;
  4. const SmartImageContainer({required this.imageUrl});
  5. @override
  6. State<SmartImageContainer> createState() => SmartImageContainerState();
  7. }
  8. class SmartImageContainerState extends State<SmartImageContainer> {
  9. Size? _imageSize;
  10. ImageStream? _imageStream;
  11. @override
  12. void initState() {
  13. super.initState();
  14. _loadImageDimensions();
  15. }
  16. void _loadImageDimensions() async {
  17. final Image image = Image.network(widget.imageUrl);
  18. _imageStream = image.image.resolve(ImageConfiguration.empty);
  19. _imageStream!.addListener(
  20. ImageStreamListener((ImageInfo info, _) {
  21. if (!mounted) return;
  22. setState(() {
  23. _imageSize = Size(
  24. info.image.width.toDouble(),
  25. info.image.height.toDouble(),
  26. );
  27. });
  28. }),
  29. );
  30. }
  31. @override
  32. void dispose() {
  33. //_imageStream?.removeListener(ImageStreamListener(_updateSize));
  34. super.dispose();
  35. }
  36. @override
  37. Widget build(BuildContext context) {
  38. return LayoutBuilder(
  39. builder: (context, constraints) {
  40. final maxWidth = constraints.maxWidth;
  41. double calculatedWidth = maxWidth;
  42. double calculatedHeight = maxWidth;
  43. if (_imageSize != null) {
  44. // Auto-sizing logic
  45. if (_imageSize!.width > maxWidth) {
  46. // Scale down large images
  47. final ratio = _imageSize!.height / _imageSize!.width;
  48. calculatedHeight = maxWidth * ratio;
  49. } else {
  50. // Keep original size for smaller images
  51. calculatedWidth = _imageSize!.width;
  52. calculatedHeight = _imageSize!.height;
  53. }
  54. }
  55. return AnimatedContainer(
  56. duration: const Duration(milliseconds: 300),
  57. width: calculatedWidth,
  58. height: calculatedHeight,
  59. alignment: Alignment.center,
  60. child: _imageSize != null
  61. ? Image.network(
  62. widget.imageUrl,
  63. fit: BoxFit.contain,
  64. width: calculatedWidth,
  65. height: calculatedHeight,
  66. )
  67. : _buildLoadingPlaceholder(maxWidth),
  68. );
  69. },
  70. );
  71. }
  72. Widget _buildLoadingPlaceholder(double maxWidth) {
  73. return Container(
  74. width: maxWidth,
  75. height: maxWidth * 0.75, // Default 4:3 ratio
  76. color: Colors.grey[200],
  77. );
  78. }
  79. }