Can't use indexOf in List of Map in DART

断了今生、忘了曾经 提交于 2021-01-28 19:30:41

问题


I have a List of Map like this

List<Map<String, String>> data = [
  {"id":"1", "name":"Job"},
  {"id":"2", "name":"Teh"},
  {"id":"3", "name":"Maru"},
  {"id":"4", "name":"Pam"},
];

void main() {
  var index = data.indexOf({"id":"1", "name":"Job"});
  print("Index: $index");
}

Result run on DartPad was: Index: -1. How can I using indexOf for Map object in List? Thanks


回答1:


It doesn't work because the two maps aren't the same Object, to solve that, you can either use const objects or use indexWhere

With const:

// Create a const (immutable) list.
List<Map<String, String>> data = const [
  {"id":"1", "name":"Job"},
  {"id":"2", "name":"Teh"},
  {"id":"3", "name":"Maru"},
  {"id":"4", "name":"Pam"},
];

void main() {
  // Search for the map.
  var index = data.indexOf(const {"id":"1", "name":"Job"});
  print("Index: $index");
}

Using indexWhere:

List<Map<String, String>> data = const [
  {"id":"1", "name":"Job"},
  {"id":"2", "name":"Teh"},
  {"id":"3", "name":"Maru"},
  {"id":"4", "name":"Pam"},
];

void main() {
  // Index where id is 1 and name is Job.
  var index = data.indexWhere((e) => e["id"] == "1" && e["name"] == "Job");
  print("Index: $index");
}


来源:https://stackoverflow.com/questions/58956044/cant-use-indexof-in-list-of-map-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!