Quick, think about this for a second
This lesson doesn't teach anything new. It's a chance to combine the Column/Row layout, ElevatedButton, GestureDetector, TextField, StatefulWidget, and setState() from the Basic and Intermediate chapters and practice them on your own. Each task has you actually write out a widget tree and watch state changes show up on the UI in real time. Just copying code won't cut it here — you need to think through the logic yourself and fill it in. So resist the urge to peek at the answer right away and give it a real try first.
Exercises
Task 1: Build a counter app with StatefulWidget, adding both an increment button and a decrement button (make sure the count never goes below 0). Task 2: Combine Row and Column to lay out a profile card (an avatar circle, a name Text, and a description Text), using CrossAxisAlignment and MainAxisAlignment to keep everything aligned. Task 3: Use GestureDetector so that tapping a Container box cycles its background color through a color list. Task 4: Pair a TextField with a 'Show' button so that pressing the button displays whatever text the user typed into a Text widget below, using setState().
Code Example
// Task 1 skeleton - Counter with limit
class CounterBox extends StatefulWidget {
const CounterBox({super.key});
@override
State<CounterBox> createState() => _CounterBoxState();
}
class _CounterBoxState extends State<CounterBox> {
int count = 0;
void increment() {
setState(() {
count++;
});
}
void decrement() {
setState(() {
if (count > 0) count--;
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$count', style: const TextStyle(fontSize: 32)),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(onPressed: decrement, child: const Text('-')),
const SizedBox(width: 12),
ElevatedButton(onPressed: increment, child: const Text('+')),
],
),
],
);
}
}
// Task 3 hint - color cycle
final colors = [Colors.blue, Colors.green, Colors.orange, Colors.purple];
int colorIndex = 0;
// GestureDetector onTap: setState(() { colorIndex = (colorIndex + 1) % colors.length; });The counter widget works with two +/- buttons and never drops below 0, and the profile card, color-cycle box, and TextField+Show button tasks all update the UI correctly every time setState() is called.5-Minute Challenge
Once you've finished Task 4, add one more condition: if the TextField is empty when 'Show' is pressed, display a warning Text that says 'Please enter something' (5 minutes).
A Quick Word of Caution
Before checking the solutions for any task, read the error message yourself and try to debug it. Learning to read errors is one of the most important skills in learning Flutter.