Dart:未捕获错误:RangeError(index):索引超出范围:索引应小于7:7

44u64gxh  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(91)

我有两个名单。我想从列表2中找到不匹配的数据,然后将列表2中的数据添加到列表3中,并使用num:list2数据和名称“z”

void main() {
   List list1 = [
    {"num": 1, "name": "a"},
    {"num": 2, "name": "b"},
    {"num": 2, "name": "b"},
    {"num": 3, "name": "c"},
    {"num": 3, "name": "c"},
    {"num": 4, "name": "d"},
    {"num": 5, "name": "e"},
    {"num": 6, "name": "f"},
    {"num": 6, "name": "f"},
    {"num": 7, "name": "g"},
    {"num": 8, "name": "h"},
    {"num": 9, "name": "i"},
    {"num": 10, "name": "j"},
    {"num": 10, "name": "j"},
  ];

  List list2 = [1, 3, 10, 30, 40, 50, 60];

  List list3 = [];
  for (int i = 0; i <= list2.length; i++) {
    list1.forEach((data) {
      if (data["num"] == list2[i]) {
        list3.add(data);
      }
    });
    list3.add({"num": list2[i], "name": "Z"});
  }
  print(list3);
}

字符串
我希望输出像这样的list3

[
    {"num": 1, "name": "a"},
    {"num": 2, "name": "b"},
    {"num": 2, "name": "b"},
    {"num": 3, "name": "c"},
    {"num": 3, "name": "c"},
    {"num": 4, "name": "d"},
    {"num": 5, "name": "e"},
    {"num": 6, "name": "f"},
    {"num": 6, "name": "f"},
    {"num": 7, "name": "g"},
    {"num": 8, "name": "h"},
    {"num": 9, "name": "i"},
    {"num": 10, "name": "j"},
    {"num": 10, "name": "j"},
    {"num": 30, "name": "z"},
    {"num": 40, "name": "z"},
    {"num": 50, "name": "z"},
    {"num": 60, "name": "z"},
  ];

yyyllmsg

yyyllmsg1#

只需更改i < list2.length

void main() {
  List list1 = [
    {"num": 1, "name": "a"},
    {"num": 2, "name": "b"},
    {"num": 2, "name": "b"},
    {"num": 3, "name": "c"},
    {"num": 3, "name": "c"},
    {"num": 4, "name": "d"},
    {"num": 5, "name": "e"},
    {"num": 6, "name": "f"},
    {"num": 6, "name": "f"},
    {"num": 7, "name": "g"},
    {"num": 8, "name": "h"},
    {"num": 9, "name": "i"},
    {"num": 10, "name": "j"},
    {"num": 10, "name": "j"},
  ];

  List list2 = [1, 3, 10, 30, 40, 50, 60];

  List list3 = [];
  final setList1 = Set<int>();
  list1.forEach((data) {
    setList1.add(data['num']);
    list3.add(data);
  });

  for (int i = 0; i < list2.length; i++) {
    if (!setList1.contains(list2[i])) {
      list3.add({"num": list2[i], "name": "Z"});
    }
  }
  print(list3);
}

字符串

相关问题