Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: List remove not removing Object

Tags:

dart

The code is on DartPad if you need a complete example (see the while loop towards the end.)

I have a loop,

Place place = places[0];
while (places.isNotEmpty) {
  // Get a list of places within distance (we can travel to)
  List reachables = place.getReachables();

  // Get the closest reachable place
  Place closest = place.getClosest(reachables);

  // Remove the current place (ultimately should terminate the loop)
  places.remove(place);

  // Iterate
  place = closest;
}

But it's not removing place on the second-to-last line. i.e., the length of the places list remains the same, making it an infinite loop. What's wrong?

like image 541
Ganymede Avatar asked Sep 25 '22 21:09

Ganymede


2 Answers

This could be because the object in the list has a different hashCode from the object you are trying to remove.

Try using this code instead, to find the correct object by comparing the objects properties, before removing it:

var item = list.firstWhere((x) => x.property1== myObj.property1 && x.property2== myObj.property2, orElse: () => null);

list.remove(item);

Another option is to override the == operator and hashCode in your class.

class Class1 {
  @override
  bool operator==(other) {
    if(other is! Class1) {
      return false;
    }
    return property1 == (other as Class1).property1;
  }

  int _hashCode;
  @override
  int get hashCode {
    if(_hashCode == null) {
      _hashCode = property1.hashCode
    }
    return _hashCode;
  }
}
like image 178
live-love Avatar answered Nov 25 '22 05:11

live-love


I have faced the very same issue. Unfortunately I haven't found the root cause, but in the same situation I replaced

places.remove[place]

with

places.removeWhere(p => p.hachCode == place.hashCode)

as a workaround. One more approach was helpful too:

// Get the place from your set:
final place = places.first;
// Replace the place in the set:
places.add(place);
// Remove the place from the set:
places.remove(place);
like image 41
Kir Perepyolov Avatar answered Nov 25 '22 04:11

Kir Perepyolov