Sub topic 2
Widgets Are Cheap, Immutable Descriptions
This chapter assumes you know basic Dart classes, constructors, and closures. You should also be comfortable composing simple Flutter widgets such as Row, Column, Padding, and Text.
The working model
A widget is an immutable description of part of the user interface. Immutable means that its fields cannot change after the object is created. A widget says what should appear, but it does not directly manage pixels or long-lived mutable state.
When a widget's build method runs, it returns a new widget configuration. Flutter compares that configuration with the previous one and updates the longer-lived objects behind it. Creating a new widget object does not mean Flutter throws away the entire screen.
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, Flutter'),
),
);
}
}GreetingApp.build creates a configuration tree. Directionality and Padding compose other widgets. Text describes text, but another object later handles its layout and painting.
| Widget kind | Main role | Usually owns mutable state? |
|---|---|---|
| `StatelessWidget` | Describes UI from its inputs | No |
| `StatefulWidget` | Identifies a stateful component | Its `State` object does |
| `InheritedWidget` | Provides data to descendants | Usually no |
| `RenderObjectWidget` | Creates or configures a render object | No |
Why widgets are cheap
Flutter expects build methods to create widget objects often. Keep widgets small and focused. Pass changing values through final constructor parameters instead of modifying a widget after construction.
Use const when every value in a widget subtree is compile-time constant:
const Text('Hello');Const widgets can be reused rather than recreated. More importantly, const documents that the configuration has no changing inputs. It does not make an entire application automatically fast. Expensive work inside build, such as sorting a large list or performing file access, still causes problems.
A widget should describe UI, not perform side effects. Start network requests, subscribe to streams, and manage controllers in the appropriate state or lifecycle methods.
Practical rule
Treat widgets as disposable input data. Put persistent values in State, keep widget fields final, use const for fixed subtrees, and avoid unrelated work in build.
Exercise
Why can Flutter create a new Padding widget during a rebuild without necessarily losing the existing UI state?
Show answer
The widget is only immutable configuration. Flutter can reuse the existing element and its related objects when the new configuration matches the old one.