Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions packages/shared_preferences/lib/shared_preferences.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,24 @@ class SharedPreferences {
SharedPreferences._(this._preferenceCache);

static const String _prefix = 'flutter.';
static SharedPreferences _instance;
static Completer<SharedPreferences> _completer;
static Future<SharedPreferences> getInstance() async {
if (_instance == null) {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
_instance = SharedPreferences._(preferencesMap);
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 _instance;
return _completer.future;
}

/// The cache that holds all preferences.
Expand Down Expand Up @@ -168,7 +178,7 @@ class SharedPreferences {

/// Initializes the shared preferences with mock values for testing.
///
/// If the singleton instance has been initialized already, it is automatically reloaded.
/// If the singleton instance has been initialized already, it is nullified.
@visibleForTesting
static void setMockInitialValues(Map<String, dynamic> values) {
_kChannel.setMockMethodCallHandler((MethodCall methodCall) async {
Expand All @@ -177,6 +187,6 @@ class SharedPreferences {
}
return null;
});
_instance?.reload();
_completer = null;
}
}
6 changes: 6 additions & 0 deletions packages/shared_preferences/test/shared_preferences_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ void main() {
expect(preferences.getString('String'), kTestValues2['flutter.String']);
});

test('back to back calls should return same instance.', () async {
final Future<SharedPreferences> first = SharedPreferences.getInstance();
final Future<SharedPreferences> second = SharedPreferences.getInstance();
expect(await first, await second);
});

group('mocking', () {
const String _key = 'dummy';
const String _prefixedKey = 'flutter.' + _key;
Expand Down