Neelay Srivastava
Neelay Srivastava

Reputation: 1221

How to get unique data from list of object in "dart"

When I save user location on local Database, I am successful in saving, however, when I retrieve the data, there are multiple data for each day. I want to eliminate redundancy by adding unique data in List and I am unable to do it.. please refer the cose snippet below, any leads is appreciated!

if (data != null) {
  for (int i = 0; i < data.length; i++) {
    if (!day.contains*(data[i].date)) {*
      day.add*(data[i]);
    }
  }
  daycount = data.length;
  print('count ${daycount}')*;
}

data model used

class Note {
  int _id;
  String _longitude;
  String _latitude;
  String _date;

Upvotes: 0

Views: 680

Answers (2)

jay mangukiya
jay mangukiya

Reputation: 11

              if (data != null) {
                List day = [];
                for (int i = 0; i < data.length; i++) {
                  day.add(data[i].date);
              }
                var dictinctsday =day.toSet().toList();
                print('filtered $dictinctsday');

              }

Upvotes: 0

loganrussell48
loganrussell48

Reputation: 1864

To eliminate duplicate values, you'll need a way to determine if 2 Note objects are "equal". You might say 2 Notes are equal if the id is the same. Or maybe the id and longitude and latitude have to all be the same. Maybe the date. It's up to you.

Basically you should override the the == operator, and the hashcode method. The == operator should return true if the hashcode method produces the same hashcode.

Once you've implemented this, you can add your Note objects to a Set instead of a List. A Set doesn't allow for duplicate values, and will use the == / hashcode features of the object to determine equality.

Upvotes: 1

Related Questions