通过互联网更新数据
大多数应用都需要通过互联网更新数据。`http` 包可以帮助你实现这一点!
本示例将采取以下步骤
- 添加 `http` 包。
- 使用 `http` 包通过互联网更新数据。
- 将响应转换为自定义 Dart 对象。
- 从互联网获取数据。
- 根据用户输入更新现有 `title`。
- 更新并在屏幕上显示响应。
1. 添加 `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` 包通过互联网更新数据
#本指南介绍了如何使用 `http.put()` 方法将专辑标题更新到 JSONPlaceholder。
Future<http.Response> updateAlbum(String title) {
return http.put(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{'title': title}),
);
}
`http.put()` 方法返回一个包含 `Response` 的 `Future`。
- `Future` 是 Dart 中用于处理异步操作的核心类。`Future` 对象表示将来某个时候可能可用或出现的返回值或错误。
- `http.Response` 类包含成功 http 调用接收到的数据。
- `updateAlbum()` 方法接受一个参数 `title`,该参数被发送到服务器以更新 `Album`。
3. 将 `http.Response` 转换为自定义 Dart 对象
#虽然进行网络请求很简单,但直接处理原始的 `Future<http.Response>` 并不是很方便。为了简化开发,请将 `http.Response` 转换为 Dart 对象。
创建 Album 类
#首先,创建一个 `Album` 类来包含网络请求中的数据。它包含一个工厂构造函数,用于从 JSON 创建 `Album` 对象。
使用 模式匹配 转换 JSON 只是其中一种方法。更多信息,请参阅关于 JSON 和序列化 的完整文章。
class Album {
final int id;
final String title;
const Album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'id': int id, 'title': String title} => Album(id: id, title: title),
_ => throw const FormatException('Failed to load album.'),
};
}
}
将 `http.Response` 转换为 `Album` 对象
#现在,按照以下步骤更新 `updateAlbum()` 函数以返回一个 `Future<Album>`
- 使用 `dart:convert` 包将响应体转换为 JSON `Map`。
- 如果服务器返回状态码为 200 的 `UPDATED` 响应,则使用 `fromJson()` 工厂方法将 JSON `Map` 转换为 `Album` 对象。
- 如果服务器没有返回状态码为 200 的 `UPDATED` 响应,则抛出异常。(即使在“404 Not Found”服务器响应的情况下,也要抛出异常。不要返回 `null`。这在检查 `snapshot` 中的数据时很重要,如下所示。)
Future<Album> updateAlbum(String title) async {
final response = await http.put(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{'title': title}),
);
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 update album.');
}
}
太棒了!现在你有一个可以更新专辑标题的函数了。
从互联网获取数据
#在更新数据之前,请先从互联网获取数据。有关完整示例,请参阅获取数据指南。
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');
}
}
理想情况下,你会在 `initState` 期间使用此方法设置 `_futureAlbum` 以从互联网获取数据。
4. 根据用户输入更新现有标题
#创建一个 `TextField` 用于输入标题,以及一个 `ElevatedButton` 用于在服务器上更新数据。另外,定义一个 `TextEditingController` 来读取 `TextField` 中的用户输入。
当 `ElevatedButton` 被按下时,`_futureAlbum` 将设置为 `updateAlbum()` 方法返回的值。
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8),
child: TextField(
controller: _controller,
decoration: const InputDecoration(hintText: 'Enter Title'),
),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
child: const Text('Update Data'),
),
],
);
按下更新数据按钮时,网络请求将 `TextField` 中的数据作为 `PUT` 请求发送到服务器。`_futureAlbum` 变量将在下一步中使用。
5. 在屏幕上显示响应
#要在屏幕上显示数据,请使用 `FutureBuilder` 组件。`FutureBuilder` 组件随 Flutter 提供,可以轻松处理异步数据源。你必须提供两个参数:
- 要处理的 `Future`。在这种情况下,是 `updateAlbum()` 函数返回的 future。
- 一个 `builder` 函数,它根据 `Future` 的状态(加载中、成功或错误)告诉 Flutter 要渲染什么。
请注意,`snapshot.hasData` 仅当快照包含非空数据值时才返回 `true`。这就是为什么 `updateAlbum` 函数即使在“404 Not Found”服务器响应的情况下也应该抛出异常的原因。如果 `updateAlbum` 返回 `null`,那么 `CircularProgressIndicator` 将无限期显示。
FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
);
完整示例
#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');
}
}
Future<Album> updateAlbum(String title) async {
final response = await http.put(
Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{'title': title}),
);
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 update album.');
}
}
class Album {
final int id;
final String title;
const Album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'id': int id, 'title': String title} => Album(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() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
final TextEditingController _controller = TextEditingController();
late Future<Album> _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Update Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(title: const Text('Update Data Example')),
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8),
child: FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(snapshot.data!.title),
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter Title',
),
),
ElevatedButton(
onPressed: () {
setState(() {
_futureAlbum = updateAlbum(_controller.text);
});
},
child: const Text('Update Data'),
),
],
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}