问题
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