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

Flutter动态ListView问题:添加新练习时复用已有组,需初始0组

问题解决:新增练习初始为0组

你的核心问题是所有练习共用了同一个sets列表,导致新添加的练习会自动带上之前练习的组数据。要让每个练习独立管理自己的组,需要用数据类封装每个练习的信息。

步骤1:定义练习数据类

创建一个类来封装练习名称和对应的组列表,确保每个练习初始时组列表为空:

class Exercise {
  String name;
  List<String> sets;

  // 构造函数,初始化时组列表为空(0组)
  Exercise(this.name) : sets = [];
}

步骤2:替换原有的列表

把原来存储练习名称的List<String> litems = []替换为存储练习对象的列表:

List<Exercise> exercises = [];

步骤3:修改添加练习的逻辑

无论是通过TextField提交还是点击"Add Exercises"按钮,都要创建新的Exercise对象:

// TextField提交逻辑修改
onSubmitted: (text) {
  exercises.add(Exercise(text));
  eCtrl.clear();
  setState(() {});
},

// "Add Exercises"按钮逻辑修改
onPressed: () {
  exercises.add(Exercise("new"));
  setState(() {});
},

步骤4:调整列表渲染和组操作逻辑

在ListView.builder中,每个练习对应自己的组列表,修改内部的组渲染、添加、删除逻辑:

Expanded(
  child: ListView.builder(
    itemCount: exercises.length,
    itemBuilder: (BuildContext ctxt, int index) {
      // 获取当前练习对象
      final currentExercise = exercises[index];
      return Card(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: ExpansionTile(
            initiallyExpanded: true,
            title: Text(
              currentExercise.name,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            subtitle: Row(
              children: [
                Expanded(child: Text(" ")),
              ],
            ),
            children: <Widget>[
              ListView.builder(
                shrinkWrap: true,
                // 用当前练习的组列表长度
                itemCount: currentExercise.sets.length,
                itemBuilder: (BuildContext context, int index1) {
                  return Dismissible(
                    key: UniqueKey(),
                    direction: DismissDirection.endToStart,
                    onDismissed: (_) {
                      setState(() {
                        // 删除当前练习的对应组
                        currentExercise.sets.removeAt(index1);
                      });
                    },
                    child: Card(
                        elevation: 0,
                        child: Padding(
                            padding: EdgeInsets.all(1),
                            child: ListTile(
                              title: Text(
                                " ",
                                style: const TextStyle(
                                  fontSize: 10,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              subtitle: Row(
                                children: [
                                  Expanded(child: Text(" ")),
                                  Expanded(child: TextField(decoration: decoratedField)),
                                  Expanded(child: TextField(decoration: decoratedField)),
                                  Expanded(child: TextField(decoration: decoratedField)),
                                ],
                              ),
                            ))),
                    background: Container(
                        color: Colors.red,
                        margin: const EdgeInsets.symmetric(horizontal: 15),
                        alignment: Alignment.centerRight,
                        child: const Text("Delete", style: TextStyle(color: Colors.white))),
                  );
                },
              ),
              Padding(
                padding: EdgeInsets.all(10),
                child: ElevatedButton(
                  onPressed: () {
                    setState(() {
                      // 给当前练习添加组
                      currentExercise.sets.add('sets-test');
                    });
                  },
                  child: const Text('+ Add Set'),
                ),
              ),
              const SizedBox(height: 5),
            ],
            leading: IconButton(
              icon: const Icon(Icons.close, color: Colors.red),
              onPressed: () {
                setState(() {
                  exercises.removeAt(index);
                });
              },
            ),
          ),
        ),
      );
    },
  ),
)

效果说明

修改后,每个练习都拥有独立的组列表,新添加的练习初始时组列表为空(0组),不会再复制上一个练习的组数据。

内容的提问来源于stack exchange,提问作者Jesper Egsgaard Nielsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:50:25