Skip to content

[shared_preferences] Fix JSON parsing issue with _decodeValue #5813

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 15 commits into from
Closed
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
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 2.2.3

* Fixes shared_preferences_web issue where non-JSON formatted strings cause parsing errors when `getAllWithParameters` is called.

## 2.2.2

* Updates minimum supported SDK version to Dart 3.2.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,16 +100,33 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform {
return json.encode(value);
}

Object _decodeValue(String encodedValue) {
final Object? decodedValue = json.decode(encodedValue);

if (decodedValue is List) {
// JSON does not preserve generics. The encode/decode roundtrip is
// `List<String>` => JSON => `List<dynamic>`. We have to explicitly
// restore the RTTI.
return decodedValue.cast<String>();
Object _decodeValue(String encodedValue) {
try {
// Attempt to decode the string as JSON
final Object? decodedValue = json.decode(encodedValue);

if (decodedValue is List) {
// JSON does not preserve generics. The encode/decode roundtrip results in
// `List<String>` => JSON => `List<dynamic>`. Explicit restoration of RTTI is required.
return decodedValue.cast<String>();
}

return decodedValue!;
} on FormatException {
// If there is a FormatException, try adding double quotes and parsing again
try {
return json.decode('\"$encodedValue\"');
} catch (e) {
// If parsing still fails, return the original string
// This indicates the string may not be a valid JSON format
return encodedValue;
}
} catch (e) {
// Print the exception and return an empty string
print(e.toString());
return '';
}

return decodedValue!;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: shared_preferences_web
description: Web platform implementation of shared_preferences
repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_web
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
version: 2.2.2
version: 2.2.3

environment:
sdk: ">=3.2.0 <4.0.0"
Expand Down