我在 Flutter 应用程序中预加载资源图像时遇到问题。我的目标是在应用程序启动之前预加载所有资产图像,以确保更流畅的用户体验。然而,在尝试预加载图像时,我不断遇到上下文为空的问题,即使在尝试了不同的方法来获取当前上下文之后也是如此。这是我的代码:
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',
.....
];
您在运行 GetMaterialApp 之前预加载图像,这就是为什么它没有获取上下文,因为 navigatorKey 尚未分配。
要加载图像,请将您的“MyApp”设置为statefulWidget,然后在 initState() 方法中使用 Future.Delay 调用 preloadImage 函数,时间至少为 50 毫秒,以便您可以从 navigatorKey 获取上下文。