Search code examples
listviewflutterflutter-layout

Increasing the index of the ListView Builder by two in Flutter


I want to place two list tiles in a single row. How can I increase the increment of the index in Flutter by two in each iteration?

enter image description here

In the below code, as you can see, I am trying to use two lists in a row, and then I want the index to be index+2. But, by default, the index is increased by index+1.

How do I increment it by two?

body: ListView.builder(
    itemCount: song.length - 1,
    itemBuilder: (BuildContext ctxt, int index) {
      return Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: ListTile(
              title: Text(song[index]),
              subtitle: Text(singer[index]),
              trailing: Text(time[index]),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => Player(
                      song[index],
                      singer[index],
                      time[index],
                    ),
                  ),
                );
              },
            ),
          ),
          Expanded(
            flex: 1,
            child: ListTile(
              title: Text(song[index+1]),
              subtitle: Text(singer[index+1]),
              trailing: Text(time[index+1]),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => Player(
                      song[index+1],
                      singer[index+1],
                      time[index+1],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      );
    },
  ),

Solution

  • It is always good to use GridView when you want two item in a row, but if you want to use list view the following code will help you.

    You can maintain index by other manual index.

    List<int> list = [1, 2, 3, 4, 5, 6, 7];
      int extraindex = -2;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Container(
            child: ListView.builder(
              itemCount:
                  list.length % 2 == 0 ? list.length / 2 : list.length ~/ 2 + 1,
              itemBuilder: (_, index) {
                extraindex += 2;
                return Row(
                  children: [
                    Text(list[extraindex].toString()),
                    if (extraindex + 1 < list.length)
                      Text(list[extraindex + 1].toString()),
                  ],
                );
              },
            ),
          ),
        );
      }