如何一次只选中/选中一个复选框?

enter image description here

下面是我的代码

Container(
    child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
            Checkbox(
                checkColor: Colors.white,
                value: isChecked,
                onChanged: (bool value) {
                    setState(() {
                        isChecked = value;
                        // ignore: unnecessary_statements
                        passData(certId);
                    });
                },
            ),
        ],
    )),

推荐答案

Option1 - Using a map to maintain the state

创建 map :

final Map<int, bool> _state = {};

然后,判断该索引的值是否为true/false:

return ListView.builder(itemBuilder: (context, index) {
      return CheckboxListTile(
        value: _state[index] ?? false,
        onChanged: (value) {
          setState(() {
            _state[index] = value!;
          });
        },
        title: Text(_data[index].text),
      );
    });

选项2--使用模型:

class CheckBoxModel {
  bool isChecked = false;
  String text = "";
  CheckBoxModel({required this.isChecked, required this.text});
}

然后,生成包含30个小部件的列表:

final _data = List.generate(
    30, (index) => CheckBoxModel(isChecked: false, text: "Item $index"));

现在,使用ListView.builder并基于index更新相应的值:


class Testing extends StatefulWidget {
  const Testing({Key? key}) : super(key: key);

  @override
  State<Testing> createState() => _TestingState();
}

class _TestingState extends State<Testing> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(itemBuilder: (context, index) {
      return CheckboxListTile(
        value: _data[index].isChecked,
        onChanged: (value) {
          setState(() {
            _data[index].isChecked = value!;
          });
        },
        title: Text(_data[index].text),
      );
    });
  }
}

See also

Expansion tile trailing icon updates all in list on interaction with one tile. How can I only change the icon for the expanded tile?

Flutter相关问答推荐

未处理异常:字符串类型不是值类型子类型的子类型'

自动测试Flutter应用程序进行QA的最佳方法是什么?

如何使用底部导航栏修复此导航问题

如何使用新的Riverpod语法将依赖传递给AsyncNotifier?

相同的Flutter 代码库,但Firebase登录适用于Web应用程序,但无法登录iOS应用程序

为什么我的PIN字段在第一次打字时不显示数字?

Android Studio扩展控件上未加载Google map

如何使DropDownMenu宽度等于TextFormfield?

如何在Flutter 中使用选定的键和值从 map 列表创建 map

Flutter CarouselSlider中如何防止右图与放大的中心图重叠?

如何从Firebase登录获取用户信息,如电话号码、出生日期和性别

无状态小部件被奇怪地重建

Android 模拟器在 Apple M2 芯片 EXC_BAD_ACCESS / KERN_INVALID_ADDRESS 上随机崩溃

如何在android中 Select 任何文件/文件路径 - Flutter

应用程序包含嵌入式私钥或密钥库文件

graphql_flutter 错误:非抽象类GraphQLWebSocketChannel缺少实现

如何在 Flutter 中滚动时为多个小部件设置动画

在 Dart 中使用隔离时访问外部范围内的变量

Flutter 中的无效日期格式 2022 年 11 月 14 日

如何判断 text.contains() 是否包含多个值