11-Apr-2022
.
Admin
Hi friends,
In this post, we will learn How to API Delete Request in Flutter?. i explained simply step by step How to make an http DELETE request in flutter. Here you will learn Simple How to Flutter Deleting Data On The Internet. This tutorial will give you simple example How to delete data over the internet in flutter.
I will give you simple Example of How To Use HTTP Requests in Flutter.
So let's see bellow example:
Step 1 : Create Flutter Project
Follow along with the setup, you will be creating an Flutter app.
- $flutter create flutter_get_request_example
Navigate to the project directory:
- $cd flutter_get_request_example
Open pubspec.yaml in your code editor and add below plugin:
dependencies:
flutter:
sdk: flutter
http: ^0.12.0+2
Step 2 : Handl GET Request
Create a http_service.dart file in the lib directory
import 'dart:convert';
// ignore: import_of_legacy_library_into_null_safe
import 'package:http/http.dart';
import 'post_model.dart';
class HttpService {
final String postsURL = "https://jsonplaceholder.typicode.com/posts";
Future
> getPosts() async {
Response res = await get(postsURL);
if (res.statusCode == 200) {
List
body = jsonDecode(res.body);
List
posts = body .map(
(dynamic item) => Post.fromJson(item),
)
.toList();
return posts;
} else {
throw "Sorry! Unable to get post.";
}
}
}
Then, create a post_model.dart file in the lib directory.
import 'package:flutter/foundation.dart';
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({
required this.userId,
required this.id,
required this.title,
required this.body,
});
factory Post.fromJson(Map
json) { return Post(
userId: json['userId'] as int,
id: json['id'] as int,
title: json['title'] as String,
body: json['body'] as String,
);
}
}
Step 3 : Display Post Data
Next, create a post_detail.dart file in the lib directory
import 'package:flutter/material.dart';
import 'post_model.dart';
class PostDetail extends StatelessWidget {
final Post post;
PostDetail({@required this.post});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(post.title),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
children:
[ Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children:
[ ListTile(
title: Text("Title"),
subtitle: Text(post.title),
),
ListTile(
title: Text("ID"),
subtitle: Text("${post.id}"),
),
ListTile(
title: Text("Body"),
subtitle: Text(post.body),
),
ListTile(
title: Text("User ID"),
subtitle: Text("${post.userId}"),
),
],
),
),
],
),
),
)
);
}
}
Next, create a posts.dart file in the lib directory
import 'package:flutter/material.dart';
import 'http_service.dart';
import 'post_detail.dart';
import 'post_model.dart';
class PostsPage extends StatelessWidget {
final HttpService httpService = HttpService();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Api get request with Delete Post"),
),
body: FutureBuilder(
future: httpService.getPosts(),
builder: (BuildContext context, AsyncSnapshot
> snapshot) {
if (snapshot.hasData) {
List
? posts = snapshot.data; return ListView(
children: posts!
.map(
(Post post) => ListTile(
title: Text(post.title),
subtitle: Text("${post.userId}"),
onTap: () => Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PostDetail(
post: post,
),
),
),
),
)
.toList(),
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
Open lib/main.dart and modify it to use PostsPage:
import 'package:flutter/material.dart';
import 'posts.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'HTTP',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: PostsPage(),
);
}
}
Step 4 : Handl DELETE Request
Open http_service.dart in your editor and create a deletePost(int id) method:
import 'dart:convert';
import 'package:http/http.dart';
import 'post_model.dart';
class HttpService {
final String postsURL = "https://jsonplaceholder.typicode.com/posts";
// ...
Future
deletePost(int id) async { Response res = await delete("$postsURL/$id");
if (res.statusCode == 200) {
print("Deleted");
} else {
throw "Sorry! Unable to delete this post.";
}
}
}
Change in post_detail.dart in your editor and add an IconButton to the actions array within the AppBar. When the icon is pressed, the associated post should be deleted:
import 'package:flutter/material.dart';
import 'http_service.dart';
import 'post_model.dart';
class PostDetail extends StatelessWidget {
final HttpService httpService = HttpService();
final Post post;
PostDetail({@required this.post});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(post.title),
actions:
[ IconButton(
icon: Icon(Icons.delete),
onPressed: () async {
await httpService.deletePost(post.id);
Navigator.of(context).pop();
},
)
],
),
// ...
);
}
}
Step 4 : Run this Debug App
Output
I hope it will help you....
#Flutter