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

Flutter中基于Map构建带下拉选择的可取值表格实现问题咨询

Flutter 带下拉选择表格实现方案

1. 基础数据与状态定义

首先定义两类全局状态:下拉选项列表、每行选中值存储结构,和你原有数据结构配合使用:

// 原有嵌套Map数据
var data = {
  'CT': {
    's1': {
      1001: 3,
      1002: 6,
      1003: 3,
      1004: 3,
      1008: 4,
      1009: 2,
    },
  }
};

// 全局统一下拉选项,可按需修改内容
final List<String> dropdownOptions = ['普通', '良好', '优秀', '不及格'];

// 存储每行选中的下拉值,key为课程code,value为选中的字符串选项
Map<int, String?> selectedOptionMap = {};

2. DataTable组件渲染逻辑

直接遍历最内层的code-credit键值对生成表格行,每行自动挂载对应下拉框:

@override
Widget build(BuildContext context) {
  return Column(
    children: [
      DataTable(
        columns: const [
          DataColumn(label: Text('Code')),
          DataColumn(label: Text('Credit')),
          DataColumn(label: Text('评级')),
        ],
        // 遍历内层Map生成行
        rows: data['CT']!['s1']!.entries.map((entry) {
          final code = entry.key;
          final credit = entry.value;
          // 初始化当前行选中值(无值时默认空)
          if (!selectedOptionMap.containsKey(code)) {
            selectedOptionMap[code] = null;
          }
          return DataRow(cells: [
            DataCell(Text(code.toString())),
            DataCell(Text(credit.toString())),
            DataCell(
              DropdownButton<String>(
                value: selectedOptionMap[code],
                hint: const Text('请选择'),
                isExpanded: true,
                items: dropdownOptions.map((option) {
                  return DropdownMenuItem(
                    value: option,
                    child: Text(option),
                  );
                }).toList(),
                onChanged: (value) {
                  setState(() {
                    selectedOptionMap[code] = value;
                  });
                },
              ),
            ),
          ]);
        }).toList(),
      ),
      // 提交按钮
      ElevatedButton(
        onPressed: getAllTableData,
        child: const Text('获取全部数据'),
      )
    ],
  );
}

3. 全量数据获取方法

按钮点击时调用该方法,即可拿到所有行的code、credit、选中值的集合:

void getAllTableData() {
  List<Map<String, dynamic>> tableData = [];
  data['CT']!['s1']!.forEach((code, credit) {
    tableData.add({
      'code': code,
      'credit': credit,
      'selectedOption': selectedOptionMap[code],
    });
  });
  // tableData即为所需的全部数据,可直接传入后续计算逻辑
  debugPrint(tableData.toString());
}

适配说明

如果外层CT、s1层级为动态值,额外加一层嵌套遍历拿到最内层的code-credit集合即可,核心渲染和数据获取逻辑不变。如果下拉选项需要和行的code/credit做关联,修改DropdownMenuItem的生成逻辑传入对应参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:54:02