Exercises
Build small widgets to lock in the Flutter fundamentals - stateless, stateful, async.
Three short challenges
EXAMPLE
// 1) Stateless: build a Profile card from a Map
class ProfileCard extends StatelessWidget {
final Map<String, String> user;
const ProfileCard({super.key, required this.user});
@override
Widget build(BuildContext context) {
return Card(
child: ListTile(
title: Text(user['name'] ?? ''),
subtitle: Text(user['email'] ?? ''),
),
);
}
}
// 2) Stateful: a counter that disables at 10
class CappedCounter extends StatefulWidget {
const CappedCounter({super.key});
@override
State<CappedCounter> createState() => _CappedCounterState();
}
class _CappedCounterState extends State<CappedCounter> {
int n = 0;
@override
Widget build(BuildContext context) {
final atCap = n >= 10;
return Column(children: [
Text('Count: $n'),
ElevatedButton(
onPressed: atCap ? null : () => setState(() => n++),
child: Text(atCap ? 'Maxed' : 'Add'),
),
]);
}
}
// 3) FutureBuilder: render a list from a fake API
class Names extends StatelessWidget {
const Names({super.key});
Future<List<String>> _load() async {
await Future.delayed(const Duration(milliseconds: 300));
return ['Ada', 'Linus', 'Grace'];
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<String>>(
future: _load(),
builder: (ctx, snap) {
if (!snap.hasData) return const CircularProgressIndicator();
return ListView(children: snap.data!.map(Text.new).toList());
},
);
}
}
Why it matters
Stateless first, stateful when you must, FutureBuilder for async. Keep build methods cheap - move work out of build and into init or state.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…