09-Flutter鸿蒙网络请求入门:HTTP数据请求和JSON模型封装 09. Flutter鸿蒙网络请求入门HTTP数据请求和JSON模型封装网络请求是业务项目最常见的能力之一。Flutter 鸿蒙项目中普通 HTTP 请求仍然可以在 Flutter 层完成添加依赖、封装模型、写请求服务、处理加载状态和错误状态即可。添加依赖dependencies:flutter:sdk:flutterhttp:^1.2.2执行flutter pub get定义模型classUser{finalint id;finalStringname;finalStringphone;constUser({requiredthis.id,requiredthis.name,requiredthis.phone,});factoryUser.fromJson(MapString,dynamicjson){returnUser(id:json[id]asint???0,name:json[name]asString???,phone:json[phone]asString???,);}MapString,dynamictoJson(){return{id:id,name:name,phone:phone,};}}封装服务importdart:convert;importpackage:http/http.dartashttp;classApiService{ApiService({http.Client?client}):_clientclient??http.Client();finalhttp.Client_client;staticconstStringbaseUrlhttps://example.com/api;FutureListUserfetchUsers()async{finaluriUri.parse($baseUrl/users);finalresponseawait_client.get(uri);if(response.statusCode!200){throwException(请求失败${response.statusCode});}finaldatajsonDecode(response.body);if(datais!List){throwException(接口返回格式不是数组);}returndata.map((item)User.fromJson(itemasMapString,dynamic)).toList();}FutureUsercreateUser(Stringname,Stringphone)async{finaluriUri.parse($baseUrl/users);finalresponseawait_client.post(uri,headers:{Content-Type:application/json},body:jsonEncode({name:name,phone:phone}),);if(response.statusCode!200response.statusCode!201){throwException(新增失败${response.statusCode});}returnUser.fromJson(jsonDecode(response.body)asMapString,dynamic);}}页面状态classUserListPageextendsStatefulWidget{constUserListPage({super.key});overrideStateUserListPagecreateState()_UserListPageState();}class_UserListPageStateextendsStateUserListPage{lateFutureListUser_future;overridevoidinitState(){super.initState();_futureApiService().fetchUsers();}Futurevoid_reload()async{setState((){_futureApiService().fetchUsers();});}overrideWidgetbuild(BuildContextcontext){returnFutureBuilderListUser(future:_future,builder:(context,snapshot){if(snapshot.connectionStateConnectionState.waiting){returnconstCenter(child:CircularProgressIndicator());}if(snapshot.hasError){returnCenter(child:Column(mainAxisSize:MainAxisSize.min,children:[Text(加载失败${snapshot.error}),constSizedBox(height:12),FilledButton(onPressed:_reload,child:constText(重试)),],),);}finaluserssnapshot.data??[];if(users.isEmpty){returnconstCenter(child:Text(暂无数据));}returnRefreshIndicator(onRefresh:_reload,child:ListView.builder(itemCount:users.length,itemBuilder:(_,index){finaluserusers[index];returnListTile(title:Text(user.name),subtitle:Text(user.phone),);},),);},);}}排错网络问题常见排查1. 接口地址是否能在浏览器或 Postman 打开 2. 设备是否有网络权限和网络连接 3. HTTP/HTTPS 是否符合服务端要求 4. JSON 顶层结构是对象还是数组 5. statusCode 是否被正确处理 6. 页面是否处理 loading、empty、error 三种状态请求层不要直接写在页面里页面里直接写http.get能跑但项目变大后很难维护。更好的做法是页面只关心状态网络细节放到 servicelib ├─ models │ └─ user.dart ├─ services │ └─ api_service.dart └─ pages └─ user_list_page.dart这样接口地址变化、请求头变化、错误处理变化时不需要翻每个页面。调试接口返回开发阶段可以临时打印响应debugPrint(statusCode:${response.statusCode});debugPrint(body:${response.body});正式提交前不要在日志里输出敏感信息比如 token、手机号、身份证、详细地址。网络日志要能辅助排错但不能泄露用户数据。不需要翻每个页面。

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/9/21 18:32:40
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/21 18:32:39
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/9/21 18:31:24
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/9/21 18:31:34
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/21 18:31:25
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/21 18:31:13

日新闻

周新闻