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?
CodePudding user response:
use below code you get exact output like you describe
Output :-
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,
);
},
),
CodePudding user response:
GridView.builder(
itemCount: 9,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return Container(
alignment: Alignment.center,
color: (index % 2 == 0) ? Colors.white : Colors.black,
child: ListTile(
title: Text(
'Rs-234554',
style: TextStyle(color: Colors.red),
),
),
);
},
),