I know someone already asked the same question. But i still confuse about something. I followed the provided answer and use this:
extension ExtendedMap on Map {
/// The first entry satisfying test, or null if there are none.
MapEntry? firstWhereOrNull(bool Function(MapEntry entry) test) {
for (var entry in this.entries) {
if (test(entry)) return entry;
}
return null;
}
}
And i try:
someMap?.firstWhereOrNull((date) => (date > recentSunday )&& (date <= nextSunday)
But i got this error:
The operator '>' isn't defined for the type 'MapEntry<dynamic, dynamic>'.Try defining the operator '>'.
The operator '<=' isn't defined for the type 'MapEntry<dynamic, dynamic>'.Try defining the operator '<='.
I'm confused why this happened. I thought it should work if any boolean function is passed as argument.Can anyone explain why it is asked to define the operator?
The callback has type bool Function(MapEntry entry)
, so date
is of type MapEntry
. If you want to access the value associated with this entry, use date.value
:
final result = someMap?.firstWhereOrNull((date) => (date.value > recentSunday )&& (date.value <= nextSunday));
^^^^^^ ^^^^^^
Complete example:
final someMap = {
'halloween': 1,
'christmas': 12,
'easter': 123,
};
final recentSunday = 10;
final nextSunday = 30;
final result = someMap?.firstWhereOrNull((date) => (date.value > recentSunday )&& (date.value <= nextSunday));
print(result);
Console output:
MapEntry(christmas: 12)
Note that the returned value is also a MapEntry
.