通过互联网更新数据
如何使用 http 包通过互联网更新数据。
对于大多数应用而言,通过互联网更新数据是必不可少的。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` 对象。
使用模式匹配 (pattern matching) 转换 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()工厂方法将 JSONMap转换为Album对象。 - 如果服务器返回的状态码不是 200,则抛出一个异常。(即使在“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.');
}
}
太棒了!现在你已经拥有了一个可以更新相册标题的函数。
从互联网获取数据
#在更新数据之前,先从互联网获取数据。有关完整示例,请参阅 获取数据 (Fetch data) 指南。
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'),
),
],
);
点击更新数据 (Update Data) 按钮后,网络请求会将 TextField 中的数据作为 PUT 请求发送到服务器。_futureAlbum 变量将在下一步中使用。
5. 在屏幕上显示响应
#要在屏幕上显示数据,请使用 FutureBuilder 组件。FutureBuilder 组件随 Flutter 提供,可轻松处理异步数据源。你必须提供两个参数:
- 你想要处理的
Future。在本例中,即updateAlbum()函数返回的 future。 - 一个 `builder` 函数,它根据 `Future` 的状态(加载中、成功或错误)告诉 Flutter 要渲染什么。
请注意,snapshot.hasData 仅在 snapshot 包含非空数据值时返回 true。这就是为什么即使在“404 Not Found”服务器响应的情况下,updateAlbum 函数也应该抛出异常的原因。如果 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();
},
),
),
),
);
}
}