Open In App

Flutter – Deleting Data On The Internet

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will explore the process of deleting data on the internet. To, do so we need to follow 3 crucial steps:

  1. Import the http package
  2. Delete the data on the server
  3. Update the screen after deletion

Now, we will explore them in detail.

Importing The http Package:

To install the http package use the below command in your command prompt:

pub get

or, if you are using the flutter cmd use the below command:

flutter pub get

After the installation add the dependency to the pubsec.yml file as shown below:

dependencies

Now import the http package in the main.dart file as shown below:

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


 

Deleting Data on Server:

Now use the http.delete() method on the JSONPlaceHolder, to delete the Album  with id=1 with as shown below:

Dart




Future<Response> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );
    
  return response;
}


Update The Screen:

Here we will create a delete data button that can verify if a data has been deleted from the server by calling the http.get() method as shown below:

Dart




Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    Text('${snapshot.data?.title ?? 'Deleted'}'),
    RaisedButton(
      child: 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:

After the data is deleted we will be needing to send a success or failure response. To do so look at the below response implementation:

Dart




Future<Album> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    headers: <String, String>{
      '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.');
  }
}


Complete Source Code:

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 =
  
  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<Album> deleteAlbum(String id) async {
  final http.Response response = await http.delete(
    headers: <String, String>{
      '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<String, dynamic> 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<MyApp> {
  Future<Album> _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<Album>(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasData) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      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();
            },
          ),
        ),
      ),
    );
  }
}


Output:



Last Updated : 17 Sep, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads