PAYATHON 2026

移除 Flutter FilterChip 中非 splashColor 的多余青色按压背景

数据小陈

结论:这个青色大概率来自 Material 3 下 FilterChip 在按压或选中过渡时读取的 ColorScheme.secondary、secondaryContainer 或 InkWell overlay 默认值,和 splashColor 关系不大。你的 ColorScheme.light 只覆盖了 primary 和 onPrimary,secondary 系列没动,而 Flutter 默认的 secondary 偏青,按压时就会露出来。只改 selectedColor、backgroundColor、surfaceTintColor 不够,因为 pressed、hovered、focused 等状态仍可能回落到主题默认色。

原因

FilterChip 的最终背景和按压反馈不只由 selectedColor 决定。Material 3 里,Chip 的选中色、状态 overlay 和水波纹会从 ChipThemeData、ColorScheme 以及 ThemeData.splashColor/highlightColor 等来源组合取色。原代码把 chipTheme.selectedColor 改成 primaryContainer,但 ColorScheme.light 里的 secondary 仍是默认值,按压状态就可能短暂显示青色。

解决步骤

  1. 在 ColorScheme 中把 secondary、onSecondary、secondaryContainer、onSecondaryContainer 一起改成红色系,或者直接用 ColorScheme.fromSeed(seedColor: Colors.red)。
  2. 给 FilterChip 设置 color,用 WidgetStateProperty.resolveWith 覆盖 pressed、hovered、focused、selected 等状态,确保按压时返回透明或目标色。
  3. 在 ThemeData 或局部 Theme 中把 splashColor、highlightColor、hoverColor、focusColor 设为 Colors.transparent 或红色系,避免 InkWell overlay 回落到默认青色。
  4. 保留 selectedColor 和 checkmarkColor,但不要让按压状态只依赖 selectedColor。

示例代码

先改主题里的颜色方案和水波纹颜色:

theme: ThemeData(
  useMaterial3: true,
  brightness: Brightness.light,
  primaryColor: Colors.red,
  scaffoldBackgroundColor: Colors.white,
  colorScheme: const ColorScheme.light(
    brightness: Brightness.light,
    primary: Colors.red,
    onPrimary: Colors.white,
    secondary: Colors.red,
    onSecondary: Colors.white,
    secondaryContainer: Color(0x1FFF0000),
    onSecondaryContainer: Colors.red,
  ),
  splashColor: Colors.transparent,
  highlightColor: Colors.transparent,
  hoverColor: Colors.transparent,
  focusColor: Colors.transparent,
),

再给 FilterChip 加 color 状态控制:

FilterChip(
  label: Text('$icon $label'),
  selected: isSelected,
  onSelected: (selected) {
    setState(() {
      if (selected) {
        _selectedCategories.add(label);
      } else {
        _selectedCategories.remove(label);
      }
    });
  },
  selectedColor: theme.colorScheme.primaryContainer.withAlpha(20),
  checkmarkColor: theme.colorScheme.primary,
  showCheckmark: true,
  color: WidgetStateProperty.resolveWith<Color?>((states) {
    if (states.contains(WidgetState.pressed)) {
      return Colors.transparent;
    }
    if (states.contains(WidgetState.hovered)) {
      return Colors.transparent;
    }
    if (states.contains(WidgetState.focused)) {
      return Colors.transparent;
    }
    if (states.contains(WidgetState.selected)) {
      return theme.colorScheme.primaryContainer.withAlpha(20);
    }
    return Colors.transparent;
  }),
)

注意事项

  • Flutter 3.19 及以上使用 WidgetState 和 WidgetStateProperty;较旧版本请换成 MaterialState 和 MaterialStateProperty。
  • 如果仍然出现青色,先检查父级 Theme 是否又把 colorScheme.secondary 覆盖回去,别只盯着 chipTheme。
  • 别只把 selectedColor 设成透明;按压状态走的是独立 overlay,得单独处理。
  • 如果确认是 InkWell 水波纹造成的,可以额外设置 splashFactory: NoSplash.splashFactory 彻底关闭水波纹,但这会一并影响同一主题下的其他组件。

备注:内容仅供参考。