In Flutter everything on screen is a widget, so this mental model underlies every other lesson.
A widget is an immutable description of part of the UI: text, padding, a button, a whole screen. You build interfaces by composing small widgets into a tree: a Scaffold contains a Column, which contains Text and ElevatedButton widgets, and so on.
A `StatelessWidget` depends only on its constructor arguments. You override build(BuildContext context) and return a widget tree. Flutter calls build whenever the widget is inserted or its inputs change, and may call it often, so keep it fast and side-effect free.
Conventions:
- Fields are
final, and the constructor isconstwhen possible:const Greeting({super.key, required this.name});. Passingsuper.keylets parents give the widget a key. - Child widgets go in
childorchildrennamed parameters. - Extract a widget class when a build method grows; prefer new widget classes over helper methods returning widgets, since classes can be
constand rebuild independently.
`BuildContext` is the widget's location in the tree. Use it to look up inherited data: Theme.of(context), MediaQuery.sizeOf(context), Navigator.of(context).
Because widgets are immutable and cheap, "changing" the UI means building new widgets with new values. Flutter diffs them against the previous tree and updates only what changed on screen.
Example
import 'package:flutter/material.dart';
class ProfileCard extends StatelessWidget {
const ProfileCard({super.key, required this.name, this.role = 'Member'});
final String name;
final String role;
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme; // inherited lookup
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(name, style: textTheme.titleLarge),
Text(role, style: textTheme.bodySmall),
],
),
),
);
}
}
// Usage: const ProfileCard(name: 'Ana', role: 'Admin')Remember
- UIs are trees of small, immutable widgets
- StatelessWidget = output depends only on constructor fields
- Use
constconstructors and extract widget classes
Watch out for
- Doing work with side effects (network calls, timers) inside
build, which may run many times.