Skip to content

[vector_graphics, flutter_svg] Implement robust precacheVectorGraphic and precacheSvg utilities #186481

Description

@kevmoo

Description / Motivation

Developers attempting to precache vector graphics or SVGs to prevent route transition jank often run into cache misses and performance regressions.

There are two primary caching bottlenecks:

  1. Theme-based Cache Misses: In flutter_svg, svg.cache keys include the SvgTheme derived from BuildContext (DefaultSvgTheme.of(context)). If a developer precaches early by calling loader.loadBytes(null), the cache key uses a default theme. When the widget is later rendered inside a MaterialApp route hierarchy with different inherited text styles or font sizes, the cache key mismatches, causing svg.cache to miss and re-fetch/re-parse everything on the fly.
  2. Ephemeral Live Picture Cache: In vector_graphics, the internal _livePictureCache is reference-counted (count == 0 when no widgets are actively mounted). Therefore, preloading bytes doesn't keep the decoded ui.Picture alive across route transitions.

Providing dedicated precacheVectorGraphic and precacheSvg functions (analogous to Flutter's precacheImage) would allow developers to correctly warm up both the byte cache and the live picture cache using the target BuildContext.

Proposed API

Add utility functions in both packages:

// In package:vector_graphics
Future<void> precacheVectorGraphic(
  BytesLoader loader,
  BuildContext context, {
  VectorGraphicsErrorListener? onError,
}) async {
  // Resolves bytes, decodes PictureInfo using context (locale/directionality),
  // and seeds _livePictureCache with an initial reference count or warm state.
}

// In package:flutter_svg
Future<void> precacheSvg(
  SvgLoader loader,
  BuildContext context, {
  VectorGraphicsErrorListener? onError,
}) async {
  // Derives the correct SvgTheme from context, resolves bytes into svg.cache,
  // and ensures downstream VectorGraphic caching is warmed up.
}

Example Usage

@override
void didChangeDependencies() {
  super.didChangeDependencies();
  // Properly warms up caches with the correct inherited SvgTheme and Locale
  precacheSvg(SvgNetworkLoader('https://example.com/icon.svg'), context);
}

See #186479 RE adding MemoryBytesLoader
See #186480 RE adding PictureVectorGraphic

Metadata

Metadata

Assignees

No one assigned

    Labels

    c: new featureNothing broken; request for a new capabilityc: proposalA detailed proposal for a change to Flutterengineflutter/engine related. See also e: labels.p: flutter_svgThe Flutter SVG drawing packagesp: vector_graphicsThe vector_graphics package setpackageflutter/packages repository. See also p: labels.team-engineOwned by Engine team

    Fields

    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions