在Flutter中进行网络请求可以使用Dart的http
库。下面是一些常用的Http请求方法:
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
var response = await http.get('https://jsonplaceholder.typicode.com/posts/1');
if (response.statusCode == 200) {
print(response.body);
} else {
print('Failed to fetch data');
}
}
import 'package:http/http.dart' as http;
Future<void> createPost() async {
var url = 'https://jsonplaceholder.typicode.com/posts';
var response = await http.post(url, body: {'title': 'foo', 'body': 'bar', 'userId': '1'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
import 'package:http/http.dart' as http;
Future<void> updatePost() async {
var url = 'https://jsonplaceholder.typicode.com/posts/1';
var response = await http.put(url, body: {'title': 'foo', 'body': 'bar', 'userId': '1'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}
import 'package:http/http.dart' as http;
Future<void> deletePost() async {
var url = 'https://jsonplaceholder.typicode.com/posts/1';
var response = await http.delete(url);
if (response.statusCode == 200) {
print('Post deleted successfully');
} else {
print('Failed to delete post');
}
}
以上是一些常用的Http请求方法,你可以根据实际需求选择合适的方法来发起网络请求。记得在Flutter项目中添加http
库的依赖:
dependencies:
http: ^0.13.3
希望这个简单的教程能帮助你开始使用Http请求在Flutter中进行网络通信。