Flutter. Part 4. Fetch data from the network

Rasul Aghakishiyev
Flutter Community
5 min readAug 1, 2019

--

Today we will learn how to fetch our news from the network and show it in our application. First of all, we need to add http to our dependencies. Open pubspec.yaml and add the following lines in the dependencies :

dependencies:
flutter:
sdk: flutter
http: ^0.12.0+2 // We need it to make network requests

After this open terminal and run: flutter pub get.

Now we should import in our main.dart file, open the main.dart file and add this line to the top:

import ‘package:http/http.dart’ as http;

Now we can use http to make network requests. We will fetch our news from https//newsapi.org. It’s a free News API, which you can also use. After registration, you will get an API key which you will use to get news.

Our response body will look like this:

{
“status”: “ok”,
“totalResults”: 38,
“articles”: [
{
“source”: {
“id”: null,
“name”: “”
},
“author”: “”,
“title”: “”,
“description”: “”,
“url”: “",
“urlToImage”: “",
“publishedAt”: “2019–07–29T09:18:00Z”,
“content”: “”
}
]
}

We need to create a model class which we will when we parse our network response.

In Android development, we have a couple of libraries which helps us to convert JSON file to our POJO class. But in Flutter, we do not have libraries like Gson and Moshi or Jackson, so we should to this work by ourselves. To do it we can use json.encode and json.decode methods which contain in Dart language.

For example, if we have a json structure like this:

{
“id”: null,
“name”: “”
}

We can create some class called sample.dart:

class Sample {   String id;
Stream name;
Sample.fromJson(Map<String, dynamic> data)
: id = json['id'],
name = json['name'];
}

If we look at our class we can see that we have a static method called fromJson which receives Map object. Then we set id and name values from our Map object called data. Now we can use our function to convert our json to class.

var sampleEntity = Sample.fromJson(json.decode(sampleJson))

If we have complex json objects we will everything in the same way.

For example:

{
“source”: {
“id”: null,
“name”: “”
},
“author”: “”
}

Our class will look like this:

As you can see to create a Source object inside Article object we just call Source.fromJson method and pass the json string from our articleJson map to it.

If it will be a list instead of an object our class will look like this:

First of all, we create a list and then map it and convert to Source class.

Now you learn how to convert json object to class. Let’s create a class for our json from news API. Our news.dart file will look like this:

Now let’s modify our main.dart file a little bit. Add new variable in _MyHomePageState

List<Article> _newsList = new List(); 

In this variable, we will store our news. Also, we edit our ListView.Builder

Before it looks like this:

ListView.builder(
itemCount: 5,
itemBuilder: (context, index) => ListItem(),
)

Now it will be like this:

ListView.builder(
itemCount: _newsList.length,
itemBuilder: (context, index) => ListItem(_newsList[index]),
)

Also, we need a constructor in our list_item.dart. where we pass our news.

final Article article;ListItem(this.article);

We should modify our Text widgets also, and instead of static text we will use text from our Article object

This:

Image.network("https://github.com/agarasul/SampleNewsApp/raw/master/empty_image.png")Text(“Dummy title”),
Text(“Dummy description”)

Will be:

Image.network(article.urlToImage)Text(article.title),
Text(article.description)

Now add function to make a network request to get our news

To call this method when the app starts, we should override the initState() method in _MyHomePageState:

@override
void initState() {
super.initState();
getData();
}

Now if we run our app we will see this:

You can see that our text does not fit our screen and flutter show as the alert. Let’s fix it and also add some style to our texts.

To make our widget get all available space, we can use the Expanded widget. And we just put our Padding widget with texts widgets in it to our Expanded widget.

And the result is:

Well, now texts fit our emulator screen, but texts are so long and list items look not so pretty and also read the news is a little bit complicated. Now we will change our title and description to allow them to have only 2 lines and also make our title bold and the description cursive to make them more readable.

Firstly we need to add the following code to our Text widgets:

overflow: TextOverflow.ellipsis,
textAlign: TextAlign.left,
maxLines: 2,

overflow — indicates that text should cut if it overflows our screen.

textAlign — sets the text start position

maxLines — how many lines our text will have

Then, we will add style to our title Text widget:

style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16 )

TextStyle has a lot of parameters but at this time we will only use fontWeigth and fontSize

fontWeigth —what type is our text

fontSize — no explanation needed

Instead of using fontWeight we will use fontStyle to make our description Text widget with cursive:

style: TextStyle(fontStyle: FontStyle.italic, fontSize: 12)

The final code is:

Now the final result of our work is:

Follow me on Twitter: https://twitter.com/a_rasul98

Github: https://twitter.com/a_rasul98

Source code: https://github.com/agarasul/SampleNewsApp

--

--

Rasul Aghakishiyev
Flutter Community

Android Software Engineer. Interested in mobile development. In love with Jetpack Compose