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

Flutter待办应用:如何在Card的ListTile左侧添加复选框

解决方法:利用ListTile的leading属性添加复选框

你不需要用Row/Column嵌套,也不用纠结child被占用的问题——ListTile本身提供了leading参数,专门用来放置列表项左侧的控件,直接把Checkbox放在这里就行。

修改后的代码示例:

Expanded(
  child: ListView.builder(
    itemCount: allTodo.length,
    itemBuilder: (context, index) {
      // 假设你的Todo模型有isDone字段用来标记完成状态
      final currentTodo = allTodo[index];
      return Card(
        child: ListTile(
          // 左侧添加复选框
          leading: Checkbox(
            value: currentTodo.isDone ?? false,
            onChanged: (bool? value) {
              setState(() {
                currentTodo.isDone = value ?? false;
                // 这里可以添加更新数据库/状态逻辑
              });
            },
          ),
          onTap: () {
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return AlertDialog(
                  title: Text("New ToDo"),
                  content: Container(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Form(
                          key: _formKey,
                          child: Column(
                            children: [
                              buildForm(_controllerTitle, "")
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  actions: [
                    TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: const Text(
                        "Cancel",
                      ),
                    ),
                    buildButton(Colors.indigo, updateObject),
                  ],
                );
              },
            );
            _controllerTitle.text = currentTodo.title;
            clickedTodoID = currentTodo.id!;
            setState(() {});
          },
          title: Text(currentTodo.title),
          trailing: GestureDetector(
            onTap: () {
              if (currentTodo.id != null) {
                _deleteTodo(currentTodo.id!, index);
                setState(() {});
              } else {
                print("id is null, cant perform Delete operation");
              }
            },
            child: Icon(Icons.delete),
          ),
        ),
      );
    },
  ),
),

关键说明:

  • ListTile的leading、title、trailing是官方设计的标准布局结构,不会引发布局冲突,比手动嵌套Row/Column更稳妥。
  • 确保你的Todo数据模型有一个布尔类型的字段(比如isDone)来存储复选框的选中状态,在onChanged回调里更新状态并调用setState刷新UI。
  • 如果之前用Row/Column报错,大概率是没有处理好布局约束(比如没有给控件指定尺寸、嵌套层级过多导致溢出),而ListTile已经帮你处理了这些布局细节。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:25:44