[Solved] Remove list of Objects from other list of objects in flutter

Question

Asked by Adil N on December 13, 2021 (source).

I want to get availableSlots = allSlots-bookedSlots and here is the code, Please help!

final List<timeSlot> allSlots=
[
TimeSlot(time: '6PM-7PM', isSelected: false),
TimeSlot(time: '7PM-8PM', isSelected: false),
TimeSlot(time: '8PM-9PM', isSelected: false),
];
final List<timeSlot> bookedSlots=
[
TimeSlot(time: '6PM-7PM', isSelected: false),
TimeSlot(time: '7PM-8PM', isSelected: false),
];

here is the TimeSlot class

  class TimeSlot {
  String time;
  bool isSelected;

  TimeSlot({this.isSelected, this.time});
}

Answer

Question answered by KuKu (source).

At first override '==' operator to compare two TimeSlot values.

And filter bookedSlots item from allSlots to get availableSlots.

enter image description here

void main() {
  final List<TimeSlot> allSlots=
  [
    TimeSlot(time: '6PM-7PM', isSelected: false),
    TimeSlot(time: '7PM-8PM', isSelected: false),
    TimeSlot(time: '8PM-9PM', isSelected: false),
  ];
  final List<TimeSlot> bookedSlots=
  [
    TimeSlot(time: '6PM-7PM', isSelected: false),
    TimeSlot(time: '7PM-8PM', isSelected: false),
  ];
  
  
  List<TimeSlot> availableSlots = allSlots.where((item) => !bookedSlots.contains(item)).toList();
  print(allSlots);
  print(availableSlots);
}

 class TimeSlot {
  String? time;
  bool? isSelected;

  TimeSlot({this.isSelected, this.time});
   
  @override
  bool operator==(Object other) {
    return other is TimeSlot && other.time == time &&other.isSelected == isSelected;
  }
   
   
   @override
  String toString() => '''TimeSlot {
     time: $time,
     isSelected: $isSelected,
  }''';
   

   @override
   int get hashCode => Object.hash(time, isSelected);
   
}


DART FLUTTER LIST
SHARE: