Reputation: 2137
Please help me understand why this sort doesn't work. I've read Dart's documentation several times and it's just not clicking why this doesn't sort how I expect it to.
void main() {
final hand1 = {
'ranking': 1,
};
final hand2 = {
'ranking': 2,
};
final hand3 = {
'ranking': 1,
};
List players = [hand1, hand2, hand3];
players.sort((a, b) => b.ranking.compareTo(a.ranking));
// Expected players to become
// [hand2, hand1, hand3]
}
Dart complains:
Unhandled exception:
NoSuchMethodError: Class '_InternalLinkedHashMap<String, int>' has no instance getter 'ranking'.
Receiver: _LinkedHashMap len:1
Tried calling: ranking
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1 main.<anonymous closure> (file:///Users/primetimetran/Desktop/projects/flutpoke/poker_class.dart:15:28)
#2 Sort._insertionSort (dart:_internal/sort.dart:69:36)
#3 Sort._doSort (dart:_internal/sort.dart:58:7)
#4 Sort.sort (dart:_internal/sort.dart:33:5)
#5 ListMixin.sort (dart:collection/list.dart:356:10)
#6 main (file:///Users/primetimetran/Desktop/projects/flutpoke/poker_class.dart:15:11)
#7 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
I lack an understanding of how the internals of Dart work I know.
Thanks in advance~!
Upvotes: 0
Views: 164
Reputation: 4551
This does not work, because Dart is not JavaScript and you can't access a map element like a field, instead you have to access it this way b['ranking']!
. The bang operator (!
) is because of null safety.
Upvotes: 1