flutterflutter-state

Need explanation for setState() function in Flutter


I am confused on why do we have to put a function in setState to update variables. I could instead update the variables and call setState. I modified the code from https://flutter.dev/docs/development/ui/widgets-intro

class _CounterState extends State<Counter> {
  int _counter = 0;

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

Instead, I thought of doing this

class _CounterState extends State<Counter> {
  int _counter = 0;

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

This still works, now I was thinking why make setState() have a function as a parameter, instead setState could not have any parameters like setState(); and we would just call it after we update our variables.


Solution

  • You'll find the answer in the official docs:

    The provided callback is immediately called synchronously. [...] If you just change the state directly without calling setState, the framework might not schedule a build and the user interface for this subtree might not be updated to reflect the new state.

    I think the problem is that UI and state object will not be in sync for a short period of time if you call setState((){}); after changing the state.