Component - setState for local state
This Flutter widget shows how to use setState to update local state inside a StatefulWidget. When the button is pressed, the number on screen increases by one.
This Flutter widget shows how to use setState to update local state inside a StatefulWidget. When the button is pressed, the number on screen increases by one.
Scaffold
├─ AppBar
│ └─ Text
└─ Center
└─ Column
├─ Text
└─ ElevatedButton
└─ TextsetState() inside a StatefulWidget in Flutter?setState()setState() tells Flutter that the widget's state has changed and the UI should update.setState().setState() in Flutter?setState syntaxsetState(() { ... });StatefulWidget:
int count = 0;
void increment() {
setState(() {
count += 2;
});
}
// Widget build shows count value
What will be the displayed count after calling increment() twice starting from 0?increment() adds 2 to count.StatefulWidget?
int counter = 0;
void increment() {
counter += 1;
}
// UI shows counter value
Why does the UI not update when increment() is called?setState() is called to notify changes.counter but does not call setState(), so UI does not refresh.setState() is not called to notify Flutter of the change -> Option CsetState()?setState() trigger UI updates.setState(). if (count % 2 == 0) {
count += 2;
} else {
count += 1;
} updates state outside setState, so UI won't refresh. setState(() => count += (count % 2 == 0) ? 2 : 1); uses arrow syntax but must return void, so it's invalid. count = (count % 2 == 0) ? count + 2 : count + 1; updates state without setState.Pass the test and this pattern moves unknown