HTTP 🤩🤩 !!!! Flutter
Prakash S
Posted on May 8, 2020
Flutter is meant to create UI/Client oriented stack, but without a backend we cannot deliver a full fledged business functionality to the user.
In this post we are going to see how we can consume the http services.
Let see in action 😇
Our first step would be add the package HTTP to pubspec.yaml file
We are going to see the Four major methods of HTTP (GET, PUT, POST, DELETE) using the open API JsonPlaceholder.
Package ❤️🥰 http ❤️🥰 does all the things for us, we just need to use it as rest client like PostMan
Get🧐
import 'dart:convert';
import 'package:http/http.dart';
import 'models/post.dart';
Future<List<Post>> getPosts() async {
Client client = Client();
try {
var response =
await client.get('https://jsonplaceholder.typicode.com/posts');
List posts = jsonDecode(response.body);
return posts.map((post) => Post.fromJson(post)).toList();
} finally {
client.close();
}
}
POST😮
Future<Post> newPost(Post editedPost) async {
Client client = Client();
try {
String url = 'https://jsonplaceholder.typicode.com/posts/';
var body = jsonEncode(editedPost.toJson());
var response = await client.post(
url,
body: body,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
var post = jsonDecode(response.body);
return Post.fromJson(post);
} finally {
client.close();
}
}
PUT🙄
Future<Post> editPost(Post editedPost) async {
Client client = Client();
try {
String url = 'https://jsonplaceholder.typicode.com/posts/${editedPost.id}';
var body = jsonEncode(editedPost.toJson());
var response = await client.put(
url,
body: body,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
var post = jsonDecode(response.body);
return Post.fromJson(post);
} finally {
client.close();
}
}
DELETE🥺
Future deletePost(int id) async {
Client client = Client();
try {
String url = 'https://jsonplaceholder.typicode.com/posts/${id}';
await client.delete(url);
print('post deleted succesfully');
} finally {
client.close();
}
}
for full sample GitHubRepo
Happy Fluttering 😇😇
💖 💪 🙅 🚩
Prakash S
Posted on May 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.