Flutter ListView and ScrollView

Flutter ListView and ScrollView

Exploring the types of ListView

We’ll start with looking at the types of ListViews and later look at the other features and neat modifications for it.

Let’s look at the types of ListViews there are:

  1. ListView
  2. ListView.builder
  3. ListView.separated
  4. ListView.custom

Let’s go around exploring these types one by one:

ListView

This is the default constructor of the ListView class. A ListView simply takes a list of children and makes it scrollable.

The general format of the code is:

ListView(
  children: <Widget>[
    ItemOne(),
    ItemTwo(),
    ItemThree(),
  ],
),

Usually this should be used with a small number of children as the List will also construct the invisible elements in the list and a large amount of elements may render this inefficient.

ListView.builder()

The builder() constructor constructs a repeating list of items. The constructor takes two main parameters: An itemCount for the number of items in the list and an itemBuilder for constructed each list item.

No alt text provided for this image
ListView.builder(
  itemCount: itemCount,
  itemBuilder: (context, position) {
    return listItem();
  },
),

The list items are constructed lazily, meaning only a specific number of list items are constructed and when a user scrolls ahead, the earlier ones are destroyed.

Neat trick: Since the elements are loaded lazily and only the needed number of elements are loaded, we don’t really need an itemCount as a compulsory parameter and the list can be infinite.

ListView.builder(
  itemBuilder: (context, position) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(position.toString(), style: TextStyle(fontSize: 22.0),),
      ),
    );
  },
),

 
  
No alt text provided for this image

ListView.separated()

In the separated() constructor, we generate a list and we can specify the separator between each item.

No alt text provided for this image
ListView.separated(
      itemBuilder: (context, position) {
        return ListItem();
      },
      separatorBuilder: (context, position) {
        return SeparatorItem();
      },
      itemCount: itemCount,
),

ClampingScrollPhysics

This is the default scrolling physics used on Android. The list stops at the end and gives an effect indicating it.

FixedExtentScrollController fixedExtentScrollController =
    new FixedExtentScrollController();
ListWheelScrollView(
  controller: fixedExtentScrollController,
  physics: FixedExtentScrollPhysics(),
  children: monthsOfTheYear.map((month) {
    return Card(
        child: Row(
      children: <Widget>[
        Expanded(
            child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            month,
            style: TextStyle(fontSize: 18.0),
          ),
        )),
      ],
    ));
  }).toList(),
  itemExtent: 60.0,
),



要查看或添加评论,请登录

Sanjoy Kumar的更多文章

社区洞察

其他会员也浏览了