Thuta Learning
Flutter
ExercisesMobile DevelopmentBeginner

Exercise: Navigation, Async & API Challenge

FlutterLesson 3140 min

What you'll walk away with

  • Explain the widget, state, and lifecycle behavior of Exercise: Navigation, Async & API Challenge
  • Test responsive, failure, and interaction cases
  • Write accessible, testable, and performant Flutter

Explain it simply

Exercise: Navigation, Async & API Challenge, in plain language

This lesson steps things up from the first exercise lesson — the tasks require combining Navigator, named routes, FutureBuilder, and the http package all at once. In real app development, passing and returning data as you move between screens, and handling a network call's loading/error state in the UI, both matter a lot. Working through these tasks yourself will help lock in the concepts you saw back in the mini-project lesson. Each task comes with a code skeleton as a sample, but you'll need to fill in the full logic yourself.

Problem → Why → Solution

The problem — why this concept matters

Not awaiting pushNamed() and using the result right away, which ends up being null

A common mistake

Skipping the snapshot.hasError check in FutureBuilder, assuming data is always there, and using snapshot.data! directly — which crashes the app the moment a network error happens

Core concept — understand how it works

Build Exercise: Navigation, Async & API Challenge in feature slices and verify it with unit, widget, and integration tests. Use measurable acceptance criteria for build modes, frame time, rebuild count, accessibility, and deployment configuration.

Mental model
  1. requirement
  2. reason and implement
  3. test and explain

Explain the widget, state, and lifecycle behavior of Exercise: Navigation, Async & API Challenge

Core syntax or pattern

dart
// Task 1 & 2 skeleton
class DetailScreen extends StatelessWidget {
  final String itemName;
  const DetailScreen({super.key, required this.itemName});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(itemName)),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          child: const Text('Confirm'),
        ),
      ),
    );
  }
}

// Home screen call
final result = await Navigator.pushNamed(context, '/detail', arguments: 'Item A');
if (result == true) {
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text('Confirmed!')),
  );
}

// Task 3 skeleton
Future<List<dynamic>> fetchUsers() async {
  final res = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
  if (res.statusCode == 200) {
    return jsonDecode(res.body);
  } else {
    throw Exception('Failed to load users');
  }
}

// FutureBuilder<List<dynamic>>(
//   future: fetchUsers(),
//   builder: (context, snapshot) {
//     if (snapshot.connectionState == ConnectionState.waiting) {
//       return const CircularProgressIndicator();
//     } else if (snapshot.hasError) {
//       return Text('Error: ${snapshot.error}');
//     } else {
//       final users = snapshot.data!;
//       return ListView.builder(...);
//     }
//   },
// )

Build Exercise: Navigation, Async & API Challenge in feature slices and verify it with unit, widget, and integration tests. Use measurable acceptance criteria for build modes, frame time, rebuild count, accessibility, and deployment configuration.

Read the code step by step

  1. requirement// Task 1 & 2 skeleton

    This lesson steps things up from the first exercise lesson — the tasks require combining Navigator, named routes, FutureBuilder, and the http package all at once. In real app development, passing and returning data as you move between screens, and handling a network call's loading/error state in the UI, both matter a lot. Working through these tasks yourself will help lock in the concepts you saw back in the mini-project lesson. Each task comes with a code skeleton as a sample, but you'll need to fill in the full logic yourself.

  2. reason and implement);

    Build Exercise: Navigation, Async & API Challenge in feature slices and verify it with unit, widget, and integration tests. Use measurable acceptance criteria for build modes, frame time, rebuild count, accessibility, and deployment configuration.

  3. test and explain// )

    Run and test an original Exercise: Navigation, Async & API Challenge example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Execution flow
  1. requirement
  2. reason and implement
  3. test and explain

Success

Explain the widget, state, and lifecycle behavior of Exercise: Navigation, Async & API Challenge

Failure

Not awaiting pushNamed() and using the result right away, which ends up being null

Quick, think about this for a second

This lesson steps things up from the first exercise lesson — the tasks require combining Navigator, named routes, FutureBuilder, and the http package all at once. In real app development, passing and returning data as you move between screens, and handling a network call's loading/error state in the UI, both matter a lot. Working through these tasks yourself will help lock in the concepts you saw back in the mini-project lesson. Each task comes with a code skeleton as a sample, but you'll need to fill in the full logic yourself.

Exercises

Task 1: Using named routes ('/', '/detail'), make tapping a ListView item on the Home screen navigate to the Detail screen via Navigator.pushNamed(), passing along the item name as an argument and displaying it on the Detail screen. Task 2: Add a 'Confirm' button on the Detail screen that sends a result back to the Home screen with Navigator.pop(context, true); on the Home screen, receive that result with await Navigator.pushNamed() and show a SnackBar. Task 3: Use the http package to fetch a user list from a public API (e.g. jsonplaceholder.typicode.com/users) with an async function, and use FutureBuilder to show a CircularProgressIndicator while loading, a ListView.builder on success, and an error Text on failure.

