Flutter_学习记录_网络请求的简单了解

devtools/2025/2/22 7:00:50/

在 Flutter 中,可以使用 http 包来发送请求。以下是一个完整的案例,展示如何通过 GET 请求获取数据并处理响应。

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 http 包的依赖:
在这里插入图片描述
然后运行 flutter pub get 来安装依赖。

2. 完整代码示例

以下是一个完整的 GET 请求示例,从一个公开 API 获取数据并显示结果:

import 'dart:convert';import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';class HttpDemo extends StatelessWidget {const HttpDemo({super.key});Widget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("HttpDemo"),),body: HttpDemoHome(),);}
}class HttpDemoHome extends StatefulWidget {const HttpDemoHome({super.key});State<HttpDemoHome> createState() => _HttpDemoHomeState();
}class _HttpDemoHomeState extends State<HttpDemoHome> {// 发起网络请求的方法Future<List<Post>> fetchPost() async {final url = Uri.parse('https://resources.ninghao.net/demo/posts.json');final response = await http.get(url);if (response.statusCode == 200) {final responseBody = json.decode(response.body);// 字典数组转模型数组List<Post> posts = responseBody["posts"].map<Post>((item) => Post.fromJson(item)).toList();return posts;} else {throw Exception("Fail to fetch post");}}Widget build(BuildContext context) {// FutureBuilder 构建页面return FutureBuilder(future: fetchPost(), builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {if (snapshot.connectionState == ConnectionState.waiting) {return Center(child: Text("Loading"),);}final data =  snapshot.data;if (data != null) {return ListView(children: data.map((post) {return ListTile(title: Text(post.title),subtitle: Text(post.author),leading: CircleAvatar(backgroundImage: NetworkImage(post.imageUrl),),);}).toList(),);} else {return Center(child: Text("暂无数据"));}});}
}// 新建数据模型 Post
class Post {final int id;final String title;final String description;final String author;final String imageUrl;Post({required this.id, required this.title, required this.description, required this.author, required this.imageUrl});// 字典转模型的方法Post.fromJson(Map json) : id = json["id"],title = json["title"],description = json["description"],author = json["author"],imageUrl = json["imageUrl"];// 模型转字典的方法Map toJson() => {"title": title,"description": description};
}

效果图如下:
在这里插入图片描述

3. 代码说明

(1) 发送异步 GET 请求

final url = Uri.parse('https://resources.ninghao.net/demo/posts.json');
final response = await http.get(url);
  • 使用 http.get 方法发送 GET 请求。
  • await 关键字确保等待请求完成后再继续执行。

(2) 检查响应状态码

if (response.statusCode == 200) {// 解析数据
} else {// 处理错误
}
  • 如果状态码为 200,表示请求成功。
  • 如果状态码不是 200,则打印错误信息。

(3) 解析 JSON 数据

final responseBody = json.decode(response.body);
// 字典数组转模型数组
List<Post> posts = responseBody["posts"].map<Post>((item) => Post.fromJson(item)).toList();

(4) 构建页面
FutureBuilder组件来设置页面,属性futher就是设置请求的方法, builder就是设置构建页面的方法。


http://www.ppmy.cn/devtools/160270.html

相关文章

SpringMVC新版本踩坑[已解决]

问题&#xff1a; 在使用最新版本springMVC做项目部署时&#xff0c;浏览器反复500&#xff0c;如下图&#xff1a; 异常描述&#xff1a; 类型异常报告 消息Request processing failed: java.lang.IllegalArgumentException: Name for argument of type [int] not specifie…

fastapi+vue实现按钮级别的权限控制

一、前端部分 1.1 自定义指令 import store from /store// 判断是否有权限 const hasPermission (value, el) > {// 检查是否配置了权限参数if (!Array.isArray(value) || value.length 0) {throw new Error(v-permission 需要配置权限&#xff0c;例如 v-permission&qu…

iOS App的启动与优化

App的启动流程 App启动分为冷启动和热启动 冷启动&#xff1a;从0开始启动App热启动&#xff1a;App已经在内存中&#xff0c;但是后台还挂着&#xff0c;再次点击图标启动App。 一般对App启动的优化都是针对冷启动。 App冷启动可分为三个阶段&#xff1a; dyld&#xff1a…

【R语言】主成分分析与因子分析

一、主成分分析 主成分分析&#xff08;Principal Component Analysis, PCA&#xff09;是一种常用的无监督数据降维技术&#xff0c;广泛应用于统计学、数据科学和机器学习等领域。它通过正交化线性变换将&#xff08;高维&#xff09;原始数据投影到一个新的坐标系&#xff…

oracle序列每天重置

在Oracle数据库中&#xff0c;若要实现序列每天重置&#xff0c;可以通过以下步骤进行操作&#xff1a; 一、创建序列 首先&#xff0c;需要创建一个序列。创建序列的SQL语句如下&#xff1a; CREATE SEQUENCE sequence_name START WITH 0 -- 或其他起始值 INCREMENT BY 1 CA…

【Vue】集成Antlr4

1.下载.g4文件 下载地址&#xff1a;https://download.csdn.net/download/qq_42454367/90396095 2.安装Antlr &#xff08;1&#xff09;使用以下命令安装依赖 pnpm install antlr4ng pnpm install --save-dev antlr4ng-cli&#xff08;2&#xff09;在package.json文件中配…

【产品资料】陀螺匠·企业助手v1.8 产品介绍

陀螺匠企业助手是一套采用Laravel 9框架结合Swoole高性能协程服务与Vue.js前端技术栈构建的新型智慧企业管理与运营系统。该系统深度融合了客户管理、项目管理、审批流程自动化以及低代码开发平台&#xff0c;旨在为企业提供一站式、数字化转型的全方位解决方案&#xff0c;助力…

调用DeepSeek API接口:实现智能数据挖掘与分析

调用DeepSeek API接口:实现智能数据挖掘与分析 在当今数据驱动的时代,企业和开发者越来越依赖高效的数据挖掘与分析工具来获取有价值的洞察。DeepSeek作为一款先进的智能数据挖掘平台,提供了强大的API接口,帮助用户轻松集成其功能到自己的应用中。本文将详细介绍如何调用D…