2

我在从模型中获取的 gridView 中列出了多张卡片。我想在选择卡片时更改特定卡片的背景颜色。也就是说,当我触摸卡片时,我希望那张卡片的颜色发生变化,如果我选择另一张卡片,我希望第一张卡片的颜色恢复到原来的颜色,并希望第二张卡片的颜色发生变化。我尝试了各种方法,但无法做到。

网格视图:

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),

...

  };
4

1 回答 1

3

在状态类上创建一个可为空的 int 并基于它传递颜色,并在onTap: like上更改索引

 int? selectedIndex;
  @override
  Widget build(BuildContext context) {
   //...  
   GestureDetector(
      child: Card(
        color: selectedIndex == index? Colors.green : null,
      ),
      onTap: () {
        setState(() {
          selectedIndex = index;
        });
      },
    );
   
于 2021-12-14T18:01:18.603 回答