Skip to content

Commit e2c9b74

Browse files
authored
Merge pull request #630 from tneotia/bugfix/image-aspect-ratio
Provide AspectRatio for Image.network
2 parents d523e56 + 52205fb commit e2c9b74

File tree

1 file changed

+33
-12
lines changed

1 file changed

+33
-12
lines changed

lib/image_render.dart

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import 'dart:convert';
44
import 'package:flutter/material.dart';
55
import 'package:flutter_html/html_parser.dart';
66
import 'package:flutter_svg/flutter_svg.dart';
7+
import 'package:flutter_svg/parser.dart';
78
import 'package:html/dom.dart' as dom;
89

910
typedef ImageSourceMatcher = bool Function(
@@ -140,18 +141,27 @@ ImageRender networkImageRender({
140141
future: completer.future,
141142
builder: (BuildContext buildContext, AsyncSnapshot<Size> snapshot) {
142143
if (snapshot.hasData) {
143-
return Image.network(
144-
src,
145-
headers: headers,
146-
width: width ?? _width(attributes) ?? snapshot.data!.width,
147-
height: height ?? _height(attributes),
148-
frameBuilder: (ctx, child, frame, _) {
149-
if (frame == null) {
150-
return altWidget?.call(_alt(attributes)) ??
151-
Text(_alt(attributes) ?? "", style: context.style.generateTextStyle());
152-
}
153-
return child;
154-
},
144+
return Container(
145+
constraints: BoxConstraints(
146+
maxWidth: width ?? _width(attributes) ?? snapshot.data!.width,
147+
maxHeight: (width ?? _width(attributes) ?? snapshot.data!.width) / _aspectRatio(attributes, snapshot)
148+
),
149+
child: AspectRatio(
150+
aspectRatio: _aspectRatio(attributes, snapshot),
151+
child: Image.network(
152+
src,
153+
headers: headers,
154+
width: width ?? _width(attributes) ?? snapshot.data!.width,
155+
height: height ?? _height(attributes),
156+
frameBuilder: (ctx, child, frame, _) {
157+
if (frame == null) {
158+
return altWidget?.call(_alt(attributes)) ??
159+
Text(_alt(attributes) ?? "", style: context.style.generateTextStyle());
160+
}
161+
return child;
162+
},
163+
),
164+
),
155165
);
156166
} else if (snapshot.hasError) {
157167
return altWidget?.call(_alt(attributes)) ??
@@ -211,3 +221,14 @@ double? _width(Map<String, String> attributes) {
211221
final widthString = attributes["width"];
212222
return widthString == null ? widthString as double? : double.tryParse(widthString);
213223
}
224+
225+
double _aspectRatio(Map<String, String> attributes, AsyncSnapshot<Size> calculated) {
226+
final heightString = attributes["height"];
227+
final widthString = attributes["width"];
228+
if (heightString != null && widthString != null) {
229+
final height = double.tryParse(heightString);
230+
final width = double.tryParse(widthString);
231+
return height == null || width == null ? calculated.data!.aspectRatio : width / height;
232+
}
233+
return calculated.data!.aspectRatio;
234+
}

0 commit comments

Comments
 (0)