删除互联网上的数据
如何使用 http 包在互联网上删除数据。
本教程介绍如何使用 http 包通过互联网删除数据。
本示例将采取以下步骤
- 添加 `http` 包。
- 在服务器上删除数据。
- 更新屏幕。
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.delete() 方法从 JSONPlaceholder 删除专辑。请注意,这需要您想要删除的专辑的 id。 对于此示例,请使用您已经知道的内容,例如 id = 1。
Future<http.Response> deleteAlbum(String id) async {
final http.Response response = await http.delete(
Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
return response;
}
http.delete() 方法返回一个包含 Response 的 Future。
-
Future是 Dart 中用于处理异步操作的核心类。 Future 对象表示将来某个时间点可用或可能发生的错误。 - `http.Response` 类包含成功 http 调用接收到的数据。
deleteAlbum()方法接受一个id参数,该参数用于标识要从服务器删除的数据。
3. 更新屏幕
#为了检查数据是否已删除,首先使用 http.get() 方法从 JSONPlaceholder 获取数据,并在屏幕上显示它。(请参阅 获取数据 教程以获取完整示例。)您现在应该有一个 删除数据 按钮,按下该按钮时会调用 deleteAlbum() 方法。
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(snapshot.data?.title ?? 'Deleted'),
ElevatedButton(
child: const Text('Delete Data'),
onPressed: () {
setState(() {
_futureAlbum = deleteAlbum(
snapshot.data!.id.toString(),
);
});
},
),
],
);
现在,当您单击 删除数据 按钮时,将调用 deleteAlbum() 方法,并且您传递的 id 是您从互联网检索到的数据的 id。 这意味着您将删除从互联网获取的相同数据。
从 deleteAlbum() 方法返回响应
#一旦发出删除请求,您可以从 deleteAlbum() 方法返回响应,以通知我们的屏幕数据已被删除。
Future<Album> deleteAlbum(String id) async {
final http.Response response = await http.delete(
Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then return an empty Album. After deleting,
// you'll get an empty JSON `{}` response.
// Don't return `null`, otherwise `snapshot.hasData`
// will always return false on `FutureBuilder`.
return Album.empty();
} else {
// If the server did not return a "200 OK response",
// then throw an exception.
throw Exception('Failed to delete album.');
}
}
FutureBuilder() 现在在收到响应时重建。 由于响应在请求成功的情况下在其主体中没有任何数据,因此 Album.fromJson() 方法会创建一个 Album 对象实例,并带有默认值(在本例中为 null)。 这种行为可以以您希望的任何方式更改。
就这样!现在您已经拥有一个从互联网删除数据的函数。
完整示例
#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> deleteAlbum(String id) async {
final http.Response response = await http.delete(
Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then return an empty Album. After deleting,
// you'll get an empty JSON `{}` response.
// Don't return `null`, otherwise `snapshot.hasData`
// will always return false on `FutureBuilder`.
return Album.empty();
} else {
// If the server did not return a "200 OK response",
// then throw an exception.
throw Exception('Failed to delete album.');
}
}
class Album {
int? id;
String? title;
Album({this.id, this.title});
Album.empty();
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> {
late Future<Album> _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Delete Data Example',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: Scaffold(
appBar: AppBar(title: const Text('Delete Data Example')),
body: Center(
child: FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
// If the connection is done,
// check for response data or an error.
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(snapshot.data?.title ?? 'Deleted'),
ElevatedButton(
child: const Text('Delete Data'),
onPressed: () {
setState(() {
_futureAlbum = deleteAlbum(
snapshot.data!.id.toString(),
);
});
},
),
],
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}