跪拜 Guibai
← Back to the summary

Three-Tier Image Size Fallback Keeps Flutter HTML Rendering from Breaking on Dirty Data

Best Practices for Flutter: Rendering Rich Text with flutter_html

1. Origin of the Requirement

Developing a news app hit a pain point: The article body returned by the backend is a piece of HTML, and image sizes vary wildly—some have fixed width/height, some only provide an aspect ratio via data-href, and some have a fake aspect ratio.

Directly using flutter_html as a one-size-fits-all solution often results in images bursting out of the layout and distorted aspect ratios. This article organizes the complete pitfalls and best practices.

A real piece of news content:

<p><img src="https://cdn.xxx.com/news/xxx.png"
        data-href="1500|1688|image/png||share" style=""/></p>
<p>In the 25/26 season Bundesliga round 12, Bayern Munich won 3-1 against St. Pauli...</p>
<blockquote>Key events</blockquote>
<p><img src="https://cdn.xxx.com/news/icon.png"
        data-href="16|16|png|icon" style="width: 20px;height: 20px;"/>
   44' Díaz passed the ball to Guerrero...</p>

Image size information is scattered in three places, with different levels of reliability:

  1. style's width/height: Most reliable, manually written by operations, use directly;
  2. data-href's width|height|type|...: Second most reliable, can be used to calculate an aspect ratio placeholder; but images marked with share often have actual sizes that differ from the label, so discard them;
  3. Nothing at all: Wait for the network image to actually load to determine the height.

flutter_html renders <img> as inline elements by default, with no size strategy. The core requirement is: customize a "from reliable to fallback" degradation parsing for <img>, ensuring the layout doesn't break under any dirty data.

2. Solution Exploration: Two Extension Points

flutter_html provides two key extension points:

Overall Typography: style with body

Html(
  data: detail?.context ?? "",
  style: {
    "body": Style(
      color: themeProvider.titleColor,       // Follow theme
      lineHeight: LineHeight.number(1.3),    // Line height
      fontSize: FontSize(16.5, Unit.px),     // Font size
      display: Display.block,
      textAlign: TextAlign.left,
    ),
    "p img": Style(                          // Block-level images default to full width and centered
      display: Display.block,
      margin: Margins(left: Margin.auto(), right: Margin.auto()),
    ),
  },
  extensions: [...],
)

Note that Style is its own set of types in flutter_html. Font size uses FontSize(16.5, Unit.px), line height uses LineHeight.number(1.3), which are not the same as Flutter's native TextStyle.

Taking Over Tags: TagExtension

TagExtension provides access to element.attributes, which is the only way to read src / style / data-href. Take over <img> completely:

TagExtension(
  tagsToExtend: {"img"},
  builder: (exContext) {
    final element = exContext.element;
    if (element == null) return const SizedBox.shrink();
    final url = element.attributes['src'] ?? '';
    final styleSize = resolveImageStyleSize(element.attributes['style']);
    final aspectRatio = resolveImageAspectRatio(element.attributes['data-href']);
    return buildHtmlImage(
      url: url,
      width: styleSize.$1,
      height: styleSize.$2,
      aspectRatio: aspectRatio,
    );
  },
),

<blockquote> (such as the "Key events" subtitle) has an ugly default quote style, so it's also taken over and rendered as a section title bar with a theme-colored vertical stripe.

3. Image Size: Three-Tier Fallback Strategy

This is the core. Try each level in order; use what you get, fall back if you don't:

Level 1: style fixed width/height (most reliable)

(double?, double?) resolveImageStyleSize(String? style) {
  if (style == null || style.isEmpty) return (null, null);
  final widthMatch = RegExp(r'width\s*:\s*([\d.]+)px', caseSensitive: false).firstMatch(style);
  final heightMatch = RegExp(r'height\s*:\s*([\d.]+)px', caseSensitive: false).firstMatch(style);
  final width = widthMatch == null ? null : double.tryParse(widthMatch.group(1)!);
  final height = heightMatch == null ? null : double.tryParse(heightMatch.group(1)!);
  return (width, height);
}

Level 2: data-href aspect ratio (second most reliable)

double? resolveImageAspectRatio(String? dataHref) {
  if (dataHref == null || dataHref.isEmpty) return null;
  final parts = dataHref.split('|');
  if (parts.length < 2) return null;
  // Example: 1500|1688|image/png||share — share images often have sizes that don't match the label
  if (parts.any((e) => e.trim().toLowerCase() == 'share')) return null;
  final width = double.tryParse(parts[0]) ?? 0;
  final height = double.tryParse(parts[1]) ?? 0;
  if (width <= 0 || height <= 0) return null;
  return width / height;
}

Key pitfall: Cover images marked with share have "fake sizes" in the metadata; calculating the aspect ratio directly will cause stretching and deformation, so this level must be discarded.

Level 3: Nothing available → real loading fallback

Widget buildHtmlImage({required String url, double? width, double? height, double? aspectRatio}) {
  // 1. Fixed width/height: use directly
  if (width != null && height != null && width > 0 && height > 0) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(2),
      child: buildNetworkImageFitWidth(url: url, width: width, height: height, fit: BoxFit.contain),
    );
  }
  // 2. Have aspect ratio: placeholder based on screen width, LayoutBuilder calculates height
  if (aspectRatio != null) {
    return SizedBox(
      width: double.infinity,
      child: LayoutBuilder(builder: (context, constraints) {
        final maxWidth = constraints.maxWidth;
        if (!maxWidth.isFinite || maxWidth <= 0) return buildNetworkImageFitWidth(url: url);
        return ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: buildNetworkImageFitWidth(
            url: url, width: maxWidth, height: maxWidth / aspectRatio,
            fit: BoxFit.fitWidth, alignment: Alignment.topCenter,
          ),
        );
      }),
    );
  }
  // 3. Nothing: real size
  return ClipRRect(borderRadius: BorderRadius.circular(4), child: buildNetworkImageFitWidth(url: url));
}

No matter which level, everything converges to a unified network image component: using CachedNetworkImage for caching, width ?? double.infinity to fill the screen width, and unified placeholder/error states. Small icon images pass SizedBox.shrink() as a placeholder to avoid flashing a large default image while loading.

4. Summary

  1. The reason for choosing flutter_html is that it can process individual tags separately.
  2. flutter_html is just a "convert HTML to Widget" library; what really determines rendering quality is your strategy for handling unstructured data. The core is one sentence:

Make <img> size parsing a "reliable → second reliable → fallback" degradation chain, and converge to a cached network image component.

This way, no matter what dirty data the backend returns, the layout won't break, images won't distort, and the loading experience stays consistent. Combined with TagExtension to customize tags like blockquote, a rich-text news page that "feels like native" is complete.


Source code reference:

github