Handling Rest API’s in Flutter like a Pro.

tekeshwar singh
2 min readOct 7, 2020

There’s a high chance you came across the term “REST API” if you’ve thought about getting data from another source on the internet.

In this article, you’ll learn how to use REST API in Flutter Apps.

Let’s Start:

We will be using newsapi.org.

Packages Required:

As I mentioned Pro in the title we have to do it in Pro Mode..

Creating Model:

  • Create a File named NewsModel.dart and paste below code.
  • In above code we have create a PODO class to handle data which will help us in Big Projects.
  • There are 2 important methods
  1. fromMap: it is used to get data and set them into variable.
  2. toJson: it is used to create a JSON which we can use to send as body in POST routes.

Now head over to main.dart or wherever you want fetch data.

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

Create a get request and save the Response, now we have to decode this response to using jsonDecode as show below.

[“articles”] is options it depends on your API response the response of newsapi.org gives it’s data under “articles” that’s why i am using this.

http.Response response = await http.get(Constansts.endPoint);var data = jsonDecode(response.body)["articles"];

now that we have the data we can add this in a List as we are getting a list of news for this we will now use you Model (as we are PRO).

List<NewsModel> _news = List<NewsModel>();for (var i = 0; i < data.length; i++) {_news.add(NewsModel.fromMap(data[i]));}

Here in first line we are declaring a empty List of type NewsModel (which is your Model name we create above).

Then using fromMap method of NewsModel add data to _news .

Complete code will look like this:

Some Important Points:

Before sending data in body make sure to jsonEncode the data.

jsonEncode(_news[0].toJson());

So, That’s All of this Article, you can get the full code at below GitHub Repo.

--

--