Ad

How To Increment Index In A GridView In Flutter?

- 1 answer

I have a GridView that is as shown below. I am trying to section it out in smaller GridViews and have a separator in between.

However instead of showing me a continuous list, the elements from 0-5 keep repeating. I am trying to continue the elements in batches of 6 where the first batch is 0-5 and the next is from 6-11 and so on..

This is my code:

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.separated(
      separatorBuilder: (context, int) {
        return Divider(color: Colors.black,);
      },
     // shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return GridView.count(
          shrinkWrap: true,
          crossAxisCount: 3,
          childAspectRatio: 2.0,
          children: List.generate(6, (index) {
            return Center(
              child: RaisedButton(
                onPressed: (){},
                color: Colors.greenAccent,
                child: Text(
                  '$index AM',
                ),
              ),
            );
          }),
        );
      },
      itemCount: 4,
    ));
  } 

This is what the GridView looks like:

enter image description here

Ad

Answer

You can use the index from the itembuilder to know which group of 6 you're generating.

Change the name index in itemBuilder to itemBuilderIndex like so:

itemBuilder: (BuildContext context, int itemBuilderIndex) {

And do this to get the calculated number you want:

'${(itemBuilderIndex * 6) + index} AM'

(6 being the number of items you have per segment)

Ad
source: stackoverflow.com
Ad