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

Flutter修改单个列表项标题致所有Tab文本同步变更问题求助

问题原因

你遇到的问题根源在于列表初始化方式错误:

  • 在Slider的onChanged回调中,你使用了List<WorkoutDay>.filled(_currentSliderValue.round(), WorkoutDay.newEmptyDay())创建训练日列表。
  • List.filled()的特性是:所有列表元素都会引用同一个对象实例。也就是说,你创建的所有WorkoutDay其实是同一个对象,修改其中任意一个的title属性,所有Tab都会显示相同内容——因为它们绑定的是同一个对象的title。
解决方案

把List.filled替换为List.generate,这样每个列表元素都会调用一次构造函数,生成独立的WorkoutDay实例:

1. 修改Slider的onChanged逻辑

将原来的代码:

workoutDays = List<WorkoutDay>.filled(
    _currentSliderValue.round(),
    WorkoutDay.newEmptyDay());

替换为:

workoutDays = List.generate(
    _currentSliderValue.round(),
    (index) => WorkoutDay.newEmptyDay());

2. 优化WorkoutDay构造函数(可选但推荐)

确保newEmptyDay每次都生成新实例,避免潜在问题:

class WorkoutDay {
  List<Exercise>? exercises;
  String title = 'Workout Day';
  
  // 改为工厂构造函数,明确返回新实例
  factory WorkoutDay.newEmptyDay() {
    return WorkoutDay('Workout Day', null);
  }
  
  WorkoutDay(this.title, this.exercises);
}

修改后的完整Slider代码片段

Slider(
  value: _currentSliderValue,
  max: 7,
  min: 1,
  divisions: 6,
  label: _currentSliderValue.round() == 1
      ? '${_currentSliderValue.round().toString()} day in a week'
      : '${_currentSliderValue.round().toString()} days in a week',
  onChanged: (double value) {
    setState(() {
      _currentSliderValue = value;
      // 用List.generate替代List.filled
      workoutDays = List.generate(
          _currentSliderValue.round(),
          (index) => WorkoutDay.newEmptyDay());
      _tabController = TabController(
          length: workoutDays.length, vsync: this);
    });
  },
),

修改后,每个训练日都是独立对象,修改某一个的title时,只有对应的Tab文本会更新,其他Tab不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:05:38