从互联网获取数据
从互联网获取数据对于大多数应用程序都是必要的。 幸运的是,Dart 和 Flutter 提供了诸如 http 包之类的工具来完成此类工作。
此食谱使用以下步骤:
- 添加
http包。 - 使用
http包发出网络请求。 - 将响应转换为自定义 Dart 对象。
- 使用 Flutter 获取和显示数据。
1. 添加 http 包
#http 包提供了从互联网获取数据的最简单方法。
要将 http 包添加为依赖项,请运行 flutter pub add:
flutter pub add http导入 http 包。
import 'package:http/http.dart' as http;如果您要部署到 Android,请编辑您的 AndroidManifest.xml 文件以添加 Internet 权限。
<!-- 获取互联网数据所需。 -->
<uses-permission android:name="android.permission.INTERNET" />同样,如果您要部署到 macOS,请编辑您的 macos/Runner/DebugProfile.entitlements 和 macos/Runner/Release.entitlements 文件以包含网络客户端授权。
<!-- 获取互联网数据所需。 -->
<key>com.apple.security.network.client</key>
<true/>2. 发出网络请求
#此食谱介绍了如何使用 http.get() 方法从 JSONPlaceholder 获取示例专辑。
Future<http.Response> fetchAlbum() {
return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}http.get() 方法返回一个包含 Response 的 Future。
Future是用于处理异步操作的核心 Dart 类。Future 对象表示将来某个时间可用的潜在值或错误。http.Response类包含从成功的 http 调用接收到的数据。
3. 将响应转换为自定义 Dart 对象
#虽然发出网络请求很容易,但使用原始 Future<http.Response> 并不方便。 为了简化您的工作,请将 http.Response 转换为 Dart 对象。
创建 Album 类
#首先,创建一个 Album 类,其中包含来自网络请求的数据。它包含一个工厂构造函数,该构造函数从 JSON 创建 Album。
使用 模式匹配 转换 JSON 只是一种选择。 有关更多信息,请参阅关于 JSON 和序列化 的完整文章。
class Album {
final int userId;
final int id;
final String title;
const Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
'userId': int userId,
'id': int id,
'title': String title,
} =>
Album(
userId: userId,
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}将 http.Response 转换为 Album
#现在,使用以下步骤更新 fetchAlbum() 函数以返回 Future<Album>:
- 使用
dart:convert包将响应主体转换为 JSONMap。 - 如果服务器确实返回了状态代码为 200 的 OK 响应,则使用
fromJson()工厂方法将 JSONMap转换为Album。 - 如果服务器没有返回状态代码为 200 的 OK 响应,则抛出异常。(即使在“404 未找到”服务器响应的情况下,也抛出异常。不要返回
null。这在检查下面的snapshot中的数据时很重要。)
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}太棒了! 现在您有了一个从互联网获取专辑的函数。
4. 获取数据
#在 initState() 或 didChangeDependencies() 方法中调用 fetchAlbum() 方法。
initState() 方法只调用一次,然后不再调用。 如果您希望根据 InheritedWidget 的更改重新加载 API,请将调用放入 didChangeDependencies() 方法中。 有关更多详细信息,请参阅 State。
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
// ···
}此 Future 用于下一步。
5. 显示数据
#要将数据显示在屏幕上,请使用 FutureBuilder 小部件。 FutureBuilder 小部件随 Flutter 提供,并简化了与异步数据源的工作。
您必须提供两个参数:
- 您要使用的
Future。 在本例中,是fetchAlbum()函数返回的 future。 - 一个
builder函数,它告诉 Flutter 根据Future的状态(加载、成功或错误)渲染什么内容。
请注意,只有当快照包含非空数据值时,snapshot.hasData 才返回 true。
因为 fetchAlbum 只能返回非空值,所以即使在“404 未找到”服务器响应的情况下,该函数也应该抛出异常。抛出异常会将 snapshot.hasError 设置为 true,这可用于显示错误消息。
否则,将显示微调器。
FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
)为什么在 initState() 中调用 fetchAlbum()?
#虽然很方便,但不建议将 API 调用放在 build() 方法中。
Flutter 每次需要更改视图中的任何内容时都会调用 build() 方法,这种情况出乎意料地频繁。如果将 fetchAlbum() 方法放在 build() 中,则会在每次重建时重复调用它,导致应用程序速度变慢。
将 fetchAlbum() 结果存储在状态变量中可确保 Future 只执行一次,然后将其缓存以进行后续重建。
测试
#有关如何测试此功能的信息,请参阅以下食谱:
完整示例
#import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
const Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{
'userId': int userId,
'id': int id,
'title': String title,
} =>
Album(
userId: userId,
id: id,
title: title,
),
_ => throw const FormatException('Failed to load album.'),
};
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}除非另有说明,否则本网站上的文档反映的是 Flutter 的最新稳定版本。页面最后更新于 2025-01-30。 查看源代码 或 报告问题。