Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 73 ยท Practice and review

Practice Exercises with Solutions

Twelve Flutter exercises on layout, state, forms, navigation and async code, each with a hint and a full solution, plus runnable stand-ins for the logic.

Reading about Flutter is the easy part. You learn it when you build a screen, hit a red error and work out why. This page gives you twelve small exercises, grouped by topic. Each has a task, a hint and a solution. Try the task on your own first (in a real project with flutter create practice), then compare.

Real vs stand-in. The Dart solutions are real Flutter code and are read-only here, because the site cannot run Dart. Where an exercise is about logic (layout math, validation, async states), a JavaScript stand-in lets you run the idea in the page. Run your own Dart solutions on a device, emulator or in DartPad.

How to practise

Try first Ten minutes before peeking.
Use the hint Only if you are stuck.
Rewrite it Solve it again the next day.
1 / 2

Layout

Exercise 1: a profile header

Task. Build a row with a 64 px circular avatar on the left and, to its right, a name (bold) above a one-line bio. The bio must be cut off with an ellipsis when it is too long, never overflow.

Hint. Row gives children unbounded width. Something has to tell the text how wide it may be.

Solution.

DART
Row(
  children: [
    const CircleAvatar(radius: 32, child: Icon(Icons.person)),
    const SizedBox(width: 16),
    Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: const [
          Text('Ada Lovelace', style: TextStyle(fontWeight: FontWeight.bold)),
          Text(
            'Mathematician who wrote the first published algorithm for a machine.',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    ),
  ],
)

Expanded gives the column a bounded width equal to the remaining space, so Text can measure and truncate. See Row, Column and Flex.

Exercise 2: three equal-height cards that adapt

Task. Show three cards side by side on a wide screen (600 px or more) and stacked on a narrow one.

Hint. You need the available width, not the screen width. LayoutBuilder provides it.

Solution.

DART
LayoutBuilder(
  builder: (context, constraints) {
    final cards = [for (var i = 1; i <= 3; i++) Card(child: Center(child: Text('Card $i')))];
    if (constraints.maxWidth >= 600) {
      return Row(children: [for (final c in cards) Expanded(child: c)]);
    }
    return Column(children: [for (final c in cards) SizedBox(height: 100, width: double.infinity, child: c)]);
  },
)

More on this in responsive layouts.

Exercise 3: predict the size

Task. A Container(width: 300, height: 300, color: Colors.red) is the direct child of a Center inside a 200ร—200 SizedBox. How big is the red box?

Solution. It is 200ร—200. The SizedBox hands the Center tight 200ร—200 constraints, Center loosens them to 0..200, and the Container asks for 300 but must obey the constraints it received, so it is clamped to 200. To get 300 you must remove the parent's limit (for example with UnconstrainedBox, which will then overflow). The rule is "constraints go down, sizes go up" (constraints and layout).

JS Stand-in: size = request clamped to constraints

Press Run (or Ctrl + Enter) to see the console output here.

No output.

State

Exercise 4: a counter that survives rebuilds

Task. Make a counter with a button that increments, where the count stays when the parent rebuilds. Dispose anything you create.

Hint. State belongs in a State object, not in a field of the widget class.

Solution.

DART
class Counter extends StatefulWidget {
  const Counter({super.key});

  @override
  State<Counter> createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return FilledButton(
      onPressed: () => setState(() => _count++),
      child: Text('Tapped $_count times'),
    );
  }
}

Widgets are recreated on every rebuild; the State object is kept. See StatefulWidget and setState.

Exercise 5: share a counter between two widgets

Task. A Text in the app bar and a button in the body must show and change the same number, without a state package.

Solution. Lift the state to the closest common parent, or use a ValueNotifier:

DART
final counter = ValueNotifier<int>(0);

AppBar(
  title: ValueListenableBuilder<int>(
    valueListenable: counter,
    builder: (context, value, _) => Text('Count: $value'),
  ),
);

FilledButton(
  onPressed: () => counter.value++,
  child: const Text('Add'),
);

Only the title rebuilds when the value changes. Remember to call counter.dispose() if you create it inside a State. See lifting state up.

JS Stand-in: a ValueNotifier with two listeners

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Forms

Exercise 6: validate a sign-up form

Task. Two fields: email (must contain @) and password (at least 8 characters). The button validates both and shows the messages under the fields.

Solution.

DART
final _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(
    children: [
      TextFormField(
        decoration: const InputDecoration(labelText: 'Email'),
        keyboardType: TextInputType.emailAddress,
        validator: (v) => (v ?? '').contains('@') ? null : 'Enter a valid email',
      ),
      TextFormField(
        decoration: const InputDecoration(labelText: 'Password'),
        obscureText: true,
        validator: (v) => (v ?? '').length >= 8 ? null : 'Use at least 8 characters',
      ),
      FilledButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // save or send
          }
        },
        child: const Text('Sign up'),
      ),
    ],
  ),
)

