skip to Main Content

I have a model class called Media, and I want to check if two lists of Media objects are equal. Below is the code for my Media model class and two example lists.

import 'package:equatable/equatable.dart';

class Media extends Equatable {
  final int id;
  final String title;

  Media({required this.id, required this.title});

  @override
  List<Object> get props => [id, title];
}
 
void main() {
  List<Media> list1 = [
    Media(id: 1, title: 'Media One'),
    Media(id: 2, title: 'Media Two'),
  ];

  List<Media> list2 = [
    Media(id: 1, title: 'Media One'),
    Media(id: 2, title: 'Media Two'),
  ];

  // How to compare list1 and list2 for equality?
}

I want to compare list1 and list2 to see if they contain the same elements with the same attributes, but the order of items in the lists does not matter. How can I do this?

Thank you for your help!

2

Answers


  1. Try the following snippet of code:

    bool areListsEqual(List<Media> list1, List<Media> list2) {
      // suppose there's no redundency in media
      if (list1.length != list2.length) {
        return false; // if it contains any redundency and you don't care about redundency just remoe this condition
      }
      bool flag = true;
    
      for (var media in list1) {
        if (!list2.contains(media)) {
          flag = false;
        }
      }
      if (!flag) {
        return flag;
      }
      for (var media in list2) {
        if (!list1.contains(media)) {
          flag = false;
        }
      }
      return flag;
    }
    
    Login or Signup to reply.
  2. Try below code hope its help to you. use toSet method for this. If you set the list vice-versa it also gives the status

    import 'package:equatable/equatable.dart';
    
    class Media extends Equatable {
      final int id;
      final String title;
    
      Media({required this.id, required this.title});
    
      @override
      List<Object> get props => [id, title];
    }
    
    void main() {
      List<Media> list1 = [
        Media(id: 1, title: 'Media One'),
        Media(id: 2, title: 'Media Two'),
      ];
    
      List<Media> list2 = [
        Media(id: 2, title: 'Media Two'),
        Media(id: 1, title: 'Media One'),
        
      ];
    
      bool listStatus = list1.toSet().containsAll(list2.toSet()) && 
                       list2.toSet().containsAll(list1.toSet());
    
      print('List Status- $listStatus');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search