Flutter Pro Design

Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Precache icons so they don't pop in

You might notice icons popping in one or two frames late in your Flutter apps. That's because Flutter loads assets into memory when a widget first asks for them, and decoding takes time.

You can fix this by preloading them during your splash screen.

For SVGs, flutter_svg has its own mechanism. For everything else, there's precacheImage. This helper handles both:

import 'package:flutter_svg/flutter_svg.dart';
  
Future<void> precacheAssets({
  required BuildContext context, 
  List<String> paths,
}) async {
  for (final String path in paths) {
    if (path.endsWith('.svg')) {
      final SvgAssetLoader loader = SvgAssetLoader(path);
        
      await svg.cache.putIfAbsent(
        loader.cacheKey(null),
        () => loader.loadBytes(null),
      );
    } else {
      await precacheImage(AssetImage(path), context);
    }
  }
}

Now in your splash screen, preload the icons the user will see as soon as the app opens. For the rest, load them in the background:

Future<void> preloadAssets(BuildContext context) async {
  // User sees these when app opens, wait for them
  await precacheAssets(
    context: context,
    paths: [
      'assets/icons/nav-bar/home.svg',
      'assets/icons/nav-bar/search.svg',
      'assets/icons/nav-bar/profile.svg',
      'assets/images/logo.png',
    ],
  );
  
  // User won't see these yet, load in the background
  precacheAssets(
    context: context, 
    paths: [
      'assets/icons/account/settings.svg',
      'assets/icons/account/notifications.svg',
    ],
  );
}

If you use asset codegen like flutter_gen, you can use Assets.icons.values instead of listing paths manually.

Also read: Load images smoothly