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

Flutter如何获取Checkbox选中值并在汇总页面输出选中内容

第一步:修复现有代码的BUG

你现有的NVMe选项的Checkbox回调存在逻辑错误,选中NVMe时会错误修改SSD的选中状态,修改对应代码:

// 原来的错误代码
Checkbox(
  value: nvme,
  onChanged: (bool? value) {
    setState(() {
      ssd = value!; // 这里错误赋值给了ssd
    });
  },
),
// 修改为
Checkbox(
  value: nvme,
  onChanged: (bool? value) {
    setState(() {
      nvme = value!;
    });
  },
),

第二步:收集选中的存储项

在_NewSignState类中新增方法,用于筛选所有选中的存储类型,返回字符串列表:

List<String> getSelectedStorage() {
  List<String> storageList = [];
  if (ssd) storageList.add("SSD");
  if (hdd) storageList.add("HDD");
  if (nvme) storageList.add("NVMe");
  if (m2) storageList.add("M.2");
  return storageList;
}

第三步:修改路由传参,把选中的存储列表传到汇总页

首先修改你的PreviewSel页面的构造函数,新增参数接收选中的存储列表,示例如下:

class PreviewSel extends StatelessWidget {
  final String pcName;
  final String motherboard;
  final String ram;
  final String casing;
  // 新增存储列表参数
  final List<String> selectedStorage;
  // 修改构造函数
  const PreviewSel(this.pcName, this.motherboard, this.ram, this.casing, this.selectedStorage, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 页面展示逻辑,你可以自行排版存储列表,比如转成逗号分隔的字符串
    return Scaffold(
      appBar: AppBar(title: const Text("汇总信息")),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("电脑名称:$pcName"),
            const SizedBox(height: 8),
            Text("主板:$motherboard"),
            const SizedBox(height: 8),
            Text("内存:$ram"),
            const SizedBox(height: 8),
            Text("机箱:$casing"),
            const SizedBox(height: 8),
            // 展示选中的存储
            Text("选中的存储:${selectedStorage.join("、")}"),
          ],
        ),
      ),
    );
  }
}

然后修改NewSign页面的提交按钮跳转逻辑,把选中的存储列表传过去:

onPressed: () {
  Navigator.of(context).push(
    MaterialPageRoute(
      builder: (context) => PreviewSel(
        pcname.text,
        motherboard.text,
        ram.text,
        casing.text,
        // 传入选中的存储列表
        getSelectedStorage(),
      ),
    ),
  );
},

如果你希望在汇总页把每个存储选项单独换行展示,也可以用Column遍历渲染:

const Text("选中的存储:"),
const SizedBox(height: 4),
...selectedStorage.map((storage) => Text("- $storage")).toList(),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:30:05