Empty set state what is the point?
Solution 1
I would say it's just a convention. The above can be re-written as
readLocal() async {
prefs = await SharedPreferences.getInstance();
setState(() {
id = prefs.getString('id') ?? '';
if (id.hashCode <= peerId.hashCode) {
groupChatId = '$id-$peerId';
} else {
groupChatId = '$peerId-$id';
}
});
}
Both will do the same thing. Calling setState(() {})
after mutating the state variable
looks neat and reabable.
As per the implementation section of setState
, it will below things in order.
- Assertions. If any assert fails, throws exception and stops there.
- Execute the callback function (
final dynamic result = fn() as dynamic;
) - Ask framework to rebuild(
_element.markNeedsBuild();
)
Solution 2
The documentation says [ https://docs.flutter.io/flutter/widgets/State/setState.html ]:
Calling setState notifies the framework that the internal state of this object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.
The empty bracket { }
is the empty callback (because you apparently don't need one):
The provided callback is immediately called synchronously. [...]
In short:
setState(() {});
is a way to tell the framework to build the state object anew, without using the possibility to pass a callback which would be called right after the build

Aya Elsisy
Updated on December 06, 2022Comments
-
Aya Elsisy 28 minutes
I want to know the point behind calling
setState
without setting a new value to the variables.readLocal() async { prefs = await SharedPreferences.getInstance(); id = prefs.getString('id') ?? ''; if (id.hashCode <= peerId.hashCode) { groupChatId = '$id-$peerId'; } else { groupChatId = '$peerId-$id'; } setState(() {}); }
-
Randal Schwartz about 4 yearsThe style guide (somewhere) says not to do this, because it should be clear from looking at the
setState
about why you are calling it, and if things get refactored such that the code is no longer needed here, the correspondingsetState
call can also be refactored out. -
Gazihan Alankus over 3 yearsEmpty
setState
usage should be avoided. medium.com/@mehmetf_71205/setting-the-state-2809936fb79d -
Karol Zlot over 1 yearI think "right after the build" part is not correct. It should be "just before rebuilding".
-
Monday Fatigue 10 months