Code Example

dart
// Task 1 & 2 skeleton
class DetailScreen extends StatelessWidget {
  final String itemName;
  const DetailScreen({super.key, required this.itemName});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(itemName)),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          child: const Text('Confirm'),
        ),
      ),
    );
  }
}

// Home screen call
final result = await Navigator.pushNamed(context, '/detail', arguments: 'Item A');
if (result == true) {
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text('Confirmed!')),
  );
}

// Task 3 skeleton
Future<List<dynamic>> fetchUsers() async {
  final res = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
  if (res.statusCode == 200) {
    return jsonDecode(res.body);
  } else {
    throw Exception('Failed to load users');
  }
}

// FutureBuilder<List<dynamic>>(
//   future: fetchUsers(),
//   builder: (context, snapshot) {
//     if (snapshot.connectionState == ConnectionState.waiting) {
//       return const CircularProgressIndicator();
//     } else if (snapshot.hasError) {
//       return Text('Error: ${snapshot.error}');
//     } else {
//       final users = snapshot.data!;
//       return ListView.builder(...);
//     }
//   },
// )
You should see
Tapping an item on the Home screen takes you to the Detail screen with the argument passed along; pressing Confirm brings up a SnackBar back on Home; and the user list screen goes from a loading indicator to showing the real API data list.

5-Minute Challenge

Once you've finished Task 3, add a RefreshIndicator for pull-to-refresh so that swiping down on the screen calls fetchUsers() again (5 minutes).

A Quick Word of Caution

Public APIs often have rate limits, so instead of letting FutureBuilder fire off a new API call on every widget rebuild, store the Future in a state variable during initState() and reuse it from there.

Real-world usage

How to apply it in a real project

Run and test an original Exercise: Navigation, Async & API Challenge example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Mini challenge

Build it yourself

Run and test an original Exercise: Navigation, Async & API Challenge example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

  • Rebuild the example without copying it
  • Test a normal input and an edge case
  • Predict the compiler or output result before running it
dart
// Task 1 & 2 skeleton
class DetailScreen extends StatelessWidget {
  final String itemName;
  const DetailScreen({super.key, required this.itemName});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(itemName)),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context, true);
          },
          child: const Text('Confirm'),
        ),
      ),
    );
  }
}

// Home screen call
final result = await Navigator.pushNamed(context, '/detail', arguments: 'Item A');
if (result == true) {
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text('Confirmed!')),
  );
}

// Task 3 skeleton
Future<List<dynamic>> fetchUsers() async {
  final res = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
  if (res.statusCode == 200) {
    return jsonDecode(res.body);
  } else {
    throw Exception('Failed to load users');
  }
}

// FutureBuilder<List<dynamic>>(
//   future: fetchUsers(),
//   builder: (context, snapshot) {
//     if (snapshot.connectionState == ConnectionState.waiting) {
//       return const CircularProgressIndicator();
//     } else if (snapshot.hasError) {
//       return Text('Error: ${snapshot.error}');
//     } else {
//       final users = snapshot.data!;
//       return ListView.builder(...);
//     }
//   },
// )

Expected: Explain the widget, state, and lifecycle behavior of Exercise: Navigation, Async & API Challenge

Show hint

Run and test an original Exercise: Navigation, Async & API Challenge example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Quick quiz 1 / 3

What best describes the core idea of Exercise: Navigation, Async & API Challenge?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

What to remember

  • requirement → reason and implement → test and explain
  • Build Exercise: Navigation, Async & API Challenge in feature slices and verify it with unit, widget, and integration tests. Use measurable acceptance criteria for build modes, frame time, rebuild count, accessibility, and deployment configuration.
  • Not awaiting pushNamed() and using the result right away, which ends up being null
  • Run and test an original Exercise: Navigation, Async & API Challenge example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

Flutter documentation — Flutter

Easy traps

  • Not awaiting pushNamed() and using the result right away, which ends up being null
  • Skipping the snapshot.hasError check in FutureBuilder, assuming data is always there, and using snapshot.data! directly — which crashes the app the moment a network error happens
  • Assuming one screen's sample output proves every rebuild, overflow, accessibility, async, and lifecycle path.

Hands-on Exercise

Run and test an original Exercise: Navigation, Async & API Challenge example with small and large screens, text scaling, empty/loading/error states, rapid interaction, navigation restoration, and disposal cases. Use flutter analyze, widget tests, and profile mode where relevant.

You'll know it worked when: Tapping an item on the Home screen takes you to the Detail screen with the argument passed along; pressing Confirm brings up a SnackBar back on Home; and the user list screen goes from a loading indicator to showing the real API data list.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Exercise: Navigation, Async & API Challenge | Thuta Learning