Here, You will learn about flutter http get request. Calling flutter get api returns JSON response. We will build get request api call and then process the json response from the server in flutter api.
If you wanna learn about Getx http request click here.
We used Laravel to send the response to the app from the server. To process the flutter http response with get request, in flutter we need to build a model. First we decode the response and save in a variable and then we build the model.
We created a dart class name my_api.dart to place our get request. Inside the class, we create a function name getArticleData() to create a restful api request to the server.
The class looks like this
class CallApi{
final String _url = 'http://mark.dbestech.com/api/';
final String _imgUrl='http://mark.dbestech.com/uploads/';
getImage(){
return _imgUrl;
}
getArticleData(apiUrl) async {
http.Response response = await http.get(
Uri.parse(_url+apiUrl)) ;
try {
if (response.statusCode == 200) {
return response;
} else {
return 'failed';
}
} catch (e) {
print(e);
return 'failed';
}
}
}
The function getArticleData() takes an end point. We assing our end point to it and wait for response.
In the above code http.get() is the actual get request that makes the request. It takes our base url and end point.
http.Response response = await http.get(
Uri.parse(_url+apiUrl)) ;
The returned response we save in a variable called response which is http.Response type object.
We also check http response using response.statuscode
if the statuscode is 200 we just return the repsonse object which also means that we got correct response from out http api call.
We have used a custom parser to decode json and use them in our application. We have used fromJson constructor build the data from the model to use and display in the widget.
Starter code github link https://github.com/dastagir-ahmed/flutter-get-api-
Check out flutter backend tutorial
Check out flutter http get request tutorial
Http post request