Widgets and Layout
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
In Flutter, the user interface is a tree of widgets. A widget is an immutable description of part of the screen; the framework turns it into pixels as explained in Architecture and Rendering. This page covers the widgets you use every day, how they are composed into layouts, and builds the Trailhead trail list and detail screens. State that outlives a single widget is the subject of State Management, and moving between the two screens is covered in Navigation and Routing.
StatelessWidget and StatefulWidget
A StatelessWidget renders only from its constructor arguments and the inherited context. A StatefulWidget pairs an
immutable widget with a long-lived State object that holds mutable data.
class SearchBox extends StatefulWidget {
const SearchBox({super.key, required this.onChanged});
final ValueChanged<String> onChanged;
@override
State<SearchBox> createState() => _SearchBoxState();
}
class _SearchBoxState extends State<SearchBox> {
late final TextEditingController _controller = TextEditingController(); // created once per State
@override
void dispose() {
_controller.dispose(); // release controllers, subscriptions and timers
super.dispose();
}
@override
Widget build(BuildContext context) =>
SearchBar(controller: _controller, hintText: 'Search trails', onChanged: widget.onChanged);
}
The lifecycle of a State object is: createState, initState, didChangeDependencies, build (many times),
didUpdateWidget (whenever the parent supplies a new widget), deactivate and finally dispose. Rules of thumb:
-
Create controllers in
initStateand release them indispose; never create them inbuild. -
Call
setStateto change state and schedule a rebuild; never call it afterdisposeor duringbuild. -
Check
mountedbefore using the context after anawaitinside aState. -
Keep
buildpure and fast: it can run on every frame during an animation.
BuildContext
A BuildContext is the handle to a widget’s position in the tree. It is how a widget looks up inherited data such as the
theme, media query or a provider above it: Theme.of(context), MediaQuery.sizeOf(context),
Navigator.of(context). A lookup registers a dependency, so the widget rebuilds when that inherited value changes. A context
refers to the widget that owns it, not to the widget it builds: calling Scaffold.of(context) with the context of the widget
that creates the Scaffold fails, so use a Builder or extract a child widget to get a context below it.
Keys
Keys tell the framework which element corresponds to which widget when a list is rebuilt in a different order. Without a key, elements are matched by type and position, so a reordered stateful row can show another row’s state.
Use ValueKey(trail.id) (a stable identifier from your data) for list items, ObjectKey when no single field is unique,
PageStorageKey to preserve scroll position, and GlobalKey to reach a State or FormState from elsewhere (costly,
use sparingly). UniqueKey forces a new element on every build and is rarely what you want.
Material 3, Cupertino and Theming
Flutter ships two design languages: Material 3 (package:flutter/material.dart, default in current releases) and
Cupertino (package:flutter/cupertino.dart) for iOS-styled widgets. Most apps use Material everywhere and adapt a few
controls with the .adaptive constructors such as Switch.adaptive. Theming is data, applied once at the top of the app.
final lightTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF2E7D32)),
useMaterial3: true,
appBarTheme: const AppBarTheme(centerTitle: false),
cardTheme: const CardThemeData(margin: EdgeInsets.symmetric(horizontal: 12, vertical: 6)),
);
// MaterialApp(theme: lightTheme, darkTheme: darkTheme, themeMode: ThemeMode.system)
Color overlay(BuildContext context) =>
Theme.of(context).colorScheme.primary.withValues(alpha: 0.12);
ColorScheme.fromSeed derives a complete, accessible palette from one colour. Read colours and text styles from
Theme.of(context) (colorScheme.surface, textTheme.titleMedium) instead of hard-coding them, so dark mode and
re-theming work automatically. Use withValues(alpha: 0.12) rather than the deprecated withOpacity.
Core Layout Widgets
| Widget | Role |
|---|---|
|
Lay children out along a horizontal or vertical main axis; |
|
Overlay children; |
|
Forces a child of a |
|
Lets a child take up to its share of the remaining space (loose fit). |
|
Add space around a child, or fix a size or gap ( |
|
Position a child inside the available space. |
|
Convenience for padding, decoration, size and alignment; prefer a specific widget when only one is needed. |
|
A |
|
Impose constraints or an aspect ratio. |
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.terrain, size: 40),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(trail.name, style: textTheme.titleMedium, maxLines: 2, overflow: TextOverflow.ellipsis),
Text('${trail.lengthKm.toStringAsFixed(1)} km', style: textTheme.bodyMedium),
],
),
),
Chip(label: Text(trail.difficulty.label)),
],
)
The Expanded around the Column is what stops the row from overflowing when the trail name is long.
Lists, ListView.builder and Slivers
ListView(children: [...]) builds every child immediately. ListView.builder builds an item only when it scrolls into
view, which is essential for long lists. A ListView is a convenience over slivers, scrollable areas that live inside a
CustomScrollView and can mix a collapsing app bar, lists and grids in a single scroll.
CustomScrollView(
slivers: [
const SliverAppBar.large(title: Text('Trails')),
SliverList.builder(
itemCount: trails.length,
itemBuilder: (context, index) => ListTile(key: ValueKey(trails[index].id), title: Text(trails[index].name)),
),
],
)
For a plain screen, ListView.builder is equivalent. Use ListView.separated for
dividers, GridView.builder for grids, and RefreshIndicator for pull-to-refresh.
The Trail List and Detail Screens
The list screen filters trails by a search query. The data arrives through a repository covered in Data, Storage and Networking; here the trails are passed in.
class TrailListScreen extends StatefulWidget {
const TrailListScreen({super.key, required this.trails});
final List<Trail> trails;
@override
State<TrailListScreen> createState() => _TrailListScreenState();
}
class _TrailListScreenState extends State<TrailListScreen> {
String _query = '';
@override
Widget build(BuildContext context) {
final visible = widget.trails
.where((t) => t.name.toLowerCase().contains(_query.toLowerCase()))
.toList();
return Scaffold(
appBar: AppBar(
title: const Text('Trailhead'),
bottom: PreferredSize(
preferredSize: const Size.fromHeight(64),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: SearchBox(onChanged: (value) => setState(() => _query = value)),
),
),
),
body: visible.isEmpty
? const Center(child: Text('No trails match your search'))
: ListView.builder(
itemCount: visible.length,
itemBuilder: (context, i) => ListTile(
key: ValueKey(visible[i].id),
title: Text(visible[i].name),
subtitle: Text('${visible[i].lengthKm} km'),
trailing: Text(visible[i].difficulty.label),
onTap: () => Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => TrailDetailScreen(trail: visible[i])),
),
),
),
);
}
}
class TrailDetailScreen extends StatelessWidget {
const TrailDetailScreen({super.key, required this.trail});
final Trail trail;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: Text(trail.name)),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Text(trail.name, style: theme.textTheme.headlineSmall),
const SizedBox(height: 8),
Wrap(spacing: 8, children: [
Chip(label: Text('${trail.lengthKm} km')),
Chip(label: Text(trail.difficulty.label)),
]),
const SizedBox(height: 24),
FilledButton(onPressed: () {}, child: const Text('Log a hike')),
],
),
);
}
}
Forms and Validation
Form groups FormField widgets such as TextFormField, and a FormState reached through a GlobalKey<FormState> validates
them together. This is the shape of the "log a hike" form.
final _formKey = GlobalKey<FormState>();
final _notes = TextEditingController(); // dispose it in the State's dispose method
Form(
key: _formKey,
child: Column(children: [
TextFormField(
controller: _notes,
decoration: const InputDecoration(labelText: 'Notes'),
validator: (v) => (v == null || v.trim().length < 3) ? 'Write at least 3 characters' : null,
),
FilledButton(
onPressed: () {
if (_formKey.currentState!.validate()) save(_notes.text.trim());
},
child: const Text('Save hike'),
),
]),
)
A validator returns an error message or null when the value is valid. Camera and GPS capture for the hike are covered in
Platform Integration.
Responsive Layout
Flutter apps run on phones, tablets, foldables, the web and desktop windows. Respond to the space available to a widget with
LayoutBuilder, and to the screen with MediaQuery. Prefer the specific accessors such as MediaQuery.sizeOf(context),
which rebuild the widget only when that property changes.
LayoutBuilder(
builder: (context, constraints) {
final columns = constraints.maxWidth >= 900 ? 3 : constraints.maxWidth >= 600 ? 2 : 1;
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: columns, mainAxisExtent: 112),
itemCount: trails.length,
itemBuilder: (context, i) => Card(child: ListTile(title: Text(trails[i].name))),
);
},
)
Design to window size classes (compact below 600, medium to 840, expanded above) rather than to device types, use
SafeArea to avoid notches and system bars, honour the text scale factor, and do not lock orientation unless the product
requires it.
Animations
Flutter offers two families of animation.
-
Implicit animations animate to a new value whenever a property changes, with no controller:
AnimatedContainer,AnimatedOpacity,AnimatedSwitcher,AnimatedAlign, and the genericTweenAnimationBuilder. -
Explicit animations use an
AnimationControllerdriven by aTickerProviderand give full control over play, pause and repeat.
late final AnimationController _controller =
AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); // State with SingleTickerProviderStateMixin
ScaleTransition(
scale: Tween<double>(begin: 1, end: 1.3).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut)),
child: IconButton(icon: const Icon(Icons.star), onPressed: () => _controller.forward(from: 0)),
)
An implicit equivalent for a fading badge is a single widget:
AnimatedOpacity(opacity: visible ? 1 : 0, duration: const Duration(milliseconds: 200), child: badge).
Always dispose controllers, and prefer implicit animations unless you need to control timing.
Accessibility
Flutter builds a semantics tree beside the widget tree, and the standard widgets populate it automatically: a
ListTile is announced as a tappable item, a TextFormField exposes its label. Add information when the widget alone is
not enough.
Semantics(
label: 'Add ${trail.name} to favourites',
button: true,
child: IconButton(
icon: const Icon(Icons.favorite_border),
tooltip: 'Add to favourites',
onPressed: () {},
),
)
Give every icon-only button a tooltip or Semantics label, keep touch targets at least 48 by 48 logical pixels, check
contrast (ColorScheme.fromSeed helps), support dynamic text sizes, and use ExcludeSemantics for purely decorative
images. Turn on TalkBack or VoiceOver to test, and run flutter test accessibility guidelines such as
meetsGuideline(androidTapTargetGuideline) in widget tests (see Testing).