FLUTTER – How to obtain the GridView horizontal index?

Issue

I am developing a GridView in flutter. In every row I have 3 items. Every item is a widget that accepts a Color to be used as a background color.

What I want to achieve is to have the colors alternate, in this way

WHITE | BLACK | WHITE
BLACK | WHITE | BLACK
WHITE | BLACK | WHITE

The problem is that I don’t know hot to get what is the index of every horizontal item. How to get this?

Solution

use below code you get exact output like you describe

Output :-

enter image description here

Code :-

GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: 16.0,
                  crossAxisSpacing: 16.0,
                ),
                itemCount: 9,
                itemBuilder: (context, index) {
                  return Container(
                    color: index % 2 == 0 ? Colors.white : Colors.black,
                  );
                },
              ),

Answered By – MohammedAli

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.