删除互联网上的数据
此食谱介绍了如何使用 http
包通过互联网删除数据。
此食谱使用以下步骤
- 添加
http
包。 - 删除服务器上的数据。
- 更新屏幕。
1. 添加 http
包
#要将 http
包添加为依赖项,请运行 flutter pub add
flutter pub add http
导入 http
包。
dart
import 'package:http/http.dart' as http;
2. 删除服务器上的数据
#此食谱介绍了如何使用 http.delete()
方法从 JSONPlaceholder 删除专辑。请注意,这需要您要删除的专辑的 id
。对于此示例,请使用您已知的任何内容,例如 id = 1
。
dart
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()
方法。
dart
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()
方法返回响应,以通知我们的屏幕数据已删除。
dart
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
对象的实例。此行为可以根据您的需要进行更改。
就是这样!现在您有了从互联网删除数据的函数。
完整示例
#dart
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();
},
),
),
),
);
}
}