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

Time:12-08

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:

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.

CodePudding user response:

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"]));
}
  • Related