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

Dart如何获取自定义列表变量名并匹配填充对应数值

问题原因

Dart在运行时默认无法直接获取普通变量的字面名称,你存入listFilled的只是列表对象的引用,已经和最初的listA/listB/listD变量名没有绑定关系,所以无法直接从遍历到的f对象上拿到它对应的原始变量名。

解决方案

你可以先构建一个名称-列表的映射表,先基于映射完成填充,再生成你需要的listFilled结构即可,完整可运行代码如下:

void main() {
  var listRaw = [
    {
      "listName": "listA",
      "listValue": [1, 2, 3]
    },
    {
      "listName": "listB",
      "listValue": [4, 5, 6]
    },
    {
      "listName": "listC",
      "listValue": [7, 8, 9]
    }
  ];

  List<int> listA = [];
  List<int> listB = [];
  List<int> listD = [];

  // 构建名称和对应列表的映射
  final nameToList = {
    "listA": listA,
    "listB": listB,
    "listD": listD,
  };

  // 遍历原始数据填充匹配的列表
  for (final r in listRaw) {
    final targetList = nameToList[r['listName'] as String];
    if (targetList != null) {
      targetList.addAll(r['listValue'] as List<int>);
    }
  }

  // 生成需要的listFilled结构
  List<List<int>> listFilled = [listA, listB, listD];

  print(listFilled); // 输出: [[1, 2, 3], [4, 5, 6], []]
}

可选扩展方案

如果后续需要更灵活的绑定逻辑,也可以自定义类存储名称和列表的关联关系,示例如下:

class NamedList {
  final String name;
  final List<int> list;
  NamedList(this.name, this.list);
}

void main() {
  var listRaw = [
    {
      "listName": "listA",
      "listValue": [1, 2, 3]
    },
    {
      "listName": "listB",
      "listValue": [4, 5, 6]
    },
    {
      "listName": "listC",
      "listValue": [7, 8, 9]
    }
  ];

  final namedLists = [
    NamedList("listA", []),
    NamedList("listB", []),
    NamedList("listD", []),
  ];

  for (final r in listRaw) {
    final match = namedLists.where((e) => e.name == r['listName']);
    if (match.isNotEmpty) match.first.list.addAll(r['listValue'] as List<int>);
  }

  final listFilled = namedLists.map((e) => e.list).toList();
  print(listFilled); // 同样输出期望结果
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 15:48:03