0

I want a function that takes a list of lists. It should sort this list of lists, regardless of its type, by the length of each list within it.

I thought I could achieve this by using the function below, but I am getting type errors. X is not a subtype of Y. From my understanding, using dynamic means it can take any type, so what am I doing wrong?

List<List<dynamic>> sortByLength(List<List<dynamic>> lss) {
  final newLss = List.from(lss);

  return newLss..sort((a, b) => a.length.compareTo(b.length));
}
Matt
  • 463
  • 4
  • 14

1 Answers1

1

Your problem is that you accidentally converted a List<List<dynamic>> to a List<dynamic> and then tried to return that as a List<List<dynamic>> without a cast.

final newLss = List.from(lss);

This makes two mistakes:

  1. It uses List.from instead of List.of (or instead of lss.toList() or [...lss]).
  2. It does not specify an explicit type for the List.

Combined, those mistakes give newLss a type of List<dynamic>. Attempting to return newLss then fails because converting List<dynamic> to List<T> requires using List.cast to change the element type.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
  • I opted for the `[...lss]` option, the purpose was just to clone it to avoid mutations, which I thought `List.from` did. Thanks for the corrections! – Matt Apr 29 '20 at 03:42
  • `List.from` does make a copy, but in a dynamically typed way which allows you to do down-casts like converting a `List` containing only integers to a `List` (fx. `List.from(listOfNum.where((x) => x is int && x.isEven)`). That means that it cannot infer the list element type from the argument, and you should either write `List>.from` use `List.of` instead. The latter works with type inference, but cannot do downcasts. – lrn Apr 29 '20 at 09:28