TExcelTAD
Home › Flutter › Flutter Exercises

Flutter Exercises

Time to practise! Each exercise has a starter playground. Edit the code until it does what the task asks, then open Show solution to compare. The Dart exercises really run here; for the Flutter ones, try them in a project created with flutter create or on DartPad, and compare with the preview.

Tip: Don't peek too early. Getting stuck for a few minutes and working it out is exactly how the knowledge sticks.

Exercise 1 — Sum of even numbers (Dart)

Complete sumOfEvens so it returns the sum of all even numbers in the list. For the list below the answer is 2 + 4 + 10 = 16.

dart · try it yourself
int sumOfEvens(List<int> numbers) {
  // TODO: add up only the even numbers
  return 0;
}

void main() {
  print('Sum of evens: ${sumOfEvens([1, 2, 3, 4, 7, 10])}');
}
Sum of evens: 0
Show solution
dart
int sumOfEvens(List<int> numbers) =>
    numbers.where((n) => n.isEven).fold(0, (sum, n) => sum + n);

void main() {
  print('Sum of evens: ${sumOfEvens([1, 2, 3, 4, 7, 10])}'); // Sum of evens: 16
}

Exercise 2 — Word counter (Dart)

Fill the counts map so each word maps to how many times it appears, then print the entries. Expected output: the: 3, cat: 2, sat: 1, on: 1, mat: 1 (one per line).

dart · try it yourself
void main() {
  const text = 'the cat sat on the mat the cat';
  final counts = <String, int>{};

  // TODO: split the text and count each word

  counts.forEach((word, n) => print('$word: $n'));
  print('Distinct words: ${counts.length}');
}
Distinct words: 0
Show solution
dart
void main() {
  const text = 'the cat sat on the mat the cat';
  final counts = <String, int>{};

  for (final word in text.split(' ')) {
    counts[word] = (counts[word] ?? 0) + 1;
  }

  counts.forEach((word, n) => print('$word: $n'));
  print('Distinct words: ${counts.length}'); // 5
}

A Dart map remembers insertion order, so the words print in the order they first appeared.

Exercise 3 — A Rectangle class (Dart)

Write a Rectangle class with final fields width and height, a const constructor, an area getter and a toString that returns e.g. Rectangle(3 x 4). Then make main print Rectangle(3 x 4) has area 12.

dart · try it yourself
// TODO: define class Rectangle here

void main() {
  print('Create the Rectangle class first!');
}
Create the Rectangle class first!
Show solution
dart
class Rectangle {
  const Rectangle(this.width, this.height);

  final int width;
  final int height;

  int get area => width * height;

  @override
  String toString() => 'Rectangle($width x $height)';
}

void main() {
  const r = Rectangle(3, 4);
  print('$r has area ${r.area}'); // Rectangle(3 x 4) has area 12
}

Exercise 4 — Null-safe greeting (Dart)

greet receives a nullable name. Return Hello, <name>!, but use Hello, guest! when the name is null or empty. Use ?? and/or a null check instead of !.

dart · try it yourself
String greet(String? name) {
  // TODO
  return 'Hello, ???!';
}

void main() {
  print(greet('Lan'));
  print(greet(null));
  print(greet(''));
}
Hello, ???!
Hello, ???!
Hello, ???!
Show solution
dart
String greet(String? name) {
  if (name == null || name.isEmpty) return 'Hello, guest!';
  return 'Hello, $name!'; // name is promoted to String here
}

void main() {
  print(greet('Lan'));  // Hello, Lan!
  print(greet(null));   // Hello, guest!
  print(greet(''));     // Hello, guest!
}

Exercise 5 — Waiting for futures (Dart)

loadUser and loadOrders both take a moment. Make main wait for both at the same time using Future.wait, then print Ana has 3 orders.

dart · try it yourself
Future<String> loadUser() async {
  await Future.delayed(const Duration(milliseconds: 80));
  return 'Ana';
}

Future<int> loadOrders() async {
  await Future.delayed(const Duration(milliseconds: 40));
  return 3;
}

Future<void> main() async {
  // TODO: await both futures with Future.wait
  print('Loading...');
}
Loading...
Show solution
dart
Future<void> main() async {
  print('Loading...');
  final results = await Future.wait([loadUser(), loadOrders()]);
  final name = results[0] as String;
  final orders = results[1] as int;
  print('$name has $orders orders');
}

With Dart 3 records you can also write final (name, orders) = await (loadUser(), loadOrders()).wait; — fully typed, no casts.

Exercise 6 — Parse JSON into objects (Dart)

Decode the JSON and create a list of Book objects using a Book.fromJson factory. Print each book as <title> (<year>).

dart · try it yourself
import 'dart:convert';

class Book {
  const Book(this.title, this.year);
  final String title;
  final int year;
  // TODO: add factory Book.fromJson(Map<String, dynamic> json)
}

void main() {
  const json = '[{"title": "Dune", "year": 1965}, {"title": "Neuromancer", "year": 1984}]';
  final raw = jsonDecode(json) as List;
  print('Found ${raw.length} books');
}
Found 2 books
Show solution
dart
import 'dart:convert';

class Book {
  const Book(this.title, this.year);
  final String title;
  final int year;

  factory Book.fromJson(Map<String, dynamic> json) =>
      Book(json['title'] as String, json['year'] as int);
}

void main() {
  const json = '[{"title": "Dune", "year": 1965}, {"title": "Neuromancer", "year": 1984}]';
  final books = (jsonDecode(json) as List)
      .map((e) => Book.fromJson(e as Map<String, dynamic>))
      .toList();
  for (final b in books) {
    print('${b.title} (${b.year})');
  }
}

Exercise 7 — Profile card (Flutter)

Turn the plain column below into a centred Card with a CircleAvatar, the name in bold, the job title in grey, and 16 px padding inside the card.

flutter · try it yourself
class ProfileCard extends StatelessWidget {
  const ProfileCard({super.key});

  @override
  Widget build(BuildContext context) {
    // TODO: wrap in Center + Card + Padding, add an avatar and styles
    return const Column(
      children: [
        Text('Linh Tran'),
        Text('Mobile Developer'),
      ],
    );
  }
}
Show solution
dart
class ProfileCard extends StatelessWidget {
  const ProfileCard({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Card(
        child: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircleAvatar(radius: 32, child: Text('LT')),
              SizedBox(height: 12),
              Text('Linh Tran',
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
              Text('Mobile Developer', style: TextStyle(color: Colors.grey)),
            ],
          ),
        ),
      ),
    );
  }
}

Exercise 8 — Counter with reset (Flutter)

Make a StatefulWidget that shows a number and two buttons: +1 increases it and Reset sets it back to 0. The Reset button should be disabled (pass onPressed: null) while the count is already 0.

flutter · try it yourself
class CounterWithReset extends StatefulWidget {
  const CounterWithReset({super.key});

  @override
  State<CounterWithReset> createState() => _CounterWithResetState();
}

class _CounterWithResetState extends State<CounterWithReset> {
  // TODO: add a count field and the buttons
  @override
  Widget build(BuildContext context) {
    return const Center(child: Text('0', style: TextStyle(fontSize: 48)));
  }
}
Show solution
dart
class _CounterWithResetState extends State<CounterWithReset> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('$_count', style: const TextStyle(fontSize: 48)),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FilledButton(
              onPressed: () => setState(() => _count++),
              child: const Text('+1'),
            ),
            const SizedBox(width: 12),
            OutlinedButton(
              onPressed: _count == 0 ? null : () => setState(() => _count = 0),
              child: const Text('Reset'),
            ),
          ],
        ),
      ],
    );
  }
}

Exercise 9 — Tappable list with a SnackBar (Flutter)

Show the list of planets with ListView.builder. Each row should have a numbered CircleAvatar and, when tapped, show a SnackBar saying You picked Mars (with the right name).

flutter · try it yourself
class PlanetList extends StatelessWidget {
  const PlanetList({super.key});

  static const planets = ['Mercury', 'Venus', 'Earth', 'Mars'];

  @override
  Widget build(BuildContext context) {
    // TODO: return a ListView.builder
    return const Placeholder();
  }
}
Show solution
dart
class PlanetList extends StatelessWidget {
  const PlanetList({super.key});

  static const planets = ['Mercury', 'Venus', 'Earth', 'Mars'];

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: planets.length,
      itemBuilder: (context, i) => ListTile(
        leading: CircleAvatar(child: Text('${i + 1}')),
        title: Text(planets[i]),
        onTap: () => ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('You picked ${planets[i]}')),
        ),
      ),
    );
  }
}

Test yourself

Which Iterable method keeps only the elements that match a condition?

  1. map
  2. where
  3. fold
  4. any

How do you disable a Material button?

  1. Set enabled: false
  2. Pass onPressed: null
  3. Wrap it in Opacity
  4. Remove its child

What does Future.wait([a, b]) do?

  1. Runs a, then starts b after a finishes
  2. Waits for both futures concurrently and returns a list of results
  3. Cancels both futures
  4. Returns whichever finishes first