跳至主要內容

刪除網路上的資料

本範例涵蓋如何使用 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.entitlementsmacos/Runner/Release.entitlements 檔案,以包含網路用戶端權限。

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

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() 方法會回傳包含 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();
            },
          ),
        ),
      ),
    );
  }
}