skip to Main Content
List a = [

AbsentModel(name: "abir", id: 1),
AbsentModel(name: "fahim", id: 2),
AbsentModel(name: "rahim", id: 3),
AbsentModel(name: "akash", id: 4), ]


List b = [
AbsentModel(name: "akash", id: 4),
AbsentModel(name: "fahim", id: 2),
AbsentModel(name: "rahim", id: 3),]

`
I need the output of –
the difference between List a and List b

result –

`List c = [ AbsentModel(name: "abir", id: 1),];

I have tried to toSet() but it only can give me the result If i made all list without model.
Like if made simple id List then it works.
But can not get the difference when I am using model data.

2

Answers


  1. This code would work fine as others. You just need to use equatable package.

    void main() {
      List a = [
    
    AbsentModel(name: "abir", id: 1),
    AbsentModel(name: "fahim", id: 2),
    AbsentModel(name: "rahim", id: 3),
    AbsentModel(name: "akash", id: 4), ]
    
    
    List b = [
    AbsentModel(name: "akash", id: 4),
    AbsentModel(name: "fahim", id: 2),
    AbsentModel(name: "rahim", id: 3),]
    
      List<AbsentModel> c = a.where((item) => !b.contains(item)).toList();
      print(c); 
    }
    

    However, you need to redefine the AbsentModel as follows:

    import 'package:equatable/equatable.dart';
    
    class AbsentModel extends Equatable {
        final String name;
        final int id;
    
        AbsentModel({required this.name, required this.id,});
    
        @override
        List<Object> get props => [name, id];
    }
    

    Equatable overrides == and hashCode for you so you don’t have to waste your time writing lots of boilerplate code.

    Login or Signup to reply.
  2. The first answer is correct, but does not take into account the fact that the deviating value would not be recognised if it were in list b.

    This solution is similar to the above one, but checks the difference from a to b and from b to a. Also it is written as an extension for generic List, so it can be used for all kind of lists.

    extension Difference<T> on List<T> {
      List<T> difference(List<T> to) {
        final diff = where((item) => !to.contains(item)).toList();
        diff.addAll(to.where((item) => !contains(item)));
        return diff;
      }
    
    main() {
    ...
      final diff = a.difference(b);
    }
    

    Also you do not have to use the Equatable package (if you don’t want to), since you could overload the == operator:

    class AbsentModel {
      final String name;
      final int id;
    
      AbsentModel({required this.name, required this.id});
    
      @override
      bool operator ==(Object other) {
        return (other is AbsentModel) && other.id == id && other.name == name;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search