Reputation: 39
One List is a List<String>?
and the other is a List<dynamic>
I'd prefer not to change these data types. I just want to check if the contents are the same.
If I have a List [1, 2, 3]
and a List [1, 2, 3]
the output of a bool should be true
If I have a List [1, 2, 3]
and a List [1, 3, 2]
the output of a bool should be true
If I have a List [1, 2, 4]
and a List [1, 2, 3]
the output of a bool should be false
Upvotes: 0
Views: 1375
Reputation: 4444
I recommend to use collection package with 564 like on pub.dev. to compare lists/maps/sets
i found from here https://stackoverflow.com/a/63633370/12838877
To compare list of integer and list of dynamic
import 'package:collection/collection.dart';
List<int> a = [1,2,4,5,6];
List<dynamic> b = [1,2,4,5,6];
List<dynamic> c = [1,4,5,6,2];
bool isEqual = DeepCollectionEquality().equals(a,b);
bool isEqual2 = DeepCollectionEquality().equals(a,c);
print(isEqual); // result is true without any error
print (isEqual2); // result is false , since its not ordered
UPDATE
if you want to compare 2 list dynamic unordered you can use code below
final unOrderedList = DeepCollectionEquality.unordered().equals(a,c);
print(unOrderedList); // result true
since its dynamic list, its also can compare between list that contain int,null, string ,list , etc,
List<dynamic> d = [1,"abc",2, null, ["a"], 4];
List<dynamic> e = [1,"abc",2, null, ["a"], 4];
final compare2list = DeepCollectionEquality.unordered().equals(d,e);
print(compare2list); // result true
Upvotes: 1
Reputation: 63769
I will sort in this case and check equal like
final e1 = [1, 2, 3]..sort();
final e2 = [1, 3, 2]..sort();
print(e1.equals(e2)); //true
Upvotes: 1
Reputation: 615
void main() {
List<int> a = [1, 2, 3];
List<dynamic> b = [1, 3, 3];
bool checkSame(List<dynamic> a, List<dynamic> b) {
var same = true;
if (a.length != b.length) {
same = false;
} else {
a.forEach((element) {
if (element.toString() != b[a.indexOf(element)].toString()) {
same = false;
}
});
}
return same;
}
bool val = checkSame(a, b);
print(val);
}
Upvotes: 0