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

Flutter使用flutter_fortune_wheel时FortuneBar如何自定义FortuneItem背景色

你遇到的FortuneBar自定义样式不生效的核心原因是指定了AlternatingStyleStrategy(),这个内置的样式策略会自动生成交替配色,直接覆盖你在单个FortuneItem上设置的style属性,所以自定义配置不会生效,也不会抛出错误。

你可以根据业务场景选择以下两种方案解决:


方案1:移除内置样式策略,直接给单个Item设置样式

如果不需要统一的交替样式逻辑,直接删除styleStrategy配置即可,组件会优先使用你给每个FortuneItem单独设置的样式:

FortuneBar(
  // 删掉AlternatingStyleStrategy配置即可
  selected: Stream.value(0),
  items: [
    FortuneItem(
      child: Text('A'),
      style: FortuneItemStyle(
        color: Colors.red, // 自定义样式正常生效
        borderColor: Colors.green,
        borderWidth: 3,
      ),
    ),
    FortuneItem(
      child: Text('B'),
      style: FortuneItemStyle(
        color: Colors.blue, // 按需配置第二个item的样式
        borderColor: Colors.yellow,
        borderWidth: 3,
      ),
    ),
  ],
)

方案2:自定义样式策略,保留交替逻辑的同时自定义配色

如果需要统一控制所有item的样式规则,可以自己实现StyleStrategy类,按自己的需求返回对应索引的item样式:

// 第一步:自定义样式策略类
class CustomFortuneBarStyleStrategy extends StyleStrategy {
  @override
  FortuneItemStyle getItemStyle(ThemeData theme, int index, int itemCount) {
    // 按索引自定义每个位置的item样式
    if (index == 0) {
      return const FortuneItemStyle(
        color: Colors.red,
        borderColor: Colors.green,
        borderWidth: 3,
      );
    } else if (index == 1) {
      return const FortuneItemStyle(
        color: Colors.blue,
        borderColor: Colors.yellow,
        borderWidth: 3,
      );
    }
    // 其他索引的通用样式规则
    return FortuneItemStyle(
      color: index.isOdd ? Colors.grey.shade200 : Colors.white,
      borderColor: Colors.black12,
      borderWidth: 1,
    );
  }
}

// 第二步:使用自定义的样式策略
FortuneBar(
  styleStrategy: CustomFortuneBarStyleStrategy(),
  selected: Stream.value(0),
  items: [
    FortuneItem(child: Text('A')),
    FortuneItem(child: Text('B')),
    // 其他item不需要重复设置style
  ],
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:15:03