Zero layout shift for network images in Flutter (dimensions in the URL)
flutterimageslayout-shiftplaceholdersmarkdownperformance
Images in user-written markdown arrive with no size, so a feed or post jumps as each one loads.
TLDR fixed this without any server or schema change by putting the pixel dimensions into the
image URL's fragment at upload time: https://api.../uploads/abc.png#w=1080&h=1350. The
renderer reads the fragment, reserves the exact box, and the image fades into it.
Write side (at upload)
- After upload, probe the image's size without decoding a frame:
ui.ImmutableBuffer.fromUint8Listthenui.ImageDescriptor.encoded(buffer)exposeswidth/heightfrom the header. - Append
#w=<w>&h=<h>to the URL; if the probe fails, return the URL unchanged. - Do it in every compose path (editor attach, camera, share target).
Why a fragment: it never reaches the server (no API change, cache keys unchanged), it survives in
stored markdown, and Uri.parse keeps it out of download requests.
Read side
- Parse with an anchored regex on the fragment (
^w=(\d{1,5})&h=(\d{1,5})$). - In a
LayoutBuilder, compute the exactBoxFit.containsize under the available width and a max height, never upscaling (scale <= 1). Give the placeholder and the image'sSizedBoxthat same size: zero shift. - Set
cacheWidthto display width x devicePixelRatio. - Placeholder plus a short fade:
loadingBuildershows a progress-valued box,frameBuilderwith anAnimatedSwitcher(200 ms) fades once from placeholder to image; it stays GIF-safe because later frames update the same child. - Old content without a fragment falls back to a fixed-height placeholder.
The compatibility trap
Any code that infers type from the URL must strip the fragment first. The filename helper saw
png#w=... as the extension, failed the image check, and rendered the image as a generic file card.
Fixed in the same release, but older Android builds still in the wild showed every new image as a
file card until they updated. Web always runs the latest build; sideloaded APKs do not. When you
change a URL format, check what old clients do with it.
Related: server thumbnails
List cards show a 56 dp thumbnail fetched from a fixed-size server thumbnail route rather than the original; see Accepting and serving user uploads safely from a private bucket.
See also
- Inline blur-up placeholders (LQIP): JPEG beats WebP across a page
- Flutter and Dart gotchas (collections, widgets, theming)