在 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
就是设置构建页面的方法。