跳转至正文

删除网络数据

如何使用 http 这个 package 来删除远程服务器的数据。

本教程介绍如何使用 http package 在互联网上删除数据。

本教程包含以下步骤:

  1. 添加 http package。

  2. 在服务器上删除数据。

  3. 更新屏幕。

1. 添加 http package

#

要将 http package 添加为依赖,请运行 flutter pub add

flutter pub add http

导入 http package。

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

如果你要部署 Android,请编辑 AndroidManifest.xml 文件,添加 Internet 权限。

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

同样,如果你要部署 macOS,请编辑 macos/Runner/DebugProfile.entitlementsmacos/Runner/Release.entitlements 文件,添加 network client 权限。

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 获取数据,并在屏幕上显示。(完整示例请参阅 Fetch Data 教程。)此时你应该有一个 Delete Data 按钮,按下时会调用 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(),
          );
        });
      },
    ),
  ],
);

现在,当你点击 Delete Data 按钮时,会调用 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();
            },
          ),
        ),
      ),
    );
  }
}