Hello, Iiro! I am happy to hear that you found what I did too. Sometimes, we, developers have our own needs, styling, or to make convenient things more convenient =) So, don’t use the setState() method directly in daily code. Just I made an extension on State and added a couple of handy methods: first I can call without an anonymous empty function. And also I check if the widget actually is mounted before calling setState. I don’t want to discuss is it right or not. Just my points:

  1. one reason is when we can call setState(), the widget might be not mounted. So, at some point you get exceptions. And write everywhere “if (mounted) setState(() { … });” you probably will tire.

  2. some methods have complex computation. It’s possible to have different if/else or switch statements. So, if you are sure, that when the method will be done, you have to rebuild your widget. It probably maybe a callback from any notifier. And you don’t want to wrap the callback function into setState. Maybe, again, at some moment of the callback function, you understand you don’t want to update the widget state.

  3. One of the points is that to put complex computation into the setState method will make code not beautiful and pretty strange. Because, usually we see that in the setState method we have just fields with any modification operations, like a = newValueA; or _counter++. But what if we have a logic of those if/else, switch, etc. And to wrap all the stuff in the setStateCall within a new anonymous function often does not have sense.

  4. I don’t know how to explain all the situations. But I do have more clean and readable code and without an explicit call of the setState method. For instance, when we use FutureBuilder, StreamBuilder, ValueListenableBuilder, … or use the convenient flutter_hooks library, we don’t need to call the setState method explicitly. And nobody has problems with the magic of why don’t we call setState call manually.

  5. Also, when I use one strategy to code with my wrapper methods, I don’t want to break this coding approach by making a mix of different approaches.

But of course, we have to see code to understand why don’t all the developers need to put computation into setState() or why we have to call at the end the setState(() {}) within a new anonymous function instead of a call wrapper like updateState() extension method on State which also checks that widget is actually mounted.

Iiro, happy coding. Thank you for your discovering and investigation! See you!

GitHub-flavored Markdown & a sane subset of HTML is supported.