12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import 'package:flutter/material.dart';
- class SmartImageContainer extends StatefulWidget {
- final String imageUrl;
- const SmartImageContainer({required this.imageUrl});
- @override
- State<SmartImageContainer> createState() => SmartImageContainerState();
- }
- class SmartImageContainerState extends State<SmartImageContainer> {
- Size? _imageSize;
- ImageStream? _imageStream;
- @override
- void initState() {
- super.initState();
- _loadImageDimensions();
- }
- void _loadImageDimensions() async {
- final Image image = Image.network(widget.imageUrl);
- _imageStream = image.image.resolve(ImageConfiguration.empty);
-
- _imageStream!.addListener(
- ImageStreamListener((ImageInfo info, _) {
- if (!mounted) return;
- setState(() {
- _imageSize = Size(
- info.image.width.toDouble(),
- info.image.height.toDouble(),
- );
- });
- }),
- );
- }
- @override
- void dispose() {
- //_imageStream?.removeListener(ImageStreamListener(_updateSize));
- 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) {
- // Auto-sizing logic
- if (_imageSize!.width > maxWidth) {
- // Scale down large images
- final ratio = _imageSize!.height / _imageSize!.width;
- calculatedHeight = maxWidth * ratio;
- } else {
- // Keep original size for smaller images
- calculatedWidth = _imageSize!.width;
- calculatedHeight = _imageSize!.height;
- }
- }
- return AnimatedContainer(
- duration: const Duration(milliseconds: 300),
- width: calculatedWidth,
- height: calculatedHeight,
- alignment: Alignment.center,
- child: _imageSize != null
- ? Image.network(
- widget.imageUrl,
- fit: BoxFit.contain,
- width: calculatedWidth,
- height: calculatedHeight,
- )
- : _buildLoadingPlaceholder(maxWidth),
- );
- },
- );
- }
- Widget _buildLoadingPlaceholder(double maxWidth) {
- return Container(
- width: maxWidth,
- height: maxWidth * 0.75, // Default 4:3 ratio
- color: Colors.grey[200],
- );
- }
- }
|