为什么获取 SharedPreferences 的实例是一个异步函数?缓存实例是一种好习惯吗?
Why getting the Instance of SharedPreferences is an async function? Is it a good practice to cache the instance?
我想知道为什么 SharedPreferences.getInstance()
是一个 async
函数?!我想将实例缓存在一个静态变量中,并用它来存储设置数据,而不必使用 await
或 SharedPreferences.getInstance().then(...)
,但如果他们做到了 async
,那应该是好的原因,有什么想法吗?
SharedPreferences.getInstance()
实际上获取数据并且 不只是 提供对 SharedPreferences 实例的引用
static Future<SharedPreferences> getInstance() async {
if (_completer == null) {
_completer = Completer<SharedPreferences>();
try {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
_completer.complete(SharedPreferences._(preferencesMap));
} on Exception catch (e) {
// If there's an error, explicitly return the future with an error.
// then set the completer to null so we can retry.
_completer.completeError(e);
final Future<SharedPreferences> sharedPrefsFuture = _completer.future;
_completer = null;
return sharedPrefsFuture;
}
}
return _completer.future;
}
和
static Future<Map<String, Object>> _getSharedPreferencesMap() async {
final Map<String, Object> fromSystem = await _store.getAll();
assert(fromSystem != null);
// Strip the flutter. prefix from the returned preferences.
final Map<String, Object> preferencesMap = <String, Object>{};
for (String key in fromSystem.keys) {
assert(key.startsWith(_prefix));
preferencesMap[key.substring(_prefix.length)] = fromSystem[key];
}
return preferencesMap;
}
我不知道这是否微不足道,但它不适合我,我认为数据仅在 get functions
上获取。
我想知道为什么 SharedPreferences.getInstance()
是一个 async
函数?!我想将实例缓存在一个静态变量中,并用它来存储设置数据,而不必使用 await
或 SharedPreferences.getInstance().then(...)
,但如果他们做到了 async
,那应该是好的原因,有什么想法吗?
SharedPreferences.getInstance()
实际上获取数据并且 不只是 提供对 SharedPreferences 实例的引用
static Future<SharedPreferences> getInstance() async {
if (_completer == null) {
_completer = Completer<SharedPreferences>();
try {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
_completer.complete(SharedPreferences._(preferencesMap));
} on Exception catch (e) {
// If there's an error, explicitly return the future with an error.
// then set the completer to null so we can retry.
_completer.completeError(e);
final Future<SharedPreferences> sharedPrefsFuture = _completer.future;
_completer = null;
return sharedPrefsFuture;
}
}
return _completer.future;
}
和
static Future<Map<String, Object>> _getSharedPreferencesMap() async {
final Map<String, Object> fromSystem = await _store.getAll();
assert(fromSystem != null);
// Strip the flutter. prefix from the returned preferences.
final Map<String, Object> preferencesMap = <String, Object>{};
for (String key in fromSystem.keys) {
assert(key.startsWith(_prefix));
preferencesMap[key.substring(_prefix.length)] = fromSystem[key];
}
return preferencesMap;
}
我不知道这是否微不足道,但它不适合我,我认为数据仅在 get functions
上获取。