Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use preCachePicture() in flutter_svg

I'm using flutter_svg package to render SVG images in my app, as flutter does not officially supports SVG yet.I'm having a delay of probably few seconds while trying to load SVG images in my app and while looking for the solution I found out that I can preload the SVG image using preCachePicture(). The problem is that the official flutter_svg documentation does not clearly states nor there are other web material to show how to use this function to preload SVG images.

I'm calling loadPictures() function in initState() to preload the SVG picture.

String onboardImage = 'assets/images/onboard.svg';

@override
  void initState() {
    loadPictures();
    super.initState();
  }

  Future<void> loadPictures() async {
    await precachePicture(ExactAssetPicture((SvgPicture.svgStringDecoder),onboardImage), null);    
  } 

After calling preCachePicture(), How to load the precached image when I wanted to use it ?

like image 494
Shubhamhackz Avatar asked Jun 08 '20 07:06

Shubhamhackz


2 Answers

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.

like image 75
Aleksandar Avatar answered Sep 28 '22 09:09

Aleksandar


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());
}
like image 21
Alexander Melnikov Avatar answered Sep 28 '22 07:09

Alexander Melnikov