Home > Software engineering >  How to remove a specific object from a list in dart/flutter?
How to remove a specific object from a list in dart/flutter?

Time:10-03

I have a list called selected list of type dynamic and it holds a list of objects, each objects contains from a teacher ID & index.

I want to check if this list contains the same Id & index, if it does i want to remove this object from the list.

here is my code ....

void addTeacher(int teacherId, int index) {

if (this.selectedList.contains({     **/// the problem is here**    })) {

  this.selectedList.remove({teacherId, index});
  this.myColor = Colors.grey;
  print('removed teacher => ${teacherId.toString()}');

} else {

  this.selectedList.add({teacherId, index});
  this.myColor = AsasColors().blue;
  print('added teacher => ${teacherId.toString()}');

}

notifyListeners();
print(selectedList);

}

how can i achive this ?

CodePudding user response:

Contains and remove use the == operator which in this case will return false because unless you override it for a specific class it will compare by reference. You can use indexWhere to find out if an item is in a list based on a compare function like that (if the function returns -1 the item is not on the list:

// Index different than -1 means the item is found somewhere in the list
final teacherIndex = this.selectedList.indexWhere((teacher) => teacher['teacherId'] == teacherId);
if (teacherIndex != -1) {
  this.selectedList.removeAt(teacherIndex);
  this.myColor = Colors.grey;
  print('removed teacher => ${teacherId.toString()}');
} else {
  ...
}

CodePudding user response:

I have implemented it and it worked fine
[The code] [The output:]

This is the written code:

class Subject {
  int? teacherID;
  int? subjectID;
  Subject(this.teacherID, this.subjectID);

  @override
  String toString() => "Subject {teacherID: $teacherID, subjectID: $subjectID";

  //TODO: Change your needed criteria here..
  @override
  bool operator ==(Object other) =>
      other is Subject &&
      teacherID == other.teacherID &&
      subjectID == other.subjectID;
}

void addSubject(List<Subject> list, Subject subject) {
  if (list.contains(subject)) {
    list.remove(subject);
  } else {
    list.add(subject);
  }
}

void main() {
  List<Subject> selectedList =
      List.generate(10, (index) => Subject(index   1, index   1));

  print("SelectedList = $selectedList");

  addSubject(selectedList, Subject(11, 11));
  addSubject(selectedList, Subject(11, 12));
  addSubject(selectedList, Subject(12, 11));
  addSubject(selectedList, Subject(12, 12));
  print("SelectedList2 = $selectedList");

  addSubject(selectedList, Subject(12, 12));
  print("SelectedList3 = $selectedList");
}

Sincerely, accept the answer if it worked for you.

  • Related