Widgets, setState and layout
Understand when widgets rebuild, how setState triggers it, and how Row, Column and Expanded share space.
In Flutter, the screen is a tree of widgets, and the framework rebuilds parts of that tree whenever something changes. Knowing when and why a rebuild happens explains most screening questions about widgets.
Stateless and stateful widgets
A StatelessWidget displays only what it receives through its constructor. A StatefulWidget has a separate State object that keeps values between rebuilds. Use stateful widgets for things like a selected tab, a counter or form input. Use initState() for one-time setup and dispose() to release controllers, timers and subscriptions.
setState and build
Changing a field does not redraw anything on its own. setState marks the widget as needing a rebuild:
void _increment() {
setState(() {
count++;
});
}Flutter then calls build() again. Because build may run many times per second during animations, keep it fast and free of side effects: no network calls, no file reads, no creating controllers. Mark unchanging widgets const so Flutter can skip rebuilding them.
Row, Column and Expanded
A Row lays children out horizontally and a Column vertically. The main axis is the direction of layout, controlled by mainAxisAlignment; the cross axis is controlled by crossAxisAlignment. Children of a Row can be as wide as they like, so a long Text overflows and shows yellow and black stripes. Fix it with Expanded or Flexible. Several Expanded children share the free space by their flex values: with flex 2 and 1 in a 300-pixel row, they get 200 and 100.
Lists and hot reload
- Use
ListView.builderfor long or unknown-length lists; it builds items only as they appear. - A
ListViewinside aColumnneeds a bounded height, usually by wrapping it inExpanded. - Hot reload keeps state, so changes in
initStateor field initialisers need a hot restart to show.
Habit: when the screen does not update, check two things first: was the change wrapped in setState, and is the widget reading the field that changed?
More in Web and app