List View class

Mercy Jemosop
Geek Culture
Published in
4 min readAug 19, 2021

Display Items In listview.builder in flutter

Introduction

A scrollable list of widgets arranged linearly, it displays its children one after another in the scroll direction. In the cross axis, the children are required to fill the ListView.

There are four ways of constructing a list view

  • List<Widget> which is the default, it is appropriate for list views with a small number of children because constructing the List requires doing work for every child that could possibly be displayed in the list view instead of just those children that are actually visible.
  • ListView.builder is a appropriate with large and infinite children. It takes an IndexedWidgetBuilder, which builds the children on demand.
  • ListView.separated takes two IndexedWidgetBuilders: itemBuilder builds child items on demand, and separatorBuilder similarly builds separator children which appear in between the child items. This constructor is appropriate for list views with a fixed number of children.
  • ListView.custom which provides the ability to customize additional aspects of the child model. For example, a SliverChildDelegate can control the algorithm used to estimate the size of children that are not actually visible.

We will work with a listView.builder constructor to display a list from an API

Get data from your API, In my case i will be retrieving data from medium endpoint. Edit your username to your medium username. N.B you can use any endpoint this is just an example.

const BLOG_API ='https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/@yourusername';

Step 1: Get data from medium/endpoint. apiProvider.dart

import 'dart:convert';import 'package:portfolio/application/theme/config.dart';
import 'package:http/http.dart' as http;
const BLOG_API =
'https://api.rss2json.com/v1/api.json?rss_url=https://medium.com/feed/@mercyjemosop';
class ApiProvider {
Future getBlogs() async {
final response = await http.get(Uri.parse(Constants.BLOG_API));
if (response.statusCode == 200) {
var data = response.body;
return jsonDecode(data);
} else {
return response.statusCode;
}
}
}

add the http package to your pubspec.yaml.Check the latest version in its documentation.

http: ^0.13.3

Step 2: Make the data/ response from API available in our app

Create a method getMediumData() which calls the getBlogs() method in ApiProvider class which contains the response/data from medium.

To call the method ,first you create an instance of the class

ApiProvider apiProvider = ApiProvider();

Then using the instance you can access the method

var mediumData = await apiProvider.getBlogs();

To understand how to retrieve specific data from the API, here is an example of the structure

our main interest, is the items which contains, the title, link to the page, blog post image(thumb nail). To fetch all those items

/// get the first image in the array
imageUrl = mediumData['items'][0]['thumbnail'];
/// get all items
itemsList = mediumData['items'];
/// get title in an array
mediumData['items'][i]['title']
/// get the author
mediumData['items'][i]['author'],

To make this data available in our widget without tapping on anything, we will add the method to the initState(), this will be called without the user calling it manually.

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

To display url from our widget, add launcher package to pubspec.yaml

url_launcher: ^6.0.9

Step 3: now we display our data in a listview.builder

Creates a scrollable, linear array of widgets that are created on demand. Providing a non-null itemCount improves the ability of the ListView to estimate the maximum scroll extent.The itemBuilder callback will be called only with indices greater than or equal to zero and less than itemCount.The itemBuilder should always return a non-null widget, and actually create the widget instances when called. Avoid using a builder that returns a previously-constructed widget. Read more on listview builder.

/// listview builder basic format
final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];

ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 50,
color: Colors.amber[colorCodes[index]],
child: Center(child: Text('Entry ${entries[index]}')),
);
}
);

With the above knowledge in mind, lets add a listview in our widget

This is the output

The items are scrollable. if you want them to scroll in a horizontal direction.

/// add this property inside ListView.builderscrollDirection: Axis.horizontal,

Let’s add a search and filter to our application

Step 1: design a text field

/// initialize your controller
TextEditingController editingController = TextEditingController();
child: TextField(
onChanged: (value) {
setState(() {
searchTerm = value;
});
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
fillColor: Colors.white,
filled: true,
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),

return all the items if Controller is empty(you have not typed anything in the text field).

editingController.text.isEmpty

return only item which contains the value typed

mediumData['items'][i]['title']
.toLowerCase()
.contains(editingController.text)

complete code

https://gist.github.com/mercykip/72e398505fecd3221eaba4ba7b01b170

It’s as easy as that. Here is my GitHub repo for reference

Happy coding!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

--

--

Mercy Jemosop
Geek Culture

Software Developer. I am open to job referrals. connect with me on twitter @kipyegon_mercy