I’m creating an Iterable extension in dart to mimick most of the methods of List.
However, when trying to remove an item from an iterable, I sometimes run into a problem where I can’t remove specific types of objects.
The code below works for native types such as int,string, but not for custom types
extension Iterables<E> on Iterable<E> {
Iterable<E> remove(E item) {
try {
return toList()..remove(item);
// this.removeWhere((p0) => p0 == item);
} catch (e) {
print(e);
return [];
}
}
}
How can I solve this issue?
To be clear: I want this to be a void function instead of creating a new copy!
Thanks!
The problem I’m trying to solve:
// my collection is a list
List<myType> x = [...manyItems]
x.map(someMap).toList();
// I want it to be an Iterable instead so that I don't have to do .toList()
// My iterable extension is missing the remove capabilities the list class has
2
Answers
The "custom types" used in this methods needs to be equal and if you don’t override the
operator ==
or thehashCode
of these classes, dart considers two "custom types" equals if the instance of object is the same.Saying that, you can:
Since you are working with custom types and the remove method is not working as expected, chances are the equality comparison is failing.
In this case, you should do one of the below:
Below is a sample on how to do option 1 mentioned above:
Some random tip:
A better way to make the code more readable and idiomatic – consider using the
where
method directly, as it is more declarative and clear about creating a newIterable
.