跳到主內容

刪除網際網路上的資料

如何使用 http 包刪除網路上的資料。

本篇指南涵蓋了如何使用 http 包透過網路刪除資料。

本示例將採取以下步驟

  1. 新增 `http` 包。
  2. 刪除伺服器上的資料。
  3. 更新螢幕。

1. 新增 `http` 包

#

要將 http 包新增為依賴項,請執行 flutter pub add

flutter pub add http

匯入 `http` 包。

dart
import 'package:http/http.dart' as http;

如果你部署到 Android,請編輯 `AndroidManifest.xml` 檔案以新增網際網路許可權。

xml
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />

同樣,如果你部署到 macOS,請編輯 `macos/Runner/DebugProfile.entitlements` 和 `macos/Runner/Release.entitlements` 檔案以包含網路客戶端授權。

xml
<!-- Required to fetch data from the internet. -->
<key>com.apple.security.network.client</key>
<true/>

2. 刪除伺服器上的資料

#

本篇指南涵蓋了如何使用 http.delete() 方法從 JSONPlaceholder 刪除一個相簿(album)。請注意,這需要你想要刪除的相簿的 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() 方法會返回一個包含 ResponseFuture

  • 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();
            },
          ),
        ),
      ),
    );
  }
}