How to use preCachePicture() in flutter_svg

Solution 1:

To cache multiple SVGs, do this:

Future.wait([
  precachePicture(
    ExactAssetPicture(
      SvgPicture.svgStringDecoder, // See UPDATE below!
      'assets/my_icon.svg',
    ),
    null,
  ),
  precachePicture(
    ExactAssetPicture(
      SvgPicture.svgStringDecoder, // See UPDATE below!
      'assets/my_asset.svg',
    ),
    null,
  ),
  // other SVGs or images here
]);

Note: do this in main.dart, or in a widget which is displayed before the widget which uses the SVG. For example, you can do it on splash screen if you need an svg for login or signup.


UPDATE: as per riccardogabellone's comment, since late 2021, instead of SvgPicture.svgStringDecoder we should use SvgPicture.svgStringDecoderOutsideViewBoxBuilder or SvgPicture.svgStringDecoderBuilder.

Solution 2:

Calling precache in your widget's initState is too late. You should instead call this method in the main() function like this:

Future<void> main() async {
    await precachePicture(ExactAssetPicture(SvgPicture.svgStringDecoder, 'assets/images/onboard.svg'), null);
    runApp(YourApp());
}