当前位置: 首页 > news >正文

一周掌握Flutter开发--5、网络请求

在这里插入图片描述

文章目录

      • 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.0
      
      dev_dependencies:
        build_runner: ^2.1.4
        json_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的精彩世界!

相关文章:

  • 白帽黑客系列教程之Windows驱动开发(64位环境)入门教程(八)
  • 【机器学习】Logistic回归#1基于Scikit-Learn的简单Logistic回归
  • 1.✨Python练习1
  • 扩散模型基本概念
  • MyBatis TypeHandler 详解与实战:FastJson 实现字符串转 List
  • 大模型最新面试题系列:训练篇之数据处理与增强
  • vue3+ts+uniapp+unibest 微信小程序(第二篇)—— 图文详解自定义背景图页面布局、普通页面布局、分页表单页面布局
  • 服务 ‘Sql Server VSS writer‘ (SQLWriter) 在安装 LocalDB 时无法启动
  • java GUI编程实现一个计算器
  • 你对 Spring Cloud 的理解
  • 使用Python结合CoppeliaSim API来实现对UR5机械臂末端轨迹记录
  • 大模型RAG(检索增强)创新--SELF-RAG
  • Python运算符与表达式精讲:从基础到实战
  • 安科瑞基站能耗监控解决方案,全面监控、分析和优化基站能效
  • can数据记录仪在汽车路测中扮演着**关键角色*
  • VBco调控海马线粒体DNA甲基化
  • 山东大学计算机网络第一章习题解析
  • RealESRGAN技术详解(附代码)
  • DeepSeek 实用万能提问模板
  • 【多模态大模型】GLM-4-Voice端到端语音交互机器人VoiceAI
  • 美众议院通过法案将“墨西哥湾”更名为“美国湾”
  • 来论|建设性推进缅北和平进程——中国的智慧与担当
  • 中俄元首今年首次面对面会谈,达成哪些新的重要共识?
  • 范志毅跨界归来做青训,探索中国足球人才培养新模式
  • 巴基斯坦信德省首府卡拉奇发生爆炸
  • 《2025城市青年旅行消费报告》发布,解码青年出行特征