HTTP requests are crucial for web applications and APIs. In Dart, making HTTP requests is straightforward and powerful, allowing developers to interact with web services efficiently.
To make HTTP requests in Dart, you'll typically use the http
package. First, add it to your pubspec.yaml
file:
dependencies:
http: ^0.13.3
Then, import it in your Dart file:
import 'package:http/http.dart' as http;
GET requests are used to retrieve data from a server. Here's a simple example:
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
print(response.body);
} else {
print('Failed to load data');
}
}
POST requests are used to send data to a server. Here's how you can make a POST request:
Future<void> sendData() async {
final response = await http.post(
Uri.parse('https://api.example.com/submit'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': 'Foo',
'body': 'Bar',
}),
);
if (response.statusCode == 201) {
print('Data sent successfully');
} else {
print('Failed to send data');
}
}
When working with HTTP responses, it's important to handle different status codes and parse the response body appropriately. The Dart JSON handling capabilities come in handy here.
Robust error handling is crucial when making HTTP requests. Use try-catch blocks to handle exceptions:
Future<void> fetchDataSafely() async {
try {
final response = await http.get(Uri.parse('https://api.example.com/data'));
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}');
}
} catch (e) {
print('An error occurred: $e');
}
}
For more complex scenarios, explore these advanced concepts:
By mastering HTTP requests in Dart, you'll be well-equipped to build robust web applications and services. Remember to always consider security and performance when working with network operations.