0
0
FlutterDebug / FixBeginner · 4 min read

How to Handle API Error in Flutter: Simple Guide

In Flutter, handle API errors by wrapping your network calls in try-catch blocks and checking the response.statusCode. Use http package to detect errors and show messages or retry options to users.
🔍

Why This Happens

API errors happen when the server returns an error status or the network call fails. If you don't check for these errors, your app may crash or show wrong data.

dart
import 'package:http/http.dart' as http;

Future<void> fetchData() async {
  final response = await http.get(Uri.parse('https://example.com/data'));
  // No error handling here
  print(response.body);
}
Output
If the server returns 404 or network fails, app crashes or shows unexpected behavior.
🔧

The Fix

Wrap your API call in a try-catch block to catch exceptions. Also, check response.statusCode to handle HTTP errors gracefully.

dart
import 'package:http/http.dart' as http;

Future<void> fetchData() async {
  try {
    final response = await http.get(Uri.parse('https://example.com/data'));
    if (response.statusCode == 200) {
      print('Data: ' + response.body);
    } else {
      print('Error: Server returned status ${response.statusCode}');
    }
  } catch (e) {
    print('Error: Could not fetch data - $e');
  }
}
Output
Data: { ... } OR Error: Server returned status 404 OR Error: Could not fetch data - SocketException
🛡️

Prevention

Always use try-catch around network calls and check HTTP status codes. Show user-friendly messages or retry options. Use packages like dio for advanced error handling and interceptors.

  • Validate URLs before requests
  • Use timeout to avoid hanging calls
  • Log errors for debugging
⚠️

Related Errors

Common related errors include SocketException for no internet, TimeoutException for slow responses, and FormatException when parsing bad JSON. Handle each with specific messages and recovery steps.

Key Takeaways

Always wrap API calls in try-catch to catch exceptions.
Check response.statusCode to handle HTTP errors properly.
Show clear messages to users when errors happen.
Use timeout and validate URLs to prevent hanging or bad requests.
Consider advanced packages like dio for better error handling.