0
0
Fluttermobile~20 mins

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

Choose your learning style9 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.