Open In App

Flutter – Deleting Data On The Internet

Last Updated : 07 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore the process of deleting data on the internet. Before deleting data on the internet, we will fetch the data first and then will delete the data.

Steps to implement Deleting Data on the Internet

Step 1 : Create a new flutter application

Create a new Flutter application using the command Prompt. To create a new app, write the below command and run it.

flutter create app_name

To know more about it refer this article: Creating a Simple Application in Flutter

Step 2 : Adding the Dependency

To add the dependency to the pubspec.yaml file, add http as a dependency in the dependencies part of the pubspec.yaml file, as shown below:

Dart
dependencies:
      flutter:
        sdk: flutter
      http: ^1.3.0

Now run the below command in the terminal.

flutter pub get


Step 3 : Importing the Dependency

Use the below line of code in the main.dart file, to import the shimmer dependency :

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


Step 4: Follow below flow to delete data from internet

Fetch data from internet

Before deleting data on the internet, we need to fetch data from internet

so, follow this article to know more about fetching data from the internet : Flutter – Fetching Data From the Internet


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<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) {
            return Album.fromJson(jsonDecode(response.body));
      } else {
            throw Exception('Item Not Deleted!');
      }
}


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'}'),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
                backgroundColor: Colors.green,
                foregroundColor: Colors.white
                ),
            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
 if (response.statusCode == 200) {
        return Album.fromJson(jsonDecode(response.body));
  } else {
        throw Exception('Item Not Deleted!');
  }


Complete Source Code

Dart
import 'dart:async';
import 'dart:convert';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({super.key});

  @override
  _MyAppState 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: 'Data Deletion',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
          foregroundColor: Colors.white,
        ),
        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'}'),
                      ElevatedButton(
                        style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green,
                            foregroundColor: Colors.white),
                        child: Text('Delete Data'),
                        onPressed: () {
                          setState(() {
                            _futureAlbum =
                                deleteAlbum(snapshot.data!.id.toString());
                          });
                        },
                      ),
                    ],
                  );
                } else if (snapshot.hasError) {
                  return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        "Deleted and again fetching",
                        style: TextStyle(
                            fontSize: 20, fontWeight: FontWeight.bold),
                      ),
                      Text(
                          "It is giving 'Null' because we deleted that content"),
                    ],
                  );
                }
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('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<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) {
    return Album.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Item Not Deleted!');
  }
}

class Album {
  final int id;
  final String title;

  Album({required this.id, required this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}

Output:




Next Article
Article Tags :

Similar Reads