Flutter
statusCode
Handle errors with Response.statusCode.
What is statusCode?
response.statusCode is the HTTP status code returned by the server. 200 means success, 404 means not found, 500 means server error. You do error handling based on this code.
if (response.statusCode == 200) {
print(response.body);
} else {
print('error: ${response.statusCode}');
}
Codes other than 200 usually mean an error.
ok and error handling
By checking 200 with response.statusCode you catch a successful request. You can show different error messages for different codes.
if (response.statusCode == 200) {
// success
} else if (response.statusCode == 404) {
// not found
} else {
// server error
}
With this pattern you give meaningful feedback to the user.
Exercise Do error handling with statusCode
Write an async method veriCek. Make a request to 'https://api.example.com/veri' with http.get. If response.statusCode == 200, print 'gövde: ${response.body}'; if 404, print 'bulunamadı'; otherwise print 'hata: ${response.statusCode}'. In main, await the method.
Show example solution
import 'package:http/http.dart' as http;
Future<void> veriCek() async {
final response = await http.get(Uri.parse('https://api.example.com/veri'));
if (response.statusCode == 200) {
print('gövde: ${response.body}');
} else if (response.statusCode == 404) {
print('bulunamadı');
} else {
print('hata: ${response.statusCode}');
}
}
void main() async {
await veriCek();
}
Test yourself
-
What does response.statusCode 200 mean?
- Request succeeded
- Resource not found
- Unauthorized access
- Server error
Show answer
Request succeeded — The 200 HTTP status code indicates that the request succeeded; the server processed the request correctly.
-
Add statusCode check
final response = await http.get(uri);
if (response.____ == 200) {
print(response.body);
} else {
print('hata');
}
Show answer
final response = await http.get(uri);
if (response.statusCode == 200) {
print(response.body);
} else {
print('hata');
}
-
statusCode parts
- statusCode
- Property giving HTTP status code
- 200
- Code for successful request
- 404
- Code for resource not found
- 500
- Code for server error
Next lesson: Summary - http