Home > database >  Map.fromIterable specify argument type of key/value extraction lambdas
Map.fromIterable specify argument type of key/value extraction lambdas

Time:10-20

Given this code:

class Dog{
  String name = "Dog";
  int age = 2;
}

final list = [Dog(), Dog()]

final dogNameToAge = Map.fromIterable(
  list, key: (value)=> value.name, value: (value)=>value.age)

Type of 'key' lambda is String Function(dynamic)? is there a way of using something more like: String Function(Dog)? so that it would be more type safe?

CodePudding user response:

You can also write it using a map literal:

final dogNameToAge = {for (var dog in list) dog.name: dog.age};

That's my recommendation over fromIterables any day.

CodePudding user response:

Yeah, that constructor is cursed since it does not have any concept of generics. I would do the following instead (fixed age so it is not assigned to "2" but 2:

class Dog {
  String name = "Dog";
  int age = 2;
}

final list = [Dog(), Dog()];

final dogNameToAge = Map.fromEntries(list.map((e) => MapEntry(e.name, e.age)));

The type of dogNameToAge is then Map<String, int> as expected.

Or do what @lrn suggests. :)

  •  Tags:  
  • dart
  • Related