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 ?
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
.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With