Flutter : listview builder
Displaying Dynamic Contents using ListView.builder
What is meant by Dynamic Contents?
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
Using ListView.builder(…)
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
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext ctxt) {
return new MaterialApp(
home: new ListDisplay(),
);
}
}class ListDisplay extends StatelessWidget {
@override
Widget build (BuildContext ctxt) {
return new Scaffold(
appBar: new AppBar(title: new Text("Dynamic Demo"),),
body: // ListView.builder() shall be used here.
),
);
}
}
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
- itemCount
- 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
List<String> litems = ["1","2","Third","4"];
Let’s use the ListView.builder(...)
to display the list item in the body. The code for the same shall look like this
body: new ListView.builder
(
itemCount: litems.length,
itemBuilder: (BuildContext ctxt, int index) {
return new Text(litems[index]);
}
)
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
// A Separate Function called from itemBuilder
Widget buildBody(BuildContext ctxt, int index) {
return new Text(litems[index]);
}body: new ListView.builder
(
itemCount: litems.length,
itemBuilder: (BuildContext ctxt, int index) => buildBody(ctxt, index)
So the overall hierarchy shall look like
Comments
Post a Comment