如何在 Flutter 中选择项目后更改卡片颜色?

How to change card color upon selection of an item in Flutter?

我在从模型中获取的 gridView 中列出了多张卡片。我想在 selection 卡片上更改特定卡片的背景颜色。也就是说,当我触摸卡片时,我希望改变那张卡片的颜色,如果我 select 另一张卡片,我希望第一张卡片的颜色恢复到原来的颜色并想要第二张卡片的颜色改变。试过各种方法都做不到。

网格视图:

Widget build(BuildContext context) {
    final petTypes = widget.pet.types();
    var petKeys = petTypes.keys.toList();

    return Scaffold(
        appBar: AppBar(
          title: Text('Add pets - Type'),
          backgroundColor: Color.fromRGBO(101, 69, 112, 1.0),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Expanded(
                child: GridView.count(
                  crossAxisCount: 2,
                  scrollDirection: Axis.vertical,
                  primary: false,
                  children: List.generate(petTypes.length, (index) {
                     return GestureDetector(
                       child: Card(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              petTypes[petKeys[index]],
                              Text(petKeys[index]),
                            ],
                          ),
                          // onPressed: () async {
                          //   widget.pet.type = petKeys[index];
                          // },
                        ),
                         onTap: (){
                         setState(() {
                           widget.pet.type = petKeys[index];
                         });
                         }
                     );
                  }),
                ),
              ),

型号:

Map<String, Image> types() => {
        "Dog":
            Image(image: AssetImage('Assets/images/dog-type.png'), width: 70),
        "Cat":
            Image(image:AssetImage('Assets/images/cat-type.png'), width: 70),
        "Bird":
            Image(image:AssetImage('Assets/images/bird-type.png'), width: 70),
        "Rabbit":
            Image(image:AssetImage('Assets/images/rabbit-type.png'), width: 70),
        "Hamster":
            Image(image:AssetImage('Assets/images/hamster-type.png'), width: 70),
        "Fish":
            Image(image:AssetImage('Assets/images/fish-tank.png'), width: 70),

...

  };

在状态 class 上创建一个可为空的整数并基于它传递颜色,并在 onTap: 上更改索引 喜欢

 int? selectedIndex;
  @override
  Widget build(BuildContext context) {
   //...  
   GestureDetector(
      child: Card(
        color: selectedIndex == index? Colors.green : null,
      ),
      onTap: () {
        setState(() {
          selectedIndex = index;
        });
      },
    );