From 6d0f344b67c6eb81e0e85b01515c2bb14e8f93e3 Mon Sep 17 00:00:00 2001 From: Sorunome Date: Wed, 7 Oct 2020 18:39:21 +0200 Subject: [PATCH] fix: overgo issues with flutter_secure_store --- lib/components/theme_switcher.dart | 2 +- lib/utils/famedlysdk_store.dart | 34 +++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/components/theme_switcher.dart b/lib/components/theme_switcher.dart index f5ddadf..a212b82 100644 --- a/lib/components/theme_switcher.dart +++ b/lib/components/theme_switcher.dart @@ -175,7 +175,7 @@ class ThemeSwitcherWidgetState extends State { BuildContext context; Future loadSelection(MatrixState matrix) async { - String item = await matrix.store.getItem('theme') ?? 'light'; + String item = await matrix.store.getItem('theme') ?? 'system'; selectedTheme = Themes.values.firstWhere( (e) => e.toString() == 'Themes.' + item, orElse: () => Themes.system); diff --git a/lib/utils/famedlysdk_store.dart b/lib/utils/famedlysdk_store.dart index b14e4b0..52b18fc 100644 --- a/lib/utils/famedlysdk_store.dart +++ b/lib/utils/famedlysdk_store.dart @@ -199,9 +199,30 @@ Future migrate(String clientName, Database db, Store store) async { }); } +// see https://github.com/mogol/flutter_secure_storage/issues/161#issuecomment-704578453 +class AsyncMutex { + Completer _completer; + + Future lock() async { + while (_completer != null) { + await _completer.future; + } + + _completer = Completer(); + } + + void unlock() { + assert(_completer != null); + final completer = _completer; + _completer = null; + completer.complete(); + } +} + class Store { final LocalStorage storage; final FlutterSecureStorage secureStorage; + static final _mutex = AsyncMutex(); Store() : storage = LocalStorage('LocalStorage'), @@ -217,9 +238,12 @@ class Store { } } try { + await _mutex.lock(); return await secureStorage.read(key: key); } catch (_) { return null; + } finally { + _mutex.unlock(); } } @@ -231,7 +255,12 @@ class Store { if (value == null) { return await secureStorage.delete(key: key); } else { - return await secureStorage.write(key: key, value: value); + try { + await _mutex.lock(); + return await secureStorage.write(key: key, value: value); + } finally { + _mutex.unlock(); + } } } @@ -245,9 +274,12 @@ class Store { } } try { + await _mutex.lock(); return await secureStorage.readAll(); } catch (_) { return {}; + } finally { + _mutex.unlock(); } } }