我有一个这样的地图列表
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");
}
在DartPad上运行的结果是:索引:-1。 如何在列表中的Map对象中使用indexOf?谢谢
答案 0 :(得分:0)
这不起作用,因为两个映射不是同一对象,要解决此问题,可以使用const对象或使用indexWhere
使用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");
}
使用索引位置:
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");
}