Flutter. Create a news app. Part 2. Adding ListView

Rasul Aghakishiyev
Flutter Community
Published in
3 min readJul 19, 2019

--

In the previous lesson, we learned how our flutter is structured and which parts it has. Today we will create the first page of our news app, which contains ListView with some data in it.

We have our _MyHomePageState class which does not has much logic in it. Let’s change it a little bit and add some widgets which we need for our application

\

As you can see, our body widget has changed and now it is a Container. Inside it, we put ListView which will have news from our API. At this stage, ListView children element is an empty array, but later we add items to it.

Let’s create a new file list_item.dart which will contain an item widget for our ListView(Like ViewHolder in RecyclerView). In flutter, all files name should start with lowercase and if it has more than 2 words in its name, words should divide with an underscore. But the name of the classes should write in the camel case and the first letter should be upper.

As you can see we have a Container widget with one Row child which has 2 Text as its children. It’s a very simple StatelessWidget. We use StatelessWidget because it will not change its state during the app running. Let's use our newly created widget in the list and show it. To do it we should write some code in our main.dart file.

To create a list in our application we use ListView.builder. It receives many arguments but in this stage, we will use just 2 of them. Let’s describe each of them.

itemCount —it says how many items will be in your ListView. Because currently do not get news from the network, we just write 5, but in the next lessons, we use there our news count.

itemBuilder — you should pass a function with 2 arguments that return your Widget which will use to draw our list items. The function must have 2 arguments which BuildContext and index. Now we will not use any of these arguments, but in the future, we will use the index to get a specific item from our list.

So let’s run the app, and look at what’s going on there.

Wow, our app is work and shows us 5 elements with title and description. But it looks a little bit bad, so we should add some paddings because it is so close to corners and also we should style our text to make our app more beautiful.

Today we learned how to create ListView with custom Widget and show our items in it. In the next lessons, our item will rich and contains image, title, description and other information about the news.

Have nice coding!

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

Github: https://github.com/agarasul

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

--

--

Rasul Aghakishiyev
Flutter Community

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