Empty set state what is the point?

4,829

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.

  1. Assertions. If any assert fails, throws exception and stops there.
  2. Execute the callback function (final dynamic result = fn() as dynamic;)
  3. 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

Share:
4,829
Aya Elsisy
Author by

Aya Elsisy

Updated on December 06, 2022

Comments

  • Aya Elsisy
    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
    Randal Schwartz about 4 years
    The 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 corresponding setState call can also be refactored out.
  • Gazihan Alankus
    Gazihan Alankus over 3 years
    Empty setState usage should be avoided. medium.com/@mehmetf_71205/setting-the-state-2809936fb79d
  • Karol Zlot
    Karol Zlot over 1 year
    I think "right after the build" part is not correct. It should be "just before rebuilding".
  • Monday Fatigue 10 months