首页 > 解决方案 > GridView 项目选择颜色更改

问题描述

我有一个 GridView。我想更改卡片的背景颜色并在单击任何索引时显示该卡片上的刻度线。请用简单的例子解释一下。下面是我要实现的示例图像。

在此处输入图像描述

标签: fluttergridview

解决方案


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,
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

推荐阅读