Flutter – Deleting Data On The Internet

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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.');
  }
}

chevron_right


Complete Source Code:

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.