📜  Flutter – 删除互联网上的数据

📅  最后修改于: 2021-09-23 06:33:51             🧑  作者: Mango

在本文中,我们将探讨在互联网上删除数据的过程。为此,我们需要遵循 3 个关键步骤:

  1. 导入http
  2. 删除服务器上的数据
  3. 删除后更新画面

现在,我们将详细探讨它们。

导入http包:

要安装 http 包,请在命令提示符中使用以下命令:

pub get

或者,如果您使用的是flutter cmd,请使用以下命令:

flutter pub get

安装完成后将依赖添加到pubsec.yml文件中,如下图:

依赖

现在在main.js中导入http。 dart文件如下图所示:

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


删除服务器上的数据:

现在使用JSONPlaceHolder上的http.delete()方法,删除 id=1 的相册,如下所示:

Dart
Future deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    'https://jsonplaceholder.typicode.com/albums/$id',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
    
  return response;
}


Dart
Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Text('${snapshot.data?.title ?? 'Deleted'}'),
    RaisedButton(
      child: Text('Delete Data'),
      onPressed: () {
       setState(() {
        _futureAlbum = deleteAlbum(snapshot.data.id.toString());
      });
      },
    ),
  ],
);


Dart
Future deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    'https://jsonplaceholder.typicode.com/albums/$id',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
  
  if (response.statusCode == 200) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to delete album.');
  }
}


Dart
import 'dart:async';
import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
Future fetchAlbum() async {
  final response =
  await http.get('https://jsonplaceholder.typicode.com/albums/1');
  
  if (response.statusCode == 200) {
    // A 200 OK response means 
    // ready to parse the JSON.
    return Album.fromJson(json.decode(response.body));
  } else {
    // If not a 200 ok response
    // means throw an exception.
    throw Exception('Failed to load album');
  }
}
  
Future deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    'https://jsonplaceholder.typicode.com/albums/$id',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
  
  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Item Not Deleted!');
  }
}
  
class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}
  
class _MyAppState extends State {
  Future _futureAlbum;
  
  @override
  void initState() {
    super.initState();
    _futureAlbum = fetchAlbum();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Data Deletion',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: FutureBuilder(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasData) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('${snapshot.data?.title ?? 'Deleted'}'),
                      RaisedButton(
                        child: Text('Delete Data'),
                        onPressed: () {
                          setState(() {
                            _futureAlbum =
                                deleteAlbum(snapshot.data.id.toString());
                          });
                        },
                      ),
                    ],
                  );
                } else if (snapshot.hasError) {
                  return Text("${snapshot.error}");
                }
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}


更新屏幕:

这里我们将创建一个删除数据按钮,它可以通过调用 http.get() 方法来验证数据是否已从服务器中删除,如下所示:

Dart

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Text('${snapshot.data?.title ?? 'Deleted'}'),
    RaisedButton(
      child: Text('Delete Data'),
      onPressed: () {
       setState(() {
        _futureAlbum = deleteAlbum(snapshot.data.id.toString());
      });
      },
    ),
  ],
);

现在,当您单击“删除数据”按钮时,将调用deleteAlbum()方法并且您传递的 id 是您从 Internet 检索到的数据的 id。这意味着您将删除从 Internet 获取的相同数据。

返回响应:

删除数据后,我们将需要发送成功或失败响应。为此,请查看以下响应实现:

Dart

Future deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    'https://jsonplaceholder.typicode.com/albums/$id',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
  
  if (response.statusCode == 200) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to delete album.');
  }
}

完整的源代码:

Dart

import 'dart:async';
import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
Future fetchAlbum() async {
  final response =
  await http.get('https://jsonplaceholder.typicode.com/albums/1');
  
  if (response.statusCode == 200) {
    // A 200 OK response means 
    // ready to parse the JSON.
    return Album.fromJson(json.decode(response.body));
  } else {
    // If not a 200 ok response
    // means throw an exception.
    throw Exception('Failed to load album');
  }
}
  
Future deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    'https://jsonplaceholder.typicode.com/albums/$id',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
  
  if (response.statusCode == 200) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Item Not Deleted!');
  }
}
  
class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}
  
class _MyAppState extends State {
  Future _futureAlbum;
  
  @override
  void initState() {
    super.initState();
    _futureAlbum = fetchAlbum();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Data Deletion',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Center(
          child: FutureBuilder(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasData) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('${snapshot.data?.title ?? 'Deleted'}'),
                      RaisedButton(
                        child: Text('Delete Data'),
                        onPressed: () {
                          setState(() {
                            _futureAlbum =
                                deleteAlbum(snapshot.data.id.toString());
                          });
                        },
                      ),
                    ],
                  );
                } else if (snapshot.hasError) {
                  return Text("${snapshot.error}");
                }
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!