I want to get the Index of the ListA with the name test in this list
First class
class ListA {
String name;
ListA({this.name});
}
Second class
List<ListA> abc = [
ListA(name: 'test'),
];
after that, i got a statless Wiget with a button, that is the onPressed-method
onPressed: () {
i = abc.indexOf(ListA(name: 'test'));
print(i);
},
I couldn´t find any misstakes, but unfortunately it´s always returning -1, what means it couldn´t find it
What am i doing wrong?
This happens because you're creating a new ListA
when calling indexOf
, and that means you have two different ListA
s. This is similar to doing:
print(ListA(name: 'test') == ListA(name: 'test'));
This will print false
because they're not the same object.
You could try one of the following:
ListA
you use, and call indexOf
passing the same reference inconst
instances of ListA
(mark the name
field as final
, add const
to the constructor definition and the calls to it)==
operator and hashCode
on your ListA
class, so that the two different instances of ListA
are considered the same if their fields/items are the sameindexOf
, use indexWhere
and check the name ( indexWhere((l) => l.name == 'test')
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.