Network calls can fail for many reasons like no internet or server problems. Handling errors helps your app stay friendly and avoid crashes.
Error handling for network calls in Flutter
try { final response = await http.get(Uri.parse('https://example.com')); if (response.statusCode == 200) { // process data } else { // handle server error } } catch (e) { // handle network or parsing error }
Use try-catch to catch errors that happen during the network call.
Check response.statusCode to see if the server responded successfully.
try { final response = await http.get(Uri.parse('https://api.example.com/data')); if (response.statusCode == 200) { print('Data loaded'); } else { print('Server error: ' + response.statusCode.toString()); } } catch (e) { print('Network error: ' + e.toString()); }
try { final response = await http.get(Uri.parse('https://badurl')); // This will throw and go to catch } catch (e) { print('Failed to connect: ' + e.toString()); }
This Flutter app shows a message on screen. When you tap the button, it tries to load data from the internet. It updates the message to show loading, success, server error, or network error.
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(home: NetworkExample()); } } class NetworkExample extends StatefulWidget { const NetworkExample({super.key}); @override State<NetworkExample> createState() => _NetworkExampleState(); } class _NetworkExampleState extends State<NetworkExample> { String _message = 'Press button to load data'; Future<void> _loadData() async { setState(() { _message = 'Loading...'; }); try { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1')); if (response.statusCode == 200) { setState(() { _message = 'Data loaded successfully!'; }); } else { setState(() { _message = 'Server error: ${response.statusCode}'; }); } } catch (e) { setState(() { _message = 'Network error: $e'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Network Error Handling')), body: Center(child: Text(_message, textAlign: TextAlign.center)), floatingActionButton: FloatingActionButton( onPressed: _loadData, tooltip: 'Load Data', child: const Icon(Icons.cloud_download), ), ); } }
Always update UI inside setState() when using StatefulWidget.
Network errors include no internet, timeout, or bad URLs.
Server errors mean the server responded but with an error code like 404 or 500.
Use try-catch to handle errors during network calls.
Check response.statusCode to handle server responses properly.
Show friendly messages to users when errors happen.
Practice
try-catch blocks in Flutter network calls?Solution
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.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.Final Answer:
To catch and handle errors that may occur during the network request -> Option CQuick Check:
try-catch handles errors = A [OK]
- Thinking try-catch speeds up requests
- Assuming try-catch retries calls automatically
- Using try-catch to format data
Solution
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.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.Final Answer:
try { await http.get(url); } catch (e) { print(e); } -> Option AQuick Check:
Correct try-catch syntax = B [OK]
- Omitting braces {} around try block
- Placing await outside try block
- Misplacing catch block
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());
}Solution
Step 1: Analyze the response status code check
The code checks if statusCode is 200 to print 'Success', else prints failure with status code.Step 2: Apply given status code 404
Since 404 is not 200, the else block runs printing 'Failed with status: 404'.Final Answer:
Failed with status: 404 -> Option DQuick Check:
Non-200 status prints failure message = D [OK]
- Assuming 404 triggers catch block
- Expecting 'Success' for any status
- Ignoring else block
try {
final response = await http.get('https://example.com');
if (response.statusCode == 200) {
print('Data loaded');
}
} catch (e) {
print('Error: ' + e.toString());
}Solution
Step 1: Check http.get parameter type
In Flutter, http.get expects a Uri object, not a plain String.Step 2: Identify the error in the code
The code passes a String directly, which causes a type error at runtime.Final Answer:
http.get requires a Uri object, not a String -> Option BQuick Check:
http.get needs Uri, not String = A [OK]
- Passing URL as String directly to http.get
- Forgetting to use Uri.parse()
- Assuming catch block is missing
Solution
Step 1: Understand user experience on network failure
Users should see a clear message when network fails, not a crash or silent failure.Step 2: Use try-catch and UI feedback
try-catch catches exceptions like no internet, and showing a SnackBar informs users kindly.Final Answer:
Use try-catch to catch exceptions and show a SnackBar with a friendly message -> Option AQuick Check:
Catch errors + show message = C [OK]
- Ignoring errors causing app crashes
- Not informing users about network issues
- Relying only on statusCode without catching exceptions
Ready to prove it?
Pass the test and this pattern moves unknown
