init method
初始化 SharedPreferences(single-flight:并发调用共享同一次 getInstance)。
完成后缓存到 _prefs;失败清空 in-flight Future 允许重试。app 启动时
调用一次即可。
Windows 文件自愈:init 成功后把 shared_preferences.json 备份一份
(.bak);init 失败时尝试用备份恢复(先校验备份为合法 JSON 对象才
回写,失败保现场),再按原语义 rethrow——备份 / 恢复自身的 IO 失败
只记日志,不影响 init 返回值。恢复成功后备份保留,下次 init 成功时
会重新备份为新鲜内容。web / 非 Windows 平台为 no-op。
失败路径的并发窗口(已定稿接受现状,注明语义):失败时先清空 in-flight Future 再做恢复,因此恢复完成前重入的 init 不会共享本次 恢复——它会再走一轮冷启动(底层仍坏则再失败一轮,恢复因幂等而不 叠加副作用);恢复完成后下一次调用按正常语义成功,不存在死锁。
返回 true 表示初始化成功(SharedPreferences 对象不外泄,
需要原始实例时用 getSp)。
Implementation
Future<bool> init() async {
if (_prefs != null) return true;
// 并发调用者共享同一个 in-flight Future(single-flight),避免各自调用
// getInstance()。
if (_initFuture != null) return _initFuture!;
final Future<bool> pending =
SharedPreferences.getInstance().then((p) async {
_prefs = p;
_initFuture = null;
// 成功路径备份(IO 失败仅记日志,不改变成功返回值)。
await sp_backup.backupSpFile();
return true;
}).catchError((Object e) async {
// 失败时清空,允许后续重试。
_initFuture = null;
// Windows 端尝试文件级自愈后再抛(rethrow 语义不变)。
await sp_backup.restoreSpFile();
throw e;
});
_initFuture = pending;
return pending;
}