Handling PUT & DELETE Requests in Flutter — Updating and Deleting Data Dynamically

Handling PUT & DELETE Requests in Flutter — Updating and Deleting Data Dynamically

FlutterPulse

This article was translated specially for the channel FlutterPulseYou'll find lots of interesting things related to Flutter on this channel. Don't hesitate to subscribe!🚀

When working with APIs in Flutter, it's essential to not only fetch and post data but also update and delete it dynamically. Many apps…

When working with APIs in Flutter, it's essential to not only fetch and post data but also update and delete it dynamically. Many apps require modifying existing records (PUT/PATCH requests) and removing records (DELETE requests).

In this guide, we'll explore how to implement PUT & DELETE requests using Dio and http packages in Flutter.

1. Understanding PUT, PATCH, and DELETE Requests

🔹 PUT Request: Replaces the entire resource with new data.
🔹 PATCH Request: Updates specific fields in an existing resource.
🔹 DELETE Request: Removes a resource from the server.

Example API endpoint (JSONPlaceholder test API):

  • PUT: https://jsonplaceholder.typicode.com/posts/1 (Replaces post)
  • PATCH: https://jsonplaceholder.typicode.com/posts/1 (Updates fields)
  • DELETE: https://jsonplaceholder.typicode.com/posts/1 (Deletes post)

2. Setting Up Flutter Project

First, create a new Flutter project:

flutter create put_delete_example
cd put_delete_example

Add dependencies:

flutter pub add http dio

Import necessary packages:

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

3. Making a PUT Request to Update Data

Using http Package

Future<void> updatePost(int id, String title, String body) async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/$id');
final response = await http.put(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'title': title, 'body': body, 'userId': 1}),
);
if (response.statusCode == 200) {
print("Post updated successfully: ${response.body}");
} else {
print("Failed to update post");
}
}

Using Dio Package

Future<void> updatePostDio(int id, String title, String body) async {
final dio = Dio();
try {
final response = await dio.put(
'https://jsonplaceholder.typicode.com/posts/$id',
data: {'title': title, 'body': body, 'userId': 1},
);
print("Post updated: ${response.data}");
} catch (e) {
print("Error updating post: $e");
}
}

What Happens Here?

  • The PUT request sends new data to replace an existing post.
  • We send JSON-encoded data with headers specifying application/json.
  • If the request is successful, we print the updated data.

4. Making a PATCH Request to Modify Specific Fields

Future<void> updatePostField(int id, String title) async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/$id');
final response = await http.patch(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'title': title}),
);
if (response.statusCode == 200) {
print("Post title updated: ${response.body}");
} else {
print("Failed to update post");
}
}

PATCH is useful when you only need to update one or two fields instead of replacing the whole resource.

5. Making a DELETE Request to Remove Data

Using http Package

Future<void> deletePost(int id) async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/$id');
final response = await http.delete(url);
if (response.statusCode == 200) {
print("Post deleted successfully");
} else {
print("Failed to delete post");
}
}

Using Dio Package

Future<void> deletePostDio(int id) async {
final dio = Dio();
try {
final response = await dio.delete('https://jsonplaceholder.typicode.com/posts/$id');
print("Post deleted: ${response.statusCode}");
} catch (e) {
print("Error deleting post: $e");
}
}

What Happens Here?

  • The DELETE request removes a resource from the server.
  • If successful, we get a status code indicating deletion.

6. Creating a Simple UI to Test API Requests

Now, let's create a simple Flutter app UI to test updating and deleting posts dynamically.

main.dart – Basic UI for API Requests

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: APIExampleScreen(),
);
}
}

class APIExampleScreen extends StatefulWidget {
@override
_APIExampleScreenState createState() => _APIExampleScreenState();
}

class _APIExampleScreenState extends State<APIExampleScreen> {
final TextEditingController _titleController = TextEditingController();
final TextEditingController _bodyController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('PUT & DELETE API Calls')),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
TextField(controller: _titleController, decoration: InputDecoration(labelText: 'Title')),
TextField(controller: _bodyController, decoration: InputDecoration(labelText: 'Body')),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
updatePost(1, _titleController.text, _bodyController.text);
},
child: Text('Update Post (PUT)'),
),
ElevatedButton(
onPressed: () {
deletePost(1);
},
child: Text('Delete Post'),
),
],
),
),
);
}
}

What Happens Here?

  • The UI has text fields for input and buttons to trigger PUT & DELETE requests.
  • When the user taps "Update Post", it sends a PUT request.
  • When the user taps "Delete Post", it sends a DELETE request.

7. Best Practices for PUT & DELETE in Flutter

Use HTTP Interceptors — If using Dio, implement interceptors to handle requests globally.
Error Handling — Always check status codes and handle errors properly.
Update UI After API Calls — Use setState() or state management (Provider, Riverpod, Bloc) to reflect changes.
Use PATCH When Possible — If only updating part of the data, prefer PATCH over PUT to save bandwidth.

Final Thoughts

PUT & DELETE requests are essential for dynamic app interactions, enabling users to modify and remove data effortlessly. Whether using http or Dio, Flutter makes API communication straightforward and efficient.

If you found this story helpful, you can support me at Buy Me a Coffee!

Report Page