Flutter REST API使用教程
Flutter REST API使用教程
3 回复
建议先学HTTP请求库如http.dart,再结合JSON解析,最后用FutureBuilder展示数据。网上很多免费教程,推荐菜鸟教程。
更多关于Flutter REST API使用教程的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中使用REST API通常涉及以下几个步骤:
- 添加依赖:首先,你需要在
pubspec.yaml
文件中添加http
包的依赖,这是Flutter中用于进行HTTP请求的常用包。
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
- 导入包:在你的Dart文件中导入
http
包。
import 'package:http/http.dart' as http;
- 发送GET请求:使用
http.get
方法发送GET请求,并处理响应。
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
// 请求成功,解析数据
print('Response data: ${response.body}');
} else {
// 请求失败,处理错误
print('Failed to load data');
}
}
- 发送POST请求:使用
http.post
方法发送POST请求,并传递请求体。
Future<void> postData() async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': 'foo',
'body': 'bar',
'userId': '1',
}),
);
if (response.statusCode == 201) {
// 请求成功,解析数据
print('Response data: ${response.body}');
} else {
// 请求失败,处理错误
print('Failed to post data');
}
}
- 处理JSON数据:通常REST API返回的数据是JSON格式的,你可以使用
dart:convert
包来解析和编码JSON数据。
import 'dart:convert';
void parseJson(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
List<Post> posts = parsed.map<Post>((json) => Post.fromJson(json)).toList();
print('Number of posts: ${posts.length}');
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({required this.userId, required this.id, required this.title, required this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
通过这些步骤,你可以在Flutter应用中轻松地使用REST API进行数据交互。