statusCode
- Flutter course
- Intermediate
- Lesson 49/99
- 4 min
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.
Practice 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.
Starter code
import 'package:http/http.dart' as http;
// veriCek: async metot ekle
void main() async {
// veriCek'i çağır
}Sample 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();
}Expected output
gövde: {"isim":"Ayşe"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does response.statusCode 200 mean?
- Request succeeded Correct answer
- Resource not found
- Unauthorized access
- Server error
Explanation: The 200 HTTP status code indicates that the request succeeded; the server processed the request correctly.
2 Add statusCode check
final response = await http.get(uri);
if (response.____ == 200) {
print(response.body);
} else {
print('hata');
}
final response = await http.get(uri);
if (response.statusCode == 200) {
print(response.body);
} else {
print('hata');
}
Explanation: If response.statusCode is 200, the request succeeded; based on this code, success or error is handled.
3 statusCode parts
| Term | Meaning |
|---|---|
statusCode |
Property giving HTTP status code |
200 |
Code for successful request |
404 |
Code for resource not found |
500 |
Code for server error |