skip to Main Content

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


  1. The "custom types" used in this methods needs to be equal and if you don’t override the operator == or the hashCode of these classes, dart considers two "custom types" equals if the instance of object is the same.

    Saying that, you can:

    1. override the operator ==;
    2. make them extends/implements Comparable; or
    3. uses Equatable (that’s what I use).
    Login or Signup to reply.
  2. 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:

    1. Override the == operator and hashCode property in your custom class to ensure correct equality comparisons.
    2. Use the equatable package.

    Below is a sample on how to do option 1 mentioned above:

    class CustomType {
      final int id;
    
      CustomType(this.id);
    
      @override
      bool operator ==(Object other) {
        if (identical(this, other)) return true;
        return other is CustomType && other.id == id;
      }
    
      @override
      int get hashCode => id.hashCode;
    }
    

    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 new Iterable.

    extension Iterables<E> on Iterable<E> {
      Iterable<E> remove(E item) {
        return this.where((e) => e != item);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search