To specify the question by an example:
If you create a new Flutter project you get the default counter-app where the _counter
variable is incremented in the setState
method of the State
class:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
....
But the following code works fine too:
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
_counter++;
setState(() {});
}
....
Here is a link to a working example in DartPad.
The documentation of the setState
method states that
The provided callback is immediately called synchronously.
and...
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.
According to this definition I see no reason why not to change the state variables before calling the setState
method and then provide an empty callback to setState
. Are there cases where this approach doesn't work or is it more or less "just" a matter of taste ( readability, clean coding,...)?
You are absolutely right. I don't know what the exact reason is but I'll try to explain what I think.
There is one purpose
setState
serves at the moment. It ensures that you update your state synchronously. See ImplementationFor example
This code might not work, because the widget will be rebuild before the variables change.
I'm not saying that you cannot change the state asynchronously, nor am I saying that careful coding doesn't work. It just a primal check for beginners.
I think Flutter has kept this approach to better cope with the risks involved with changes in the framework. There might not be a need for the callback now, but in the future, the framework might need to include certain functionality that would need this approach.
Whatever the true reason is, only Flutter team can tell.