How To Delete Data Over The Internet In Flutter

How To Delete Data Over The Internet In Flutter

ยท

4 min read

Hi, I am Kest,

If you have been following my CRUD operation tutorial series you will already know without the title that this is the last part of the series on CRUD operation.

Users are used to this feature (ability to delete input fields) that are now available in almost every application that involves inputting fields. They do not only want to be able to edit their input, they also want to be able to delete it.

This tutorial which is the last of the four CRUD operation, is the simplest of them all, so grab a chair ๐Ÿช‘ and a drink ๐Ÿน๐Ÿฅค let's go over it.

In just three simple steps, you will be able to implement the Delete operation in your flutter application, here are the steps:

  • Add the Http Package.

  • Delete data on the server.

  • Update the screen.

๐Ÿ˜ฏ๐Ÿ˜ฏ๐Ÿ˜ฏ is that it? Yes, it's as simple as that. Let go deep into the steps.

1. Add the Http Package.

As usual to install the http package, add it to the dependencies section of the pubspec.yaml file. You can find the latest version of the http package on pub.dev. That famous pubspec.yaml file is pronounced(pubspec dot yamul or yamil depending on where you coding from... ๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚).

2.Delete data on the server.

Using the JSONPlaceholder as a case study, we want to delete a particular album. we will make use of the http.delete() method.

Note that this requires the id of the album that you want to delete. For this example, use something you already know, for example 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;
      }

The http.delete() method returns a Future that contains a Response.

  • Future is a core Dart class for working with async operations. A Future object represents a potential value or error that will be available at some time in the future.

  • The http.Response class contains the data received from a successful http call.

  • The deleteAlbum() method takes an id argument that is needed to identify the data to be deleted from the server.

3.Update the screen.

In order to check whether the data has been deleted or not. First, fetch the data from the JSONPlaceholder using the http.get() method, and display it on the screen. (See my tutorial on how to fetch Data from the internet here for a complete example). You should now have a Delete Data button that, when pressed, calls the deleteAlbum() method.

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

Now, when you click on the Delete Data button, the deleteAlbum() method is called and the id you are passing is the id of the data that you retrieved from the internet. This means you are going to delete the same data that you fetched from the internet.

Returning a response from the deleteAlbum() method

Once the delete request has been made, you can return a response from the deleteAlbum() method to notify our screen that the data has been deleted.

   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 parse the JSON. After deleting,
       // you'll get an empty JSON `{}` response.
       // Don't return `null`, otherwise `snapshot.hasData`
       // will always return false on `FutureBuilder`.
      return Album.fromJson(jsonDecode(response.body));
      } else {
      // If the server did not return a "200 OK response",
      // then throw an exception.
      throw Exception('Failed to delete album.');
        }  
       }

FutureBuilder() now rebuilds when it receives a response. Since the response wonโ€™t have any data in its body if the request was successful, the Album.fromJson() method creates an instance of the Album object with a default value (null in our case). This behavior can be altered in any way you wish.

Yeah ๐Ÿ•บ๐Ÿ•บ๐Ÿ•บ๐Ÿ•บ๐Ÿ•บ

Thatโ€™s all! Now youโ€™ve got a function that deletes the data from the internet.

Congratulations. If you have been following my tutorials on CRUD operations you should be able to perform the CRUD operations in flutter now.

kindly follow me on Twitter for More...

ย