Skip to content

Commit

Permalink
[shared_preferences]Fix : SetState returning future (#8398)
Browse files Browse the repository at this point in the history
This pull request includes a change to the `SharedPreferencesDemoState` class in the `main.dart` file. The change improves the way the external counter value is fetched and updated in the state.

* [`packages/shared_preferences/shared_preferences/example/lib/main.dart`](diffhunk://#diff-6e8eaf30aa7259bf259f36e9c2057d82498b436c508f202521b4f8808788c15bL59-R61): Refactored the `_getExternalCounter` method to fetch the external counter value before calling `setState`, ensuring that asynchronous operations are handled correctly.

The issue was : 
```
 FlutterError (setState() callback argument returned a Future.
The setState() method on SharedPreferencesDemoState#1acdd(lifecycle state: created) was called with a closure or method that returned a Future. Maybe it is marked as "async".
Instead of performing asynchronous work inside a call to setState(), first execute the work (without updating the widget state), and then synchronously update the state inside a call to setState().)
```
  • Loading branch information
berhili098 authored Feb 10, 2025
1 parent 1023443 commit 1ecb531
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
4 changes: 4 additions & 0 deletions packages/shared_preferences/shared_preferences/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 2.5.2

* Fixes `setState` returning `Future` on `example/main.dart` error in example code.

## 2.5.1

* Exposes `SharedPreferencesOptions`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
/// or via some native system.
Future<void> _getExternalCounter() async {
final SharedPreferencesAsync prefs = SharedPreferencesAsync();
setState(() async {
_externalCounter = (await prefs.getInt('externalCounter')) ?? 0;
final int externalCounter = (await prefs.getInt('externalCounter')) ?? 0;
setState(() {
_externalCounter = externalCounter;
});
}

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.5.1
version: 2.5.2

environment:
sdk: ^3.5.0
Expand Down

0 comments on commit 1ecb531

Please sign in to comment.