CodeBlanks Logo Icon CodeBlanks

The setState method

Learn that setState triggers a rebuild.

The setState method

setState is the method that signals Flutter to call build again after you update data inside the State. The code you write inside setState changes the data; after setState returns, Flutter marks the State as dirty and runs build again in the next frame.

void artir() {
  setState(() {
    deger = deger + 1;
  });
}

dirty and rebuild

When setState is called, the State is marked as dirty. In the next frame, Flutter calls build again on every dirty State. This process is known as rebuild. Changes made without setState do not trigger build, so they never reach the screen.

// wrong: no setState, screen does not refresh
void artirYanlis() {
  deger = deger + 1;
}

// right: setState triggers build
void artirDogru() {
  setState(() {
    deger = deger + 1;
  });
}

Practice Print setState info

In main, print two lines with print: setState tetikler and dirty bekler.

Starter code

main.dart
void main() {
  // iki satır yazdır:
  // setState tetikler
  // dirty bekler

}

Sample solution

main.dart
void main() {
  print('setState tetikler');
  print('dirty bekler');
}

Expected output

setState tetikler
dirty bekler

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does setState do?

  • Completely restarts the app
  • Removes the widget from the tree
  • Marks the data change and triggers build Correct answer
  • Creates a new State object

Explanation: setState marks the data change and signals Flutter to call build again.

2 setState call

Question
void artir() {
  ____(() {
    deger = deger + 1;
  });
}
Answer
void artir() {
  setState(() {
    deger = deger + 1;
  });
}

Explanation: setState notifies Flutter of a data update and triggers build.

3 setState concepts

Term Meaning
setState çağrısı Triggers build again
rebuild build method called again
dirty State waiting to be redrawn
next frame Moment build runs

All lessons in Beginner