Delete Data from REST API
Introduction
Deleting data from a REST API is a critical function in many applications, allowing users to remove information from external data sources. This tutorial explains how to implement DELETE requests in Flutter using the http
package.
Setup
Ensure you have the http
package in your pubspec.yaml
file to make HTTP requests:
dependencies:
flutter:
sdk: flutter
http: ^1.2.1
Example: Deleting a Post
This example demonstrates how to delete a post from a JSON placeholder API. We’ll send a DELETE request and handle the response.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DeletePostExample(),
);
}
}
class DeletePostExample extends StatefulWidget {
@override
_DeletePostExampleState createState() => _DeletePostExampleState();
}
class _DeletePostExampleState extends State<DeletePostExample> {
Future<void> deletePost(int postId) async {
final response = await http.delete(Uri.parse('https://jsonplaceholder.typicode.com/posts/$postId'));
if (response.statusCode == 200) {
// If the server returns a 200 OK response, post is successfully deleted.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Success"),
content: Text("Post has been deleted successfully."),
actions: [
MaterialButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
} else {
// If the server did not return a 200 OK response,
// throw an exception.
throw Exception('Failed to delete post');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Delete Data Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () => deletePost(1), // Assuming you want to delete the post with ID 1
child: const Text('Delete Post'),
),
),
);
}
}