刪除網際網路上的資料
本指南介紹瞭如何使用 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();
},
),
),
),
);
}
}