Flutter - Making http calls using http and dio
Code snippets for making http requests using flutter or dio plugin.
Setup
we will be using http to make basic network calls for methods like GET, POST, DELETE and so on.
http: latest_versionMaking a simple GET request
I will setup a simple class named APIService which contains all the methods for making requests.
class APIService{
}I am not exclusively checking for internet availability using any package like connectivity plus. Will be handling errors here itself.
class APIService{
// baseurl for API
String baseUrl = "http://10.0.2.2:5000";
// returns a list of all posts as per my API
// may use this in a futurebuilder
Future<List> getPosts() async {
try {
var response = await http.get(Uri.parse(baseUrl));
if (response.statusCode == 200) {
// return a decoded body
return jsonDecode(response.body);
} else {
// server error
return Future.error("Server Error !");
}
} catch (SocketException) {
// fetching error
// may be timeout, no internet or dns not resolved
return Future.error("Error Fetching Data !");
}
}
}POST with data
I will send post data to server with some json data. This api doesn't require any authentication hence no Bearer or auth token.
Future<String> createPost(Map<String, dynamic> data) async {
try {
var response = await http.post(
Uri.parse("$baseUrl/create"),
body: jsonEncode(data),
headers: {
"Content-Type": "application/json; charset=UTF-8",
},
);
if (response.statusCode == 200) {
return "success";
} else {
print(response.body);
// server error
return "err";
}
} catch (SocketException) {
// fetching error
return "err";
}
}The returned string can be used to show weather the post was created successfully or not.
Delete Request
Deleting a resource is also simple , make a request as per your API, mine expects a slug in the body, so doing that. Create a map/object of the data that you grab from a form or anything.
Future<String> deletePost(Map<String, dynamic> data) async {
try {
var response = await http.delete(
Uri.parse("$baseUrl/delete"),
body: jsonEncode(data),
headers: {
"Content-Type": "application/json; charset=UTF-8",
},
);
//
if (response.statusCode == 200) {
return "success";
} else {
print(response.body);
// server error
return "err";
}
} catch (SocketException) {
// fetching error
return "err";
}
}