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

Flutter ListView.builder动态生成Checkbox如何获取各复选框选中状态

解决方案

核心思路是状态提升,把复选框的选中状态同步到父组件层统一维护,具体修改步骤如下:

步骤1:修改自定义复选框组件,新增状态回调

给checkBox组件新增选中状态变化的回调参数,将当前项的选中状态同步给父组件:

class checkBox extends StatefulWidget {
  const checkBox({
    required this.text,
    required this.onSelectionChanged, // 新增回调参数
    this.initialValue = false, // 可选初始选中状态
  });
  final String text;
  final ValueChanged<bool> onSelectionChanged;
  final bool initialValue;

  @override
  State<checkBox> createState() => _CheckBoxState();
}

class _CheckBoxState extends State<checkBox> {
  late bool checkboxListTileValue;

  @override
  void initState() {
    super.initState();
    checkboxListTileValue = widget.initialValue; // 初始化状态
  }

  @override
  Widget build(BuildContext context) {
    return CheckboxListTile(
      value: checkboxListTileValue,
      onChanged: (newValue) {
          setState(() => checkboxListTileValue = newValue!);
          widget.onSelectionChanged(newValue); // 触发回调同步状态到父组件
      },
      title: Text(
        widget.text,
        style: MainTheme.title2.override(
          fontFamily: 'Montserrat',
          fontWeight: FontWeight.w400,
          fontSize: 16,
        ),
      ),
      tileColor: MainTheme.tertiaryColor,
      activeColor: MainTheme.primaryColor,
      checkColor: MainTheme.tertiaryColor,
      controlAffinity: ListTileControlAffinity.trailing,
    );
  }
}

步骤2:父组件维护选中状态集合

在父组件中定义一个集合保存所有选中的项,在回调中更新这个集合即可随时获取选中内容:

// 父组件中先定义保存选中项的集合
Set<String> selectedIncidencias = {};

// 原列表生成代码修改为如下
return SlideTile(
    title: "Incidencia del solicitante",
    listBuilder: Container(
        height: MediaQuery.of(context).size.height * 0.25,
        child: MediaQuery(
            data: MediaQuery.of(context).removePadding(
              removeTop: true,),
            child: ListView.builder(
                padding: EdgeInsets.fromLTRB(
                    10, 0, 10, 5),
                primary: false,
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: blocAssistant.incidencias_solicitante.length,
                itemBuilder: (context, index) {
                  final currentText = blocAssistant.incidencias_solicitante[index];
                  return checkBox(
                    text: currentText,
                    // 传入初始状态:如果当前文本在选中集合里就是选中状态
                    initialValue: selectedIncidencias.contains(currentText),
                    onSelectionChanged: (isSelected) {
                      setState(() {
                        if (isSelected) {
                          selectedIncidencias.add(currentText);
                        } else {
                          selectedIncidencias.remove(currentText);
                        }
                      });
                      // 这里可以实时拿到最新的选中集合做其他逻辑
                      debugPrint("当前选中项:$selectedIncidencias");
                    }
                  );
                }
            )
        )
    ),
    desc: "Aqui debe indicar el tipo de error de la incidencia.",
  );

后续使用

需要获取所有选中项时,直接读取selectedIncidencias集合即可,集合里存储的就是所有被选中的复选框对应的文本内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:06:06