You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中创建自定义FilterChip组件时,如何正确声明onSelect回调?

自定义FilterChip组件的回调声明方案

你需要把onSelect声明为ValueChanged<bool>类型,这和原生FilterChip的onSelected参数类型完全匹配——它的定义就是接收一个bool类型参数且无返回值。

另外注意你代码里的lable是拼写错误,应该改成label。

修正后的完整代码如下:

class CustomFilterChipWidget extends StatelessWidget {
  final bool isSelected;
  final String label;
  // 声明与FilterChip onSelected一致的回调类型
  final ValueChanged<bool> onSelect;

  const CustomFilterChipWidget({
    Key? key,
    required this.isSelected,
    required this.label,
    required this.onSelect,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FilterChip(
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
      showCheckmark: false,
      selectedColor: Colors.white,
      backgroundColor: Colors.white,
      shape: StadiumBorder(
        side: BorderSide(
          width: isSelected ? 2 : 0,
          color: isSelected ? Colors.blue : Colors.grey,
        ),
      ),
      selected: isSelected,
      label: Text(label),
      // 直接传递自定义的onSelect回调即可
      onSelected: onSelect,
    );
  }
}

使用示例

在父组件中使用这个自定义组件时,可像原生FilterChip一样传入回调:

CustomFilterChipWidget(
  isSelected: _isChipSelected,
  label: "示例标签",
  onSelect: (value) {
    // 这里处理选中状态变化逻辑,value为当前选中状态
    setState(() {
      _isChipSelected = value;
    });
  },
)

补充说明

ValueChanged<bool>是Flutter内置的函数类型别名,等价于void Function(bool),用它能让代码更贴合Flutter规范,同时直接和原生组件回调类型对齐,避免类型不匹配问题。

内容的提问来源于stack exchange,提问作者user22362195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:27:06