【问题标题】:GridView Item Selection Color changeGridView 项目选择颜色更改
【发布时间】:2021-03-28 20:33:49
【问题描述】:

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

【问题讨论】:

    标签: flutter gridview


    【解决方案1】:
    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,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
    

    【讨论】:

    • 我已经编辑了答案,只是将checkedIndex初始值设置为0
    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多