Three-Tier Image Size Fallback Keeps Flutter HTML Rendering from Breaking on Dirty Data
Flutter apps that pull HTML from CMSes or news backends will eventually encounter inconsistent image metadata. This fallback pattern is a concrete way to keep layouts stable without rewriting the backend, and it's generalizable to any HTML renderer that lacks built-in image sizing.
Rendering HTML article bodies in Flutter usually means flutter_html, but the library treats every <img> as an inline element with no size strategy. Real backend HTML carries image dimensions in three places of varying trustworthiness: inline style width/height, a data-href attribute with an aspect ratio, or nothing at all. One project building a news app found that blindly using flutter_html let images burst the layout and distorted aspect ratios, especially when cover images carried a 'share' flag whose metadata was fake.
The fix is a three-tier fallback. First, check inline style for explicit pixel width and height and use those directly. Second, parse data-href's pipe-separated values, but only if the string doesn't contain 'share'—share-marked images often report dimensions that don't match reality. Third, when neither exists, let the image load at its natural size. All three paths converge on a single cached network image widget that fills the screen width and shares placeholder/error handling.
The pattern uses flutter_html's TagExtension to take over <img> rendering entirely, plus a style map for the body and blockquote tags. The result is a rich-text page that keeps layout intact regardless of how messy the backend data gets.
Backend HTML metadata is a trust boundary: CMS operators can put fake dimensions in data-href, so client-side code needs a kill switch like the 'share' flag check rather than trusting everything.
The fallback chain pattern generalizes beyond Flutter's flutter_html; any HTML renderer that doesn't handle image sizing would benefit from a similar tiered resolution.
Routing every size outcome through one network image component makes placeholder and error behavior consistent, which is worth more than per-image customization.