Flutter : listview builder

 

Displaying Dynamic Contents using ListView.builder

Unless an app is very basic and created for learning purposes, it will always use dynamic data i.e. Contents of the screen will change based on user actions and/or with change in network data.

Most of the time, the dynamic behaviour is achieved by changing the contents that is being displayed in the body. Flutter provides ListView.builder which can be used to generate dynamic contents

 Image for post

ListView.builder is a way of constructing the list where children’s (Widgets) are built on demand. However, instead of returning a static widget, it calls a function which can be called multiple times (based on itemCount ) and it’s possible to return different widget at each call.

For example, let’s create a simple application containing basic MaterialApp with Scaffold contains AppBar and Body

To use ListView.builder, we have to create an instance of it by calling its constructor using new , it takes multiple parameters, however, two of them are of special importance. They are

  1. itemCount
  2. itemBuilder

The itemCount parameter decides how many times the callback function in itemBuilder will be called.

To demonstrate the same, let’s assume that we have a global list like this in our application

Let’s use the ListView.builder(...) to display the list item in the body. The code for the same shall look like this

In here, the in-place callback function shall be called 4 times and each call will generate a Text Widget which shall be displayed in the body.

We can also write a separate function which can be called from itemBuilder as

 

So the overall hierarchy shall look like


Image for post
Stateful Widget Scaffold Hierarchy

Comments

Popular posts from this blog

Flutter: Exploring more widgets

Flutter: Everything is a widget

Food Delivery App 5 - Firebase Storage for Profile Picture