skip to Main Content

I am new to dart so sorry if I’m missing something obvious
I’m writing a code to add elements to this Set<List> which works fine, but when I try to check if the element exists or to delete it does not work.

here’s the code

void main(List<String> args) {
  Set<List<double>> level1barriers = {};
  print(level1barriers);
  level1barriers.add([1, 1]);
  level1barriers.add([0.5, 0.3]);
  print(level1barriers);
  print(level1barriers.contains([1, 1]));
  level1barriers.remove([1, 1]);
  print(level1barriers);
}

3

Answers


  1. I used a variable instead and it worked

    void main(List<String> args) {
      Set<List<double>> level1barriers = {};
      print(level1barriers);
    
      List<double> list = [1,1];
    
      level1barriers.add(list);
      level1barriers.add([0.5, 0.3]);
      print(level1barriers);
      print(level1barriers.contains(list));
      level1barriers.remove(list);
      print(level1barriers);
    }
    

    Console :

    {}
    {[1, 1], [0.5, 0.3]}
    true
    {[0.5, 0.3]}
    
    Login or Signup to reply.
  2. Contains checks if one item is identically to another, so if you use the same exact object it will return true but if only the values is the same it wont.

    list1 = [1,1]
    list2 = [1,1]
    list1 == list2 -> Returns false.
    

    So, you have to options if you want a Set, one is instead of making a Set<List> make a Set and make that class have as an only object a List. And make it Equalable.

    Login or Signup to reply.
  3. As @Agustin Pazos included [1,1]==[1,1] will return false. It is checking reference instead of list items. You can use some packages, equatable is handle while working with model class.

    For this list issue I am using ListEquality.

    Set<List<double>> level1barriers = {};
      print(level1barriers);
      level1barriers.add([1, 1]);
      level1barriers.add([0.5, 0.3]);
      print(level1barriers);
    
      final eq = ListEquality();
      final item = level1barriers.firstWhere(
        (element) => eq.equals(element, [1, 1]),
      );
      level1barriers.remove(item);
      print(level1barriers);
    

    Will return

    {}
    {[1.0, 1.0], [0.5, 0.3]}
    {[0.5, 0.3]}
    

    Check this question for list equality

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search