Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my list equal check not working when they look the same in Flutter?

Part of my Flutter program creates a list and later checks to see if the list is equal to another. However, when I test this, it returns false. I’ve done a series of printout statements to check why they aren’t equal and they look the same, but it keeps returning false.

The code:

print("programList: " + programList.toString());
//print(programList.runtimeType);
var testResult = (programList == ["apple", "apple", "banana"]);
print("programList are correct: " + testResult.toString());
for(var i in programList){
  print(i + ": " + i.runtimeType);
}
if(programList == ["apple", "apple", "banana"]){
  print("in test loop");
  //do stuff
}

This is the print out:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I/flutter ( 1429): programList: \[apple, apple, banana\]
I/flutter ( 1429): programList are correct: false

Exception caught by gesture
The following \_TypeError was thrown while handling a gesture:
type '\_Type' is not a subtype of type 'String' of 'other'

The error didn’t start showing up until the runtimeType for loop, but before that, it didn’t print "in test loop".

I tried adding all of those print statements to see what was happening. I tried adding runtimeTypes to try to understand if they were coming up with different types, but that caused an error of it’s own.

>Solution :

Because dart’s default is to compare the objects by reference. As the result, you have different references for 2 arrays with the same values.

To make it work you have to use DeepCollectionEquality

import 'package:collection/collection.dart';

void main() {
  Function equality = const DeepCollectionEquality().equals;
  final programList = ["apple", "apple", "banana"];
  print(equality(programList, ["apple", "apple", "banana"]));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading