从互联网获取数据
对于大多数应用来说,从互联网获取数据是必要的。幸运的是,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` 文件以添加互联网权限。
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
同样,如果你部署到 macOS,请编辑 `macos/Runner/DebugProfile.entitlements` 和 `macos/Runner/Release.entitlements` 文件以包含网络客户端授权。
<!-- Required to fetch data from the internet. -->
<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
- 使用 `dart:convert` 包将响应体转换为 JSON `Map`。
- 如果服务器返回状态码为 200 的 OK 响应,则使用 `fromJson()` 工厂方法将 JSON `Map` 转换为 `Album` 对象。
- 如果服务器没有返回状态码为 200 的 OK 响应,则抛出异常。(即使在服务器返回“404 Not Found”的情况下,也要抛出异常。不要返回 `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
widget。`FutureBuilder` widget 是 Flutter 自带的,可以轻松处理异步数据源。
你必须提供两个参数
- 你想要处理的 `Future`。在本例中,是 `fetchAlbum()` 函数返回的 `Future`。
- 一个 `builder` 函数,它根据 `Future` 的状态(加载中、成功或错误)告诉 Flutter 要渲染什么。
请注意,`snapshot.hasData` 仅在快照包含非空数据值时才返回 `true`。
因为 `fetchAlbum` 只能返回非空值,所以即使在服务器返回“404 Not Found”的情况下,该函数也应该抛出异常。抛出异常会将 `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();
},
),
),
),
);
}
}