Skip to content

[FR]: add global caching for SvgPicture instances to improve performance #721

@Chndr-3

Description

@Chndr-3

Is there an existing issue for this?

  • I have searched the existing issues

Describe the problem

SvgIntegration currently creates a new SvgPicture instance on every call, which can lead to hundreds of identical VectorGraphic and SvgPicture objects when reusing the same asset in large UIs. This results in excessive rebuild cost and memory usage (as observed in my own DevTools).

Describe the solution

Add a simple global cache mechanism in SvgGenImage to reuse identical SvgPicture widgets for repeated parameters (path, color, size, fit, etc.).

// Global cache to store and reuse identical SvgPicture instances.
// Prevents creating duplicate widgets for the same asset and parameters.
static final Map<String, _svg.SvgPicture> _cache = {};

// Generate a unique key for this SvgPicture configuration.
// Combines asset name and all relevant parameters that affect rendering.
final cacheKey =
    '${_assetName}-${colorFilter?.hashCode}-${color?.value}-${width ?? 0}-${height ?? 0}-${fit.name}-${alignment.hashCode}';

// Return the cached SvgPicture if one already exists for this configuration.
if (enableGlobalCache && _cache.containsKey(cacheKey)) {
  return _cache[cacheKey]!;
}

// Create a new SvgPicture instance when not found in cache.
final picture = _svg.SvgPicture(
  loader,
  key: key,
  matchTextDirection: matchTextDirection,
  width: width ?? size?.width,
  height: height ?? size?.height,
  fit: fit,
  alignment: alignment,
  allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
  placeholderBuilder: placeholderBuilder,
  semanticsLabel: semanticsLabel,
  excludeFromSemantics: excludeFromSemantics,
  colorFilter: colorFilter ??
      (color == null ? null : ColorFilter.mode(color, colorBlendMode)),
  clipBehavior: clipBehavior,
  cacheColorFilter: cacheColorFilter,
);

// Store the created instance in the cache for future reuse.
// Only applied when the global cache flag is enabled.
if (enableGlobalCache) {
  _cache[cacheKey] = picture;
}

// Return the SvgPicture (either newly created or from cache).
return picture;

Additional context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions