I’m encountering an issue with preloading asset images in my Flutter app. My goal is to preload all asset images before the app starts to ensure smoother user experience. However, I keep running into a problem where the context is null when trying to preload the images, even after trying different approaches to obtain the current context. This is my code:
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
void main() async {
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
await preloadImages();
FlutterNativeSplash.remove();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.theme,
navigatorKey: navigatorKey,
translations: TranslationService(),
locale: locale.initLocale,
fallbackLocale: const Locale('en'),
initialBinding: AppBindings(),
initialRoute:
pref.getValue('id') == null ? AppRoutes.welcome : AppRoutes.home,
getPages: AppPages.pages,
);
}
}
Future<void> preloadImages() async {
BuildContext? context = navigatorKey.currentContext;
if (context != null) {
for (String asset in allAsset) {
await precacheImage(AssetImage(asset), context);
}
} else {
print("Current context is null. Images couldn't be preloaded.");
}
}
final List<String> allAsset = [
'assets/images/user.png',
'assets/images/twitter.png',
'assets/images/logo2.png',
.....
];