【发布时间】:2020-12-04 10:00:36
【问题描述】:
我正在开发一个 dart 应用程序,我想在其中获取缓存中存在的数据 (SharedPreferences),然后将其显示在应用程序的 UI(主屏幕)上。
问题:由于 SharedPreferences 是一个等待调用,我的主页加载,尝试读取数据并且应用程序崩溃,因为尚未从 SharedPreferences 获取数据,并且在此之前应用程序加载。
在从 SharedPreferences 读取缓存完成之前,如何才能启动应用程序? 这是必需的,因为我必须在应用程序的主页上显示来自 SharedPreferences 的数据。 我的项目的各种视图文件调用静态函数: MyService.getValue(key) 由于 cacheResponseJson 尚未填充而崩溃。我想在我的应用启动之前等待 SharedPreferences 完成。
Class MyService {
String _cacheString;
static Map < String, dynamic > cacheResponseJson;
MyService() {
asyncInit();
}
Future < void > asyncInit() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
_cacheString = sharedPreferences.getString(“ConfigCache”);
cacheResponseJson = jsonDecode(ecsCacheString);
}
static String getValue(String key) {
return cacheResponseJson[key];
}
}
void main() {
MyService s = MyService();
}
任何帮助将不胜感激!
【问题讨论】:
标签: flutter asynchronous dart caching sharedpreferences