删除互联网上的数据
本食谱介绍了如何使用 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()
方法会使用默认值(在本例中为 null
)创建一个 Album
对象实例。此行为可以按您希望的任何方式进行更改。
就是这样!现在您已经有了一个从互联网上删除数据的函数。
完整示例
#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();
},
),
),
),
);
}
}