https://i-blog.csdnimg.cn/img_convert/1aab26c143a3c682a27bb2de0c2ad8bf.jpeg" alt="在这里插入图片描述" />
文章目录
- 5. 网络请求
- 核心库
- 必须掌握
- 5.3 GET/POST 请求
- 5.4 JSON 序列化与反序列化(`json_serializable`)
- 5.5 错误处理与加载状态管理
- 总结
5. 网络请求
网络请求是移动应用开发中不可或缺的一部分,Flutter 提供了多种方式来实现网络请求。掌握网络请求的核心库和技巧,可以帮助你高效地与后端 API 交互。
核心库
http_10">5.1 http
dio_18">5.2 dio
必须掌握
5.3 GET/POST 请求
-
使用
http
库:import 'package:http/http.dart' as http;// GET 请求 Future<void> fetchData() async {final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));if (response.statusCode == 200) {print('Response data: ${response.body}');} else {print('Request failed with status: ${response.statusCode}');} }// POST 请求 Future<void> postData() async {final response = await http.post(Uri.parse('https://jsonplaceholder.typicode.com/posts'),body: {'title': 'foo', 'body': 'bar', 'userId': '1'},);if (response.statusCode == 201) {print('Response data: ${response.body}');} else {print('Request failed with status: ${response.statusCode}');} }
-
使用
dio
库:import 'package:dio/dio.dart';final dio = Dio();// GET 请求 Future<void> fetchData() async {final response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');if (response.statusCode == 200) {print('Response data: ${response.data}');} else {print('Request failed with status: ${response.statusCode}');} }// POST 请求 Future<void> postData() async {final response = await dio.post('https://jsonplaceholder.typicode.com/posts',data: {'title': 'foo', 'body': 'bar', 'userId': '1'},);if (response.statusCode == 201) {print('Response data: ${response.data}');} else {print('Request failed with status: ${response.statusCode}');} }
serializable_91">5.4 JSON 序列化与反序列化(json_serializable
)
-
手动序列化:
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'],);}Map<String, dynamic> toJson() {return {'userId': userId,'id': id,'title': title,'body': body,};} }
-
使用
json_serializable
:-
添加依赖:
dependencies:json_annotation: ^4.4.0dev_dependencies:build_runner: ^2.1.4json_serializable: ^6.1.4
-
定义模型类:
import 'package:json_annotation/json_annotation.dart';part 'post.g.dart';() 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) => _$PostFromJson(json);Map<String, dynamic> toJson() => _$PostToJson(this); }
-
生成代码:
运行以下命令生成序列化代码:flutter pub run build_runner build
-
使用模型类:
Future<Post> fetchPost() async {final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));if (response.statusCode == 200) {return Post.fromJson(jsonDecode(response.body));} else {throw Exception('Failed to load post');} }
-
5.5 错误处理与加载状态管理
-
错误处理:
Future<void> fetchData() async {try {final response = await dio.get('https://jsonplaceholder.typicode.com/posts/1');if (response.statusCode == 200) {print('Response data: ${response.data}');} else {throw Exception('Request failed with status: ${response.statusCode}');}} catch (e) {print('Error: $e');} }
-
加载状态管理:
class DataProvider with ChangeNotifier {bool isLoading = false;String data = '';Future<void> fetchData() async {isLoading = true;notifyListeners();try {final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));if (response.statusCode == 200) {data = response.body;} else {throw Exception('Request failed with status: ${response.statusCode}');}} catch (e) {print('Error: $e');} finally {isLoading = false;notifyListeners();}} }
总结
- 核心库:
http
和dio
是 Flutter 中最常用的网络请求库。 - GET/POST 请求:掌握基本的请求方法。
- JSON 序列化与反序列化:使用
json_serializable
简化 JSON 处理。 - 错误处理与加载状态管理:确保应用的健壮性和用户体验。
掌握这些网络请求的核心技能后,你可以轻松实现与后端 API 的交互,并处理复杂的业务逻辑。
结束语
Flutter是一个由Google开发的开源UI工具包,它可以让您在不同平台上创建高质量、美观的应用程序,而无需编写大量平台特定的代码。我将学习和深入研究Flutter的方方面面。从基础知识到高级技巧,从UI设计到性能优化,欢饮关注一起讨论学习,共同进入Flutter的精彩世界!