How to get difference of lists in Flutter/Dart?

Technology CommunityCategory: FlutterHow to get difference of lists in Flutter/Dart?
VietMX Staff asked 3 years ago
Problem

Consider you have two lists [1,2,3,4,5,6,7] and [3,5,6,7,9,10]. How would you get the difference as output? eg. [1, 2, 4]

You can do something like this:

List<double> first = [1,2,3,4,5,6,7];
List<double> second = [3,5,6,7,9,10];
List<double> output = first.where((element) => !second.contains(element));

alternative answer:

List<double> first = [1,2,3,4,5,6,7];
List<double> second = [3,5,6,7,9,10];
List<double> output = [];

first.forEach((element) {
    if(!second.contains(element)){
    output.add(element);
}
});

//at this point, output list should have the answer

note that for both cases, you need to loop over the larger list.