Bird
Raised Fist0
Fluttermobile~20 mins

Why API calls fetch remote data in Flutter - Build It to Prove It

Choose your learning style10 modes available
Build: Remote Data Fetch Screen
This screen shows how an app fetches data from the internet using an API call and displays it.
Target UI
-------------------------
| Remote Data Fetch     |
|-----------------------|
| [Fetch Data Button]   |
|                       |
| Data will appear here |
|                       |
-------------------------
Add a button labeled 'Fetch Data'.
When tapped, it calls a fake API that returns a string after 2 seconds.
Show a loading indicator while waiting.
Display the fetched data below the button.
Handle errors by showing an error message.
Starter Code
Flutter
import 'package:flutter/material.dart';

class RemoteDataFetchScreen extends StatefulWidget {
  @override
  State<RemoteDataFetchScreen> createState() => _RemoteDataFetchScreenState();
}

class _RemoteDataFetchScreenState extends State<RemoteDataFetchScreen> {
  String? data;
  bool isLoading = false;
  String? error;

  Future<String> fetchFakeApi() async {
    // TODO: Simulate API call
    return 'Hello from API!';
  }

  void fetchData() async {
    // TODO: Implement fetching logic
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Remote Data Fetch')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                // TODO: Call fetchData
              },
              child: Text('Fetch Data'),
            ),
            SizedBox(height: 20),
            // TODO: Show loading, data or error
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
Flutter
import 'package:flutter/material.dart';

class RemoteDataFetchScreen extends StatefulWidget {
  @override
  State<RemoteDataFetchScreen> createState() => _RemoteDataFetchScreenState();
}

class _RemoteDataFetchScreenState extends State<RemoteDataFetchScreen> {
  String? data;
  bool isLoading = false;
  String? error;

  Future<String> fetchFakeApi() async {
    await Future.delayed(Duration(seconds: 2));
    // Simulate success or failure
    bool success = true; // Change to false to test error
    if (success) {
      return 'Hello from API!';
    } else {
      throw Exception('Failed to fetch data');
    }
  }

  void fetchData() async {
    setState(() {
      isLoading = true;
      error = null;
      data = null;
    });
    try {
      String result = await fetchFakeApi();
      setState(() {
        data = result;
      });
    } catch (e) {
      setState(() {
        error = e.toString();
      });
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Remote Data Fetch')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: fetchData,
              child: Text('Fetch Data'),
            ),
            SizedBox(height: 20),
            if (isLoading) CircularProgressIndicator(),
            if (data != null) Text(data!, style: TextStyle(fontSize: 18)),
            if (error != null) Text(error!, style: TextStyle(color: Colors.red)),
          ],
        ),
      ),
    );
  }
}

This screen shows a button labeled 'Fetch Data'. When the user taps it, the app simulates calling an API by waiting 2 seconds and then returning a string.

While waiting, a spinning loading circle appears to show the app is busy.

If the call succeeds, the returned text is shown below the button.

If there is an error, an error message is shown in red.

This example helps understand why apps use API calls: to get fresh data from somewhere else (like a server) instead of using only data inside the app.

Final Result
Completed Screen
-------------------------
| Remote Data Fetch     |
|-----------------------|
| [Fetch Data Button]   |
|                       |
| Loading... (spinner)  |
|                       |
| Hello from API!       |
-------------------------
Tap 'Fetch Data' button triggers loading spinner.
After 2 seconds, spinner disappears and 'Hello from API!' text appears.
If error occurs, error message appears in red instead.
Stretch Goal
Add a retry button that appears only when an error happens, allowing the user to try fetching data again.
💡 Hint
Show a TextButton with label 'Retry' below the error message that calls fetchData() when tapped.

Practice

(1/5)
1. Why do Flutter apps make API calls to fetch remote data?
easy
A. To speed up the app without network
B. To store data only on the device
C. To avoid using the internet
D. To get the latest information from the internet

