Skip to content

Commit 1ecb531

Browse files
authored
[shared_preferences]Fix : SetState returning future (flutter#8398)
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().) ```
1 parent 1023443 commit 1ecb531

File tree

3 files changed

+8
-3
lines changed

3 files changed

+8
-3
lines changed

packages/shared_preferences/shared_preferences/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 2.5.2
2+
3+
* Fixes `setState` returning `Future` on `example/main.dart` error in example code.
4+
15
## 2.5.1
26

37
* Exposes `SharedPreferencesOptions`.

packages/shared_preferences/shared_preferences/example/lib/main.dart

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,9 @@ class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
5959
/// or via some native system.
6060
Future<void> _getExternalCounter() async {
6161
final SharedPreferencesAsync prefs = SharedPreferencesAsync();
62-
setState(() async {
63-
_externalCounter = (await prefs.getInt('externalCounter')) ?? 0;
62+
final int externalCounter = (await prefs.getInt('externalCounter')) ?? 0;
63+
setState(() {
64+
_externalCounter = externalCounter;
6465
});
6566
}
6667

packages/shared_preferences/shared_preferences/pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ description: Flutter plugin for reading and writing simple key-value pairs.
33
Wraps NSUserDefaults on iOS and SharedPreferences on Android.
44
repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences
55
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22
6-
version: 2.5.1
6+
version: 2.5.2
77

88
environment:
99
sdk: ^3.5.0

0 commit comments

Comments
 (0)