I am learning on how to use lookup in Flutter, this is an example that I came across.
void main() {
Map<List<String>, String> lookup = {
['foo', 'bar']: 'foobar',
['baz', 'qux']: 'bazqux',
['hello', 'world']: 'helloworld',
};
List<String> key = ['foo', 'bar'];
String? result = lookup[key];
if (result != null) {
print('Result: $result');
} else {
print('No match found for $key');
}
}
But the problem is the result is ‘No match found for [‘foo’,’bar’], although the code is correct. It is supposed to return ‘foobar’ as the result, but I am not sure where the problem is and how to fix it.
5
Answers
From the documentation…Lists are, by default, only equal to themselves. https://api.dart.dev/be/180791/dart-core/List/operator_equals.html
Problem is how Dart compares Lists for equality. See here for more information on how to compare lists. But that wont work in the case here.
If you use it lie this you will get the result because they key is the same object
The problem is you are trying to compare new List,
List<String> key = ['foo', 'bar']
with the existing key of['foo','bar']
which are not equal because of different references, so you need to make the reference of both the key point to the same variablekey
Example:
Output :
You can use this function where I am using
IterableEquality
fromAnd test
You can check more about How can I compare Lists for equality in Dart?
As declare
key
, which generate a new object, so it won’t be getting matched. To overcome with this, you can use custom comparison function to solve this.