Making network requests in Dart can be accomplished using the http package, which provides a simple way to perform HTTP requests. Here's a basic example of how to make a GET request:
Add the http package to your project:
First, you need to add the http package to your pubspec.yaml file:
dependencies:
http: ^0.13.3
Then, run pub get to install the package.
Import the http package:
In your Dart file, import the http package:
import 'package:http/http.dart' as http;
Make a GET request:
Use the http.get method to make a GET request. Here's an example:
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
print('Response data: ${response.body}');
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load posts');
}
}
Run the function:
Call the fetchData function to execute the network request:
void main() {
fetchData();
}
This example demonstrates how to make a simple GET request to fetch data from a REST API. The response is then printed to the console.
Here's an example of making a POST request:
Future<void> postData() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'title': 'foo',
'body': 'bar',
'userId': 1,
}),
);
if (response.statusCode == 201) {
print('Post created: ${response.body}');
} else {
throw Exception('Failed to create post');
}
}
For handling more complex network requests and backend services, consider using Tencent Cloud's API Gateway service. It provides a managed API service that allows you to create, publish, maintain, monitor, and secure APIs at any scale. This can be particularly useful for building scalable and reliable backend services for your Dart applications.