Sub topic 1
Why Flutter Rebuilds UI from Configuration
Flutter uses a declarative UI model. You describe what the interface should look like for the current state. Flutter compares that description with the existing UI and updates only what changed.
This approach differs from directly modifying views. You do not usually find a text label and change its contents. Instead, you change application state and build a new widget description from that state.
Prerequisites
Assume you know basic Dart classes, constructors, fields, and closures. You should also be familiar with StatelessWidget, StatefulWidget, and composing widgets such as Column, Padding, and Text.
Widgets Describe the Desired UI
A widget is an immutable object that describes part of the interface. Immutable means its fields do not change after the object is created. A widget can contain values such as text, color, padding, or a child widget.
For example, this build method describes a greeting:
import 'package:flutter/widgets.dart';
void main() {
runApp(const GreetingApp());
}
class GreetingApp extends StatelessWidget {
const GreetingApp({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Hello'),
),
);
}
}The returned objects form a widget tree. GreetingApp contains Directionality, which contains Padding, which contains Text. Some of these widgets only compose other widgets. They do not directly draw pixels.
Rebuilding Means Recomputing Configuration
A rebuild runs a widget's build method again. It creates a new description using the latest state. Rebuilding does not necessarily mean that Flutter destroys and recreates every visible object.
For a counter, setState changes the state and tells Flutter that the associated part of the tree needs rebuilding:
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
void increment() {
setState(() {
count++;
});
}
@override
Widget build(BuildContext context) {
return Text('Count: $count');
}
}Flutter calls build again and receives a new Text widget. Flutter then compares the new configuration with the existing tree. Matching objects can be updated or reused, while changed parts may be replaced.
The separation between configuration and managed objects lets Flutter preserve useful work. Your code can describe the complete result, while Flutter decides which underlying objects need updating.
Exercise
What does a rebuild recompute, and why does it not automatically mean that the whole screen is recreated?
Show answer
A rebuild recomputes widget configuration by running build again. Flutter compares the new configuration with the existing tree and reuses compatible objects where possible.