When do I use setState in Flutter?

When you change the state of a stateful widget, use setState() to cause a rebuild of the widget and it's descendants.
You don't need to call setState() in the constructor or initState() of the widget, because build() will be run afterwards anyway.

Also don't call setState() in synchronous code inside build(). You shouldn't need to cause a rerun of build() from within build().


According to the docs:

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.

So if the state of the widget changes you have to call setState to trigger a rebuild of the view and see immediatly the changes implied by the new state.

Anyhow the below snippets are equivalent.

first case (directly form flutter create <myproject>):

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {

    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

second case:

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    _counter++;
    setState(() {});
  }

What I don't know is the reason why and if the first case is the conventional way to use setState, I would say because of readability of code.