tezvyn:

Flutter's setState(): Triggering UI Updates

AI-drafted, machine-checkedSource: api.flutter.devintermediate

setState() tells Flutter "my data changed, so rebuild the UI." It's not the change itself, but the notification that a change happened. Use it in a StatefulWidget's State class when events modify data your build() method uses.

WHY IT EXISTS: Flutter needs an explicit signal to know when to redraw a part of the screen. Simply changing a variable's value isn't enough for the framework to detect. The setState() method provides this signal, telling the framework that a widget's internal state has changed and its UI might need to be updated.

THE MENTAL MODEL: Think of setState() as flipping a "needs update" switch for a widget. You pass it a small function that performs the actual state change (e.g., _counter++). After that function runs, Flutter's engine is notified and schedules a call to your widget's build method in an upcoming frame. The UI doesn't change instantly, but the update is queued.

HOW IT WORKS: When you call setState((){ ... }), two things happen in order. First, the function you provided is executed synchronously. Second, the framework internally calls Element.markNeedsBuild(), which adds the widget to a "dirty" list. On the next frame, the Flutter engine rebuilds the widgets on this list, causing their build() methods to run again with the new state.

WHEN TO USE IT: Call setState() any time you change a variable inside a State object that affects the output of your build method. This is common in response to user input (like a button's onPressed), after a timer completes, or when data from a Future or Stream arrives and needs to be displayed.

WHEN NOT TO USE IT: Do not put asynchronous operations (like network requests or file I/O) directly inside the setState() callback; the callback must be synchronous. Perform the async work first, then call setState() with the result. Avoid calling it from within the build method, as this can cause infinite rebuild loops. Finally, never call it after the widget has been removed from the tree (after dispose() is called).

ONE CANONICAL EXAMPLE: In the classic counter app, an _counter variable is stored in the State class. A FloatingActionButton's onPressed callback calls a method that wraps only the state mutation, _counter++, inside a setState() call. This signals Flutter to rebuild the widget, which then reads the new value of _counter and updates the Text widget on screen.

Read the original → api.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.