Flutter GridView项目选择颜色更改

Flutter GridView项目选择颜色更改,flutter,gridview,Flutter,Gridview,我有一个网格视图。我想更改卡片的背景色,并在单击任何索引时显示卡片上的勾号。请用简单的例子来解释这一点。下面是我想要实现的示例图像 int checkedIndex=0; 列出卡片名=[ "体育",, “野生动物”, “晚上”, “陆地空间”, ]; @凌驾 小部件构建(构建上下文){ 返回脚手架( 正文:GridView.builder( 填充:常量边集。全部(16), itemCount:cardNames.length, itemBuilder:(构建上下文,int索引){ 返回构建卡(索

我有一个网格视图。我想更改卡片的背景色,并在单击任何索引时显示卡片上的勾号。请用简单的例子来解释这一点。下面是我想要实现的示例图像

int checkedIndex=0;
列出卡片名=[
"体育",,
“野生动物”,
“晚上”,
“陆地空间”,
];
@凌驾
小部件构建(构建上下文){
返回脚手架(
正文:GridView.builder(
填充:常量边集。全部(16),
itemCount:cardNames.length,
itemBuilder:(构建上下文,int索引){
返回构建卡(索引);
},
gridDelegate:SliverGridDelegateWithFixedCrossAxisCount(
交叉轴计数:2,
),
),
);
}
小部件构建卡(int索引){
bool checked=index==checkedIndex;
字符串名=卡片名[索引];
返回手势检测器(
onTap:(){
设置状态(){
checkedIndex=索引;
});
},
子:堆栈(
儿童:[
填充物(
填充:常量边集。全部(16),
孩子:卡片(
颜色:选中?颜色。橙色:颜色。白色,
形状:圆形矩形边框(
边界半径:边界半径。圆形(12),
),
子:容器(
子对象:中心(子对象:文本(名称)),
),
),
),
定位(
前12名,
右:12,
孩子:台下(
后台:!已选中,
子:容器(
装饰:盒子装饰(
颜色:颜色,白色,
边框:边框。全部(宽度:2),
形状:长方形。圆形),
子:图标(
图标。检查,
颜色:颜色。绿色,
),
),
),
),
],
),
);
}

我已经编辑了答案,只需将checkedIndex初始值设置为0
int checkedIndex = 0;

List cardNames = [
  'Sports',
  'Wild Life',
  'Night',
  'LandSpace',
];

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: GridView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: cardNames.length,
      itemBuilder: (BuildContext context, int index) {
        return buildCard(index);
      },
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
    ),
  );
}

Widget buildCard(int index) {
  bool checked = index == checkedIndex;
  String name = cardNames[index];
  return GestureDetector(
    onTap: () {
      setState(() {
        checkedIndex = index;
      });
    },
    child: Stack(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(16),
          child: Card(
            color: checked ? Colors.orange : Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            child: Container(
              child: Center(child: Text(name)),
            ),
          ),
        ),
        Positioned(
          top: 12,
          right: 12,
          child: Offstage(
            offstage: !checked,
            child: Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(width: 2),
                  shape: BoxShape.circle),
              child: Icon(
                Icons.check,
                color: Colors.green,
              ),
            ),
          ),
        ),
      ],
    ),
  );
}