Solution

  1. Step 1: Understand the purpose of API calls

    API calls connect to servers to get fresh data, like weather or news updates.
  2. Step 2: Compare options

    Only To get the latest information from the internet explains fetching latest info from the internet, others are incorrect.
  3. Final Answer:

    To get the latest information from the internet -> Option D
  4. Quick Check:

    API calls fetch fresh data = A [OK]
Hint: API calls get fresh data from servers [OK]
Common Mistakes:
  • Thinking API calls store data locally only
  • Believing API calls avoid internet use
  • Confusing API calls with offline storage
2. Which Flutter code snippet correctly starts an API call to fetch data asynchronously?
easy
A. var response = http.get(url);
B. var response = await http.get(Uri.parse(url));
C. var response = http.getSync(Uri.parse(url));
D. var response = http.fetch(url);

Solution

  1. Step 1: Identify correct async syntax

    In Flutter, http.get requires Uri and await for async calls.
  2. Step 2: Check each option

    var response = await http.get(Uri.parse(url)); uses await and Uri.parse correctly; others are invalid or wrong method names.
  3. Final Answer:

    var response = await http.get(Uri.parse(url)); -> Option B
  4. Quick Check:

    Async call with await and Uri.parse = A [OK]
Hint: Use await with http.get and Uri.parse for async calls [OK]
Common Mistakes:
  • Forgetting await keyword
  • Passing string URL directly without Uri.parse
  • Using non-existent http.getSync or http.fetch methods
3. What will this Flutter code print if the API returns JSON {"name":"Alice"}?
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
  var data = jsonDecode(response.body);
  print(data['name']);
} else {
  print('Error');
}
medium
A. Alice
B. Error
C. null
D. Exception

Solution

  1. Step 1: Check response status

    Status code 200 means success, so code enters the if block.
  2. Step 2: Parse JSON and print value

    jsonDecode parses JSON string; data['name'] is "Alice", so it prints Alice.
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Successful API call prints JSON name value = B [OK]
Hint: Status 200 means success; print JSON key value [OK]
Common Mistakes:
  • Ignoring statusCode check
  • Not parsing JSON before accessing keys
  • Expecting 'Error' when status is 200
4. Identify the error in this Flutter API call code:
var response = http.get(Uri.parse(url));
if (response.statusCode == 200) {
  print('Success');
}
medium
A. Incorrect statusCode property name
B. Wrong URL format
C. Missing await keyword for async call
D. No error, code is correct

Solution

  1. Step 1: Check async call usage

    http.get returns a Future; must use await to get response before accessing statusCode.
  2. Step 2: Identify missing await

    Code tries to access statusCode on Future, causing error; await is missing.
  3. Final Answer:

    Missing await keyword for async call -> Option C
  4. Quick Check:

    Async calls need await before accessing response = C [OK]
Hint: Always await async http.get before using response [OK]
Common Mistakes:
  • Accessing statusCode on Future without await
  • Assuming http.get is synchronous
  • Ignoring async nature of API calls
5. You want your Flutter app to show a list of user names from an API. Which approach correctly fetches and uses the remote data? A) Call API once, parse JSON list, and update UI with names asynchronously. B) Store user names locally and never update from API. C) Call API without checking status code and parse JSON directly. D) Use synchronous API call to block UI until data loads.
hard
A. Call API once, parse JSON list, and update UI with names asynchronously.
B. Store user names locally and never update from API.
C. Call API without checking status code and parse JSON directly.
D. Use synchronous API call to block UI until data loads.

Solution

  1. Step 1: Understand best practice for API data use

    Fetching data asynchronously and updating UI after parsing JSON is correct and user-friendly.
  2. Step 2: Evaluate other options

    B ignores fresh data, C risks errors by skipping status check, D blocks UI causing bad experience.
  3. Final Answer:

    Call API once, parse JSON list, and update UI with names asynchronously. -> Option A
  4. Quick Check:

    Async fetch, parse, update UI = A [OK]
Hint: Fetch async, check status, parse JSON, update UI [OK]
Common Mistakes:
  • Ignoring status code check before parsing
  • Blocking UI with synchronous calls
  • Not updating UI after data fetch
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard