Bird
Raised Fist0
Fluttermobile~20 mins

Error handling for network calls in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Network Error Handling Screen
This screen fetches data from a network and shows it. It handles errors by showing a friendly message and a retry button.
Target UI
┌───────────────────────────────┐
│ Network Data                  │
├───────────────────────────────┤
│ [Loading spinner]              │
│                               │
│                               │
│                               │
│                               │
│                               │
│                               │
└───────────────────────────────┘
Show a loading spinner while fetching data
Display fetched data as text when successful
Show an error message if the network call fails
Provide a Retry button to try fetching data again
Use try-catch to handle exceptions from the network call
Starter Code
Flutter
import 'package:flutter/material.dart';

class NetworkErrorHandlingScreen extends StatefulWidget {
  @override
  State<NetworkErrorHandlingScreen> createState() => _NetworkErrorHandlingScreenState();
}

class _NetworkErrorHandlingScreenState extends State<NetworkErrorHandlingScreen> {
  String? data;
  String? errorMessage;
  bool isLoading = false;

  Future<void> fetchData() async {
    setState(() {
      isLoading = true;
      errorMessage = null;
    });

    // TODO: Add network call with error handling here

    setState(() {
      isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Network Error Handling')),
      body: Center(
        child: // TODO: Add UI for loading, data, error
      ),
    );
  }
}
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

class NetworkErrorHandlingScreen extends StatefulWidget {
  @override
  State<NetworkErrorHandlingScreen> createState() => _NetworkErrorHandlingScreenState();
}

class _NetworkErrorHandlingScreenState extends State<NetworkErrorHandlingScreen> {
  String? data;
  String? errorMessage;
  bool isLoading = false;

  Future<void> fetchData() async {
    setState(() {
      isLoading = true;
      errorMessage = null;
      data = null;
    });

    try {
      // Simulate network delay
      await Future.delayed(Duration(seconds: 2));

      // Simulate success or failure randomly
      final success = DateTime.now().second % 2 == 0;

      if (success) {
        data = 'Fetched data from network at ${DateTime.now()}';
      } else {
        throw Exception('Network error occurred');
      }
    } catch (e) {
      errorMessage = e.toString();
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Network Error Handling')),
      body: Center(
        child: isLoading
            ? CircularProgressIndicator()
            : errorMessage != null
                ? Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text('Error: $errorMessage', style: TextStyle(color: Colors.red), textAlign: TextAlign.center),
                      SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: fetchData,
                        child: Text('Retry'),
                      ),
                    ],
                  )
                : Text(data ?? 'No data', textAlign: TextAlign.center),
      ),
    );
  }
}

This solution uses a StatefulWidget to manage the network call state.

Inside fetchData(), we use a try-catch block to simulate a network call that may succeed or fail.

While loading, a spinner is shown. If an error happens, an error message and a Retry button appear. On success, the fetched data text is displayed.

The Retry button calls fetchData() again to try fetching data.

This approach keeps the UI responsive and user-friendly by clearly showing loading, success, and error states.

Final Result
Completed Screen
┌───────────────────────────────┐
│ Network Error Handling        │
├───────────────────────────────┤
│                               │
│   [Loading spinner]            │
│                               │
│                               │
│                               │
│                               │
│                               │
└───────────────────────────────┘

-- OR --

┌───────────────────────────────┐
│ Network Error Handling        │
├───────────────────────────────┤
│                               │
│ Error: Exception: Network     │
│ error occurred                │
│                               │
│      [ Retry Button ]          │
│                               │
└───────────────────────────────┘

-- OR --

┌───────────────────────────────┐
│ Network Error Handling        │
├───────────────────────────────┤
│                               │
│ Fetched data from network at  │
│ 2024-06-01 12:34:56           │
│                               │
│                               │
│                               │
│                               │
└───────────────────────────────┘
When the screen loads, a spinner shows while fetching data.
If the fetch succeeds, the data text appears.
If the fetch fails, an error message and Retry button appear.
Tapping Retry tries fetching data again.
Stretch Goal
Add pull-to-refresh to reload the data by swiping down.
💡 Hint
Wrap the body in a RefreshIndicator widget and call fetchData() on refresh.

Practice

(1/5)
1. What is the main purpose of using try-catch blocks in Flutter network calls?
easy
A. To automatically retry the network call
B. To speed up the network request
C. To catch and handle errors that may occur during the network request
D. To format the response data

Solution

  1. Step 1: Understand the role of try-catch

    The try-catch block is used to catch exceptions or errors that happen during code execution, such as network failures.
  2. Step 2: Apply this to network calls

    Network calls can fail due to no internet or server issues, so try-catch helps handle these errors gracefully.
  3. Final Answer:

    To catch and handle errors that may occur during the network request -> Option C
  4. Quick Check:

    try-catch handles errors = A [OK]
Hint: Try-catch is for catching errors during network calls [OK]
Common Mistakes:
  • Thinking try-catch speeds up requests
  • Assuming try-catch retries calls automatically
  • Using try-catch to format data
2. Which of the following is the correct syntax to catch exceptions in a Flutter network call?
easy
A. try { await http.get(url); } catch (e) { print(e); }
B. try await http.get(url) catch (e) { print(e); }
C. catch (e) { await http.get(url); }
D. http.get(url).try { } catch (e) { print(e); }

Solution

  1. Step 1: Recall correct try-catch syntax in Dart

    The try block wraps the code that might throw an error, followed by catch to handle it.
  2. Step 2: Check each option

    try { await http.get(url); } catch (e) { print(e); } correctly uses try { await ... } catch (e) { ... } syntax. Others have syntax errors or misplaced keywords.
  3. Final Answer:

    try { await http.get(url); } catch (e) { print(e); } -> Option A
  4. Quick Check:

    Correct try-catch syntax = B [OK]
Hint: Try-catch wraps code in braces with catch after [OK]
Common Mistakes:
  • Omitting braces {} around try block
  • Placing await outside try block
  • Misplacing catch block
3. Given this code snippet, what will be printed if the server returns status code 404?
try {
  final response = await http.get(Uri.parse('https://example.com/data'));
  if (response.statusCode == 200) {
    print('Success');
  } else {
    print('Failed with status: ' + response.statusCode.toString());
  }
} catch (e) {
  print('Error: ' + e.toString());
}
medium
A. Success
B. No output
C. Error: Exception message
D. Failed with status: 404

Solution

  1. Step 1: Analyze the response status code check

    The code checks if statusCode is 200 to print 'Success', else prints failure with status code.
  2. Step 2: Apply given status code 404

    Since 404 is not 200, the else block runs printing 'Failed with status: 404'.
  3. Final Answer:

    Failed with status: 404 -> Option D
  4. Quick Check:

    Non-200 status prints failure message = D [OK]
Hint: Non-200 status triggers else block message [OK]
Common Mistakes:
  • Assuming 404 triggers catch block
  • Expecting 'Success' for any status
  • Ignoring else block
4. Identify the error in this Flutter network call code:
try {
  final response = await http.get('https://example.com');
  if (response.statusCode == 200) {
    print('Data loaded');
  }
} catch (e) {
  print('Error: ' + e.toString());
}
medium
A. Missing await keyword before http.get
B. http.get requires a Uri object, not a String
C. No catch block to handle errors
D. No print statement inside try block

Solution

  1. Step 1: Check http.get parameter type

    In Flutter, http.get expects a Uri object, not a plain String.
  2. Step 2: Identify the error in the code

    The code passes a String directly, which causes a type error at runtime.
  3. Final Answer:

    http.get requires a Uri object, not a String -> Option B
  4. Quick Check:

    http.get needs Uri, not String = A [OK]
Hint: Use Uri.parse() to convert String to Uri [OK]
Common Mistakes:
  • Passing URL as String directly to http.get
  • Forgetting to use Uri.parse()
  • Assuming catch block is missing
5. You want to show a friendly message to users when a network call fails due to no internet. Which approach is best in Flutter?
hard
A. Use try-catch to catch exceptions and show a SnackBar with a friendly message
B. Ignore errors and let the app crash to detect bugs
C. Only check response.statusCode without try-catch
D. Use a timer to retry the call without informing the user

Solution

  1. Step 1: Understand user experience on network failure

    Users should see a clear message when network fails, not a crash or silent failure.
  2. Step 2: Use try-catch and UI feedback

    try-catch catches exceptions like no internet, and showing a SnackBar informs users kindly.
  3. Final Answer:

    Use try-catch to catch exceptions and show a SnackBar with a friendly message -> Option A
  4. Quick Check:

    Catch errors + show message = C [OK]
Hint: Catch errors and notify user with SnackBar [OK]
Common Mistakes:
  • Ignoring errors causing app crashes
  • Not informing users about network issues
  • Relying only on statusCode without catching exceptions
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