Skip to content

Commit

Permalink
[shared_preferences] Fix initialization race (#4159)
Browse files Browse the repository at this point in the history
During the NNBD transition, the structure of the completer logic in the initialization flow was incorrectly changed to set the field after an `await` instead of immediately.

Also updates the error handling to handle `Error` the same way it currently handles `Exception`, which this change surfaced.

Fixes flutter/flutter#42407
  • Loading branch information
stuartmorgan authored Jun 8, 2023
1 parent 010ba50 commit d935cb0
Show file tree
Hide file tree
Showing 4 changed files with 193 additions and 175 deletions.
4 changes: 3 additions & 1 deletion packages/shared_preferences/shared_preferences/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## NEXT
## 2.1.2

* Fixes singleton initialization race condition introduced during NNBD
transition.
* Updates minimum supported macOS version to 10.14.
* Updates minimum supported SDK version to Flutter 3.3/Dart 2.18.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,19 @@ class SharedPreferences {
if (_completer == null) {
final Completer<SharedPreferences> completer =
Completer<SharedPreferences>();
_completer = completer;
try {
final Map<String, Object> preferencesMap =
await _getSharedPreferencesMap();
completer.complete(SharedPreferences._(preferencesMap));
} on Exception catch (e) {
} 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;
}
_completer = completer;
}
return _completer!.future;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: Flutter plugin for reading and writing simple key-value pairs.
Wraps NSUserDefaults on iOS and SharedPreferences on Android.
repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
version: 2.1.1
version: 2.1.2

environment:
sdk: ">=2.18.0 <4.0.0"
Expand Down
Loading

0 comments on commit d935cb0

Please sign in to comment.