繁体   English   中英

在 flutter 中按下时更改按钮的颜色

[英]Change color of button when pressed in flutter

我有这个模拟 ElevatedButton 的小部件标签。 我想要的是每次点击时更改按钮本身的颜色。 我认为在回调“ontap”中设置 state 会起作用,但没有任何反应。

我试过了,但没有颜色变化,它保持蓝色:

        return SingleChildScrollView(
      child: Wrap(
        children: <Widget>[
          for (var i = 0; i < attributesFoundDistinct.length; i++)
            FilterChipCustom(
                color: filteredByTag == true ? Colors.red : Colors.blue,
                label: attributesFoundDistinct[i],
                onSelected: (value) {
                  setState(() {
                    snapList = snapListAll;
                    _filteredDogList = snapList
                        .where((dog) => (dog[attributesFoundDistinct[i]]
                            .toLowerCase()
                            .contains(textControllerValue.toLowerCase())))
                        .toList();
                    filteredByTag = true;
                  });
                }),
        ],
      ),
    );
  }
}


class FilterChipCustom extends StatelessWidget {
  var label;
  var color;
  final ValueChanged<bool?> onSelected;

  FilterChipCustom(
      {Key? key, required this.label, this.color, required this.onSelected})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FilterChip(
      selectedColor: color,
      labelPadding: EdgeInsets.all(5.0),
      avatar: CircleAvatar(
        backgroundColor: Colors.grey.shade600,
        child: Text(label[0].toUpperCase()),
      ),
      label: Text(
        label,
        style: TextStyle(
          color: Colors.white,
        ),
      ),
      onSelected: onSelected,
      backgroundColor: Colors.blue,
      elevation: 6.0,
      shadowColor: Colors.grey[60],
      padding: EdgeInsets.all(6.0),
    );
    ;
  }
}

执行没有到达这一行: filteredByTag = true;

这可能是因为:

  • onTap 实际上并没有被调用
  • 此行之前的行抛出异常

您应该调试并查看 onTap function 中到底发生了什么。 一些猜测: snapListAll可能是 null,或者点左侧的其他任何东西都可能是 null。

 setState(() {
                    snapList = snapListAll;
                    _filteredDogList = snapList
                        .where((dog) => (dog[attributesFoundDistinct[i]]
                            .toLowerCase()
                            .contains(textControllerValue.toLowerCase())))
                        .toList();
                    filteredByTag = true; //Here
                  });

这里filteredByTag 总是正确的。 所以它总是会显示红色。

如果您需要更改两个 colors 或者单击按钮,我认为您可以尝试此操作。

 filteredByTag = !filteredByTag;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM