Reputation: 1072
I'm working on a Flutter app, where I need to iterate over a map.
The content of the map looks like this: ({amount: 1, ingredient: Egg}, {amount: 2 ss, ingredient: Havremel})
(It's stored as an array of maps in the DB. Not sure why Dart outputs it like this, instead of a list to begin with).
I'm getting a type error whenever I map over the data. I'm separating the data in a separate function, and calling it from a Column Widget:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ingredients',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
_getIngredients(recipe['ingredients']),
],
),
The _getIngredients function. I have tried to type this multiple ways. The error message is commented at the top of each line.
Widget _getIngredients(ingredients) {
// type 'MappedListIterable<dynamic, Widget>' is not a subtype of type 'Widget'
return ingredients.map<Widget>((i) => Text(i['amount']));
// type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'Widget'
return ingredients.map((i) => Text(i['amount']));
// type 'List<dynamic>' is not a subtype of type 'Widget'
return ingredients.map((i) => Text(i['amount'])).toList();
// type 'List<Widget>' is not a subtype of type 'Widget'
return ingredients.map<Widget>((i) => Text(i['amount'])).toList();
}
Clearly, there is something I don't understand about the type system. I don't understand how I am supposed to figure out the correct types either. I have no problem understanding the regular Dart types, as String, int, List, Map and so forth, however Flutter types threw me off a bit. I usually program in JS or Python, so my experience with types are limited.
Any pointers on how to solve my type problem?
Upvotes: 2
Views: 5532
Reputation: 398
Your _getIngredients
expects a return value of Widget.
In each of you examples you either return a list or a map.
So I think what you want is to return a list of Widget like that:
List<Widget> _getIngredients(ingredients) {
// type 'List<Widget>' is not a subtype of type 'Widget'
return ingredients.map<Widget>((i) => Text(i['amount'])).toList();
}
And here something like that:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ingredients',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
..._getIngredients(recipe['ingredients']), // the ... operator adds to array
],
),
Upvotes: 6