A validator returns null for valid input and a message for invalid input. See forms and validation.

Exercise 7: show an error only after the user typed

Task. Instead of validating on button press, show errors while typing, but not before the user touched the field.

Solution. Set autovalidateMode: AutovalidateMode.onUserInteraction on the Form or on each TextFormField. The field stays quiet until its first change, then validates on every edit.

Exercise 8: pass data forward and a result back

Task. A list item opens a detail page. The detail page has a "Mark done" button that returns true to the list, which then crosses the item out.

Solution.

DART
// List page
Future<void> _open(Task task) async {
  final done = await Navigator.of(context).push<bool>(
    MaterialPageRoute(builder: (_) => DetailPage(task: task)),
  );
  if (!mounted) return;
  if (done == true) {
    setState(() => task.done = true);
  }
}

// Detail page
FilledButton(
  onPressed: () => Navigator.of(context).pop(true),
  child: const Text('Mark done'),
)

The mounted check is needed because the await created an async gap. If the user pressed the system back button, done is null. See Navigator and routes.

Exercise 9: protect a route

Task. With go_router, send anyone who is not logged in to /login when they open /account.

Solution.

DART
final router = GoRouter(
  redirect: (context, state) {
    final loggedIn = authState.isLoggedIn;
    final goingToAccount = state.matchedLocation == '/account';
    if (!loggedIn && goingToAccount) return '/login';
    return null; // no redirect
  },
  refreshListenable: authState,
  routes: [ /* ... */ ],
);

Returning null means "stay". refreshListenable re-runs the redirect when login state changes. See go_router.

Async

Exercise 10: loading, error and data

Task. Load a list from a function that may fail. Show a spinner while waiting, an error with a Retry button on failure, and the list on success. Do not refetch on every rebuild.

Hint. Create the Future once, in initState, not inside build.

Solution.

DART
class _UsersState extends State<Users> {
  late Future<List<String>> _future;

  @override
  void initState() {
    super.initState();
    _future = fetchUsers();
  }

  void _retry() => setState(() => _future = fetchUsers());

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<String>>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.connectionState != ConnectionState.done) {
          return const Center(child: CircularProgressIndicator());
        }
        if (snapshot.hasError) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('Failed: ${snapshot.error}'),
                TextButton(onPressed: _retry, child: const Text('Retry')),
              ],
            ),
          );
        }
        final users = snapshot.data!;
        return ListView(children: [for (final u in users) ListTile(title: Text(u))]);
      },
    );
  }
}

See FutureBuilder and StreamBuilder.

JS Stand-in: loading, error, data with retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 11: a search box that does not spam the server

Task. Call a search function only after the user stopped typing for 400 ms.

Solution. Debounce with a Timer:

DART
Timer? _debounce;

void _onChanged(String text) {
  _debounce?.cancel();
  _debounce = Timer(const Duration(milliseconds: 400), () => _search(text));
}

@override
void dispose() {
  _debounce?.cancel();
  super.dispose();
}

Cancelling in dispose prevents a callback from running after the widget is gone.

Exercise 12: find the bug

Task. This code sometimes throws "setState() called after dispose()". Fix it.

DART
Future<void> _load() async {
  final data = await api.fetch();
  setState(() => _data = data);
}

Solution. The user may leave the page while the request runs. Check mounted after the await:

DART
Future<void> _load() async {
  final data = await api.fetch();
  if (!mounted) return;
  setState(() => _data = data);
}

More traps like this are collected in common Flutter mistakes.

Where to go next

Pick the exercises you got wrong and rebuild them from a blank file. Then try a full app: the shopping app or the 2D game.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A Text inside a Row overflows. What usually fixes it?

    A Row gives children unbounded width; Expanded/Flexible gives the Text a bounded width so it can wrap or truncate.
  2. 2. Where should you create the Future you pass to FutureBuilder?

    Creating it in build refetches on every rebuild. Create it once and reuse it.
  3. 3. What must you check after an await before calling setState?

    The widget may have been removed during the wait, and setState after dispose throws.
  4. 4. What does a TextFormField validator return for valid input?

    null means no error; any string is shown as the error message.

Summary

  • Layout bugs come from constraints: give flexible children a bounded size with Expanded, Flexible or SizedBox.
  • State lives in State objects, notifiers or a state package, never in widget fields.
  • Validators return null when valid, and Form.validate() runs them all.
  • Navigation returns results through pop, and async code must check mounted.
  • Create futures once, show loading, error and data, and debounce noisy input.

Next: Common Flutter Mistakes and How to Fix Them