Build UIs with stateless/stateful widgets, Row, Column, Stack, and Flex layouts.
Widget Fundamentals
Everything in Flutter is a widget. Widgets are immutable descriptions of UI.
Widget Tree Element Tree Render Tree
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ MaterialApp │──────────────▶│ _MaterialApp│───────────────▶│ RenderView │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Scaffold │──────────────▶│ _Scaffold │───────────────▶│ RenderFlex │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Column │──────────────▶│ _Column │───────────────▶│ RenderFlex │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
▼ ▼ ▼
Children Children Children
StatelessWidget vs StatefulWidget
StatelessWidget
Immutable - never changes after creation.
class MovieCard extends StatelessWidget {
final String title;
final int year;
final double rating;
final VoidCallback? onTap;
const MovieCard({
super.key,
required this.title,
required this.year,
required this.rating,
this.onTap,
});
@override
Widget build(BuildContext context) {
return Card(
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: Theme.of(context).textTheme.titleLarge),
Text('$year • ⭐ $rating/10'),
],
),
),
),
);
}
}StatefulWidget
Mutable - can change over time via setState.
class FavoriteButton extends StatefulWidget {
final bool initialFavorite;
final ValueChanged<bool>? onChanged;
const FavoriteButton({
super.key,
this.initialFavorite = false,
this.onChanged,
});
@override
State<FavoriteButton> createState() => _FavoriteButtonState();
}
class _FavoriteButtonState extends State<FavoriteButton> {
late bool _isFavorite;
@override
void initState() {
super.initState();
_isFavorite = widget.initialFavorite;
}
void _toggle() {
setState(() {
_isFavorite = !_isFavorite;
});
widget.onChanged?.call(_isFavorite);
}
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(
_isFavorite ? Icons.favorite : Icons.favorite_border,
color: _isFavorite ? Colors.red : null,
),
onPressed: _toggle,
);
}
}When to Use Which
| Scenario | Widget Type |
|---|---|
| UI depends only on constructor params | StatelessWidget |
| UI changes over time (user input, animation, data) | StatefulWidget |
| Simple toggle, counter, form input | StatefulWidget |
| Complex state shared across widgets | State management (Provider/Riverpod/Bloc) |
Layout Widgets
Column - Vertical Layout
Column(
// Main axis (vertical) alignment
mainAxisAlignment: MainAxisAlignment.center,
// Cross axis (horizontal) alignment
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Title'),
Text('Subtitle'),
Spacer(), // Flexible empty space
Text('Bottom'),
],
)Row - Horizontal Layout
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(Icons.movie),
Expanded(
child: Text('Movie Title', overflow: TextOverflow.ellipsis),
),
IconButton(icon: Icon(Icons.favorite), onPressed: () {}),
],
)Flex - Flexible Children
// Flexible: child can flex but has min/max constraints
Flexible(
flex: 2, // Takes 2/3 of available space
child: Container(color: Colors.red),
)
Flexible(
flex: 1, // Takes 1/3 of available space
child: Container(color: Colors.blue),
)
// Expanded: shorthand for Flexible(fit: FlexFit.tight)
Expanded(
child: Container(color: Colors.green),
)Stack - Overlapping Children
Stack(
alignment: Alignment.center,
children: [
// Background
Image.network('https://example.com/bg.jpg', fit: BoxFit.cover),
// Gradient overlay
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black54],
),
),
),
// Content on top
Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Movie Title', style: TextStyle(color: Colors.white, fontSize: 24)),
Text('2024 • Sci-Fi', style: TextStyle(color: Colors.white70)),
],
),
// Positioned widget
Positioned(
top: 16,
right: 16,
child: IconButton(
icon: Icon(Icons.close, color: Colors.white),
onPressed: () {},
),
),
],
)Container - Single Child with Decoration
Container(
width: 200,
height: 100,
padding: EdgeInsets.all(16),
margin: EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey.shade300),
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 8,
offset: Offset(0, 2),
),
],
gradient: LinearGradient(
colors: [Colors.blue, Colors.purple],
),
),
child: Text('Content'),
)Constraint System
Flutter uses constraints go down, sizes go up:
Parent: "You can be between 0 and 300 wide"
Child: "I want to be 200 wide"
Parent: "OK, you are 200 wide"
BoxConstraints
// Unconstrained (infinite) - causes errors in Column/Row
// Fix: Wrap in Expanded, Flexible, or SizedBox
// Constrained
ConstrainedBox(
constraints: BoxConstraints(
minWidth: 100,
maxWidth: 300,
minHeight: 50,
maxHeight: 200,
),
child: ChildWidget(),
)
// Size constraints
SizedBox(
width: 200,
height: 100,
child: ChildWidget(),
)
// Aspect ratio
AspectRatio(
aspectRatio: 16 / 9,
child: ChildWidget(),
)
// Fraction of parent
FractionallySizedBox(
widthFactor: 0.8, // 80% of parent width
child: ChildWidget(),
)Intrinsic Dimensions
// Size to content (expensive, use sparingly)
IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Short'),
Text('Much longer text that determines width'),
],
),
)Common Layout Patterns
Card with Image and Content
class MovieCard extends StatelessWidget {
final Movie movie;
const MovieCard({super.key, required this.movie});
@override
Widget build(BuildContext context) {
return Card(
clipBehavior: Clip.antiAlias,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Image with fixed aspect ratio
AspectRatio(
aspectRatio: 16 / 9,
child: Image.network(
movie.posterUrl,
fit: BoxFit.cover,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return Center(
child: CircularProgressIndicator(
value: progress.expectedTotalBytes != null
? progress.cumulativeBytesLoaded / progress.expectedTotalBytes!
: null,
),
);
},
errorBuilder: (context, error, stackTrace) =>
Container(color: Colors.grey[200], child: Icon(Icons.error)),
),
),
// Content
Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(movie.title, style: Theme.of(context).textTheme.titleLarge),
SizedBox(height: 8),
Row(
children: [
Icon(Icons.star, color: Colors.amber, size: 16),
SizedBox(width: 4),
Text('${movie.rating}/10'),
Spacer(),
Text(movie.year.toString()),
],
),
],
),
),
],
),
);
}
}List Item with Leading/Trailing
ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(movie.posterUrl),
),
title: Text(movie.title),
subtitle: Text('${movie.year} • ${movie.genre}'),
trailing: IconButton(
icon: Icon(movie.isFavorite ? Icons.favorite : Icons.favorite_border),
onPressed: () => toggleFavorite(movie),
),
onTap: () => navigateToDetail(movie),
)Responsive Grid
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: MediaQuery.of(context).size.width > 600 ? 3 : 2,
childAspectRatio: 2 / 3,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
itemCount: movies.length,
itemBuilder: (context, index) => MovieCard(movie: movies[index]),
padding: EdgeInsets.all(16),
)Scrollable with Slivers
CustomScrollView(
slivers: [
SliverAppBar(
expandedHeight: 200,
flexibleSpace: FlexibleSpaceBar(
background: Image.network(headerImage, fit: BoxFit.cover),
),
pinned: true,
),
SliverPadding(
padding: EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 2 / 3,
crossAxisSpacing: 16,
mainAxisSpacing: 16,
),
delegate: SliverChildBuilderDelegate(
(context, index) => MovieCard(movie: movies[index]),
childCount: movies.length,
),
),
),
],
)Safe Areas and MediaQuery
// Handle notches, status bar, home indicator
SafeArea(
child: Scaffold(
body: Column(
children: [
// Status bar height automatically handled
Expanded(child: Content()),
// Bottom safe area (home indicator)
],
),
),
)
// Access device info
MediaQuery.of(context).size; // Screen size
MediaQuery.of(context).padding; // Safe area padding
MediaQuery.of(context).viewInsets; // Keyboard height
MediaQuery.of(context).platformBrightness; // Light/dark mode
MediaQuery.of(context).textScaler; // Text scaling factorHot Reload vs Hot Restart
| Feature | Hot Reload | Hot Restart |
|---|---|---|
| Speed | ~1 second | ~3 seconds |
| Preserves state | Yes | No |
| Code changes | Most changes | All changes |
| Trigger | r in terminal / Save | R in terminal |
Try It
Experiment with Row, Column, Stack, Flex. Try different mainAxisAlignment, crossAxisAlignment values. Add Expanded/Flexible.
class LayoutPlayground extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(width: 50, height: 50, color: Colors.red),
Container(width: 50, height: 50, color: Colors.green),
Container(width: 50, height: 50, color: Colors.blue),
],
),
],
),
),
);
}
}Build a movie detail screen
- Create a detail screen with hero image, title, metadata
- Use Stack for overlapping gradient and content
- Add Row for rating, year, genre chips
- Use Column for description and cast list
- Handle safe areas properly
- Make it responsive (different layouts for phone/tablet)
Flutter's layout is based on constraints. Column/Row for linear layouts, Stack for overlapping. Use Expanded/Flexible for flexible sizing. Everything is a widget - compose small widgets into larger ones. Hot reload preserves state for rapid iteration.
Resources
- Flutter Widget Catalog: https://docs.flutter.dev/ui/widgets
- Layout Tutorial: https://docs.flutter.dev/ui/layout
- BoxConstraints: https://api.flutter.dev/flutter/rendering/BoxConstraints-class.html
- Slivers: https://docs.flutter.dev/ui/widgets/slivers