The Wayback Machine - https://web.archive.org/web/20240930215550/https://www.geeksforgeeks.org/flutter-deleting-data-on-the-internet/
Open In App

Flutter – Deleting Data On The Internet

Last Updated : 17 Sep, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:



Previous Article
Next Article

Similar Reads

Flutter - Updating Data on the Internet
In today's world, most applications heavily rely on fetching and updating information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore the same. To update the data on the Internet follow the below steps: Import the http packageUpdate data t using the http packageConv
5 min read
Flutter - Fetching Data From the Internet
In today's world, most applications heavily rely on fetching information from the servers through the internet. In Flutter, such services are provided by the http package. In this article we will explore the same. To fetch data from the internet follow the below steps: Import the http packageMake a network request using the http packageConvert the
3 min read
Flutter - Sending Data To The Internet
Interacting with the Internet is crucial for most apps to function. In Flutter the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. To send data to the internet through your application follow the below steps: Import the http packageSend data to the server through the http packageChan
4 min read
How to Check Internet Connection in Flutter?
In many applications, you need to check Internet Connection before going to Proceeds into the main screen. If the Internet connection is not available we can notify the user to Turn On the internet connection. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.org/wp-c
3 min read
Flutter - Build a Internet Speed Test App
Flutter is a popular framework for building mobile applications. It allows developers to create intuitive and user-friendly apps. In this article, we'll explore how to build Internet Speed Tracker App using Flutter. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.or
5 min read
Flutter - Check Internet Download Speed Programmatically
In Flutter, we can check the network speed programmatically by making HTTP requests and measuring the time it takes to download a small file. There is a small formula to calculate the download speed of the internet connection. final speedInKbps = ((response.bodyBytes.length / 1024) / (elapsed / 1000)) * 8;First, we make an HTTP using an HTTP Packag
7 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
Retrieve Data From TextFields in Flutter
In this article, we'll learn how to retrieve data from TextFields. TextField() widget is the most common widget used in flutter apps to take user input. We'll talk about two major methods used to extract text from TextField. Using Variables:The TextField widget has various callback properties through which we can extract text. Majorly, onChanged is
4 min read
Flutter - Return Data from Screen
Interaction with UI is an essential part of any application. During the same, there might raise a need to return data from the screen. This kind of interaction can range from selecting an option to navigating to different routes through the various buttons in the UI. In this article, we will explore the process of returning data from a screen in a
5 min read
Flutter - Send Data to Screen using RouteSettings
Interaction with the UI is an integral part of any application. But more often than not, the information needs to be sent from one screen to another. For instance, say you need to pass data regarding a selected or tapped component of the UI to another route(ie, page). In this article, we will explore in detail the process of sending data to another
4 min read
Flutter - Read JSON Data from Assets Folder
A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma. We will learn how to read the data already stored in your project folder in your app with just a simple function. Sometimes it happens that
3 min read
Flutter - Read and Write Data on Firebase
Firebase helps developers to manage their mobile app easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from firebase. We will be using flutter for this. To do this job we need to follow the 3-
4 min read
How to Import Data From One Page to Another in Flutter?
Flutter is Google’s Mobile SDK to build native iOS and Android, Desktop (Windows, Linux, macOS), Web apps from a single codebase. When building applications with Flutter everything towards Widgets – the blocks with which the flutter apps are built. They are structural elements that ship with a bunch of material design-specific functionalities and n
5 min read
Flutter - Fetching JSON Data using HTTP
In this article, we will learn how to fetch data from the internet or JSON file using the HTTP package in a flutter. What is HTTP? The HTTP is a composable, future-based library for making HTTP requests. This package contains a set of high-level functions and classes that make it easy to consume HTTP resources. It's multi-platform and supports mobi
4 min read
Persist Data with SQLite in Flutter
SQLite is an open supply computer database, it's wont to produce a piece of information, perform completely different operations like add, delete, and take away knowledge. SQLite doesn't need a server or backend code, all the info is saved to a computer file within the device, or we will say it's native to storage. Installing SQLite Plugin to Flutt
4 min read
Read and Write Data in Flutter using SharedPreferences
SharedPreferences is the best option to store a small amount of data in flutter projects. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, integer, float, Boolean that make up your preferences in an XML file inside the app on the devi
4 min read
Flutter - Pass Data One Screen To Another Screen
In this article we gonna know how you can pass the data from one screen to another screen in Flutter. In this example we took two screens one and screen two, In the first screen, you enter the data, and that data you can see on your second screen. This is the main object of this application. If we told you about the design of the app then on the fi
4 min read
Flutter - Fetch Data From REST APIs
In this article, we know about how we can fetch the data from the API and show it on our screen dynamically. Dynamically means all the data came from the API using the internet or you can say that you need internet access to fetch the data. For this process, we have to follow some steps to make it successfully fetch the data. Step by Step Implement
5 min read
Flutter - Store Data in Hive Local Database
Hive is a data storage in our phone where we can store data in boxes. We can store an integer, string, list of strings, Boolean, double, models, list of integers, etc. in Hive. Now let us discuss where we can implement these. The first we can use this is to save the user information user is logged in or not, and any id or user details so that users
10 min read
Flutter - Handling Asynchronous Data
Asynchronous events in Flutter, refer to events that do not occur immediately and may take some time to complete. They typically involve asynchronous operations, allowing your application to continue executing other tasks while waiting for the asynchronous operation to finish. Asynchronous events are essential for handling tasks such as network req
4 min read
Flutter - Extract Data From an Image to Text
Google ML kit provides many features, one of them is Image to Text Extraction, through which we can simply extract text from an image. To extract text from the image first we need to take an image as input either from the gallery or camera for which we will use 'image_picker: ^1.0.4' (dependency from pub.dev for flutter ) and to extract text from t
3 min read
Flutter - Fetching List of Data From API Through Dio
Dio is a powerful HTTP client for Dart, which supports Interceptors, Global configuration, FormData, File downloading, etc. and Dio is very easy to use. In this article, we will learn how to use Dio in Flutter to make API Calls and show data in ListView. Before heading toward its implementation. Why Use Dio For Internet calls?Dio makes networking f
3 min read
Flutter - Passing Multiple Data with GetX
GetX is a state management library for Flutter that provides a simple and powerful way to manage the state of your application. It provides various features like State management, Routing etc. Passing back the Data from the Second Screen to the First Screen involves State Management to achieve this in the simplest way here we are going to take the
5 min read
Flutter - How to Get Instagram Username Data
Flutter is a cross-platform application development toolkit developed and maintained by Google. Flutter redefines cross-platform app development by combining great design with superb capabilities. Flutter was released to the public in 2017, and since then many large corporations have shifted towards Flutter to supercharge their app development proc
3 min read
Flutter - Send Data to Screen
Interaction with the UI is an integral part of any application. But more often than not, the information needs to be sent from one screen to another. For instance, say you need to pass data regarding a selected or tapped component of the UI to another route(ie, page). In this article, we will explore in detail the process of sending data to another
4 min read
Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and to further read the text we can click "Read More" o
3 min read
Article Tags :