当前位置: 首页> 文旅> 美景 > 网络搭建drc_广西智能网站建设企业_seo导航站_游戏行业seo整站优化

网络搭建drc_广西智能网站建设企业_seo导航站_游戏行业seo整站优化

时间:2025/8/23 8:04:34来源:https://blog.csdn.net/yikezhuixun/article/details/145894187 浏览次数:0次
网络搭建drc_广西智能网站建设企业_seo导航站_游戏行业seo整站优化

在这里插入图片描述

文章目录

      • 5. 网络请求
      • 核心库
        • 5.1 `http`
        • 5.2 `dio`
      • 必须掌握
        • 5.3 GET/POST 请求
        • 5.4 JSON 序列化与反序列化(`json_serializable`)
        • 5.5 错误处理与加载状态管理
      • 总结

5. 网络请求

网络请求是移动应用开发中不可或缺的一部分,Flutter 提供了多种方式来实现网络请求。掌握网络请求的核心库和技巧,可以帮助你高效地与后端 API 交互。


核心库

5.1 http
  • 特点:Flutter 官方提供的轻量级网络请求库。
  • 安装
    dependencies:http: ^0.13.3
    
5.2 dio
  • 特点:功能强大的第三方网络请求库,支持拦截器、文件上传、请求取消等高级功能。
  • 安装
    dependencies:dio: ^4.0.0
    

必须掌握

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}');}
    }
    

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

    1. 添加依赖

      dependencies:json_annotation: ^4.4.0dev_dependencies:build_runner: ^2.1.4json_serializable: ^6.1.4
      
    2. 定义模型类

      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);
      }
      
    3. 生成代码
      运行以下命令生成序列化代码:

      flutter pub run build_runner build
      
    4. 使用模型类

      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();}}
    }
    

总结

  • 核心库httpdio 是 Flutter 中最常用的网络请求库。
  • GET/POST 请求:掌握基本的请求方法。
  • JSON 序列化与反序列化:使用 json_serializable 简化 JSON 处理。
  • 错误处理与加载状态管理:确保应用的健壮性和用户体验。

掌握这些网络请求的核心技能后,你可以轻松实现与后端 API 的交互,并处理复杂的业务逻辑。


结束语
Flutter是一个由Google开发的开源UI工具包,它可以让您在不同平台上创建高质量、美观的应用程序,而无需编写大量平台特定的代码。我将学习和深入研究Flutter的方方面面。从基础知识到高级技巧,从UI设计到性能优化,欢饮关注一起讨论学习,共同进入Flutter的精彩世界!

关键字:网络搭建drc_广西智能网站建设企业_seo导航站_游戏行业seo整站优化

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: