Reputation: 376
Really frustrated about not solving it myself but finally gave up. I have an array of fields, each being a map with title and value. I want to iterate through it and create a list of text widgets along with some padding between them. I tried the following:
fields.expand((field)=>
[ Text(field['title']),
Padding(padding: const EdgeInsets.only(bottom: 4.0))
]
).toList()
But this gives the following error:
type 'List<dynamic>' is not a subtype of type 'List<Widget>'
I tried adding <Widget>
after expand
but then I get:
type 'MappedListIterable<Map<String, String>, dynamic>' is not a subtype of type 'List<Widget>'
I also tried adding <Widget>
after expand(
but then I get:
type '<Widget>(dynamic) => List<Widget>' is not a subtype of type '(Map<String, String>) => Iterable<dynamic>' of 'f'
Not sure what else to do. How the heck can I force it to realize this is a list of widgets? I also tried using fold but got similar typing issues.
Upvotes: 1
Views: 2558
Reputation: 17143
As I said in my comment, one of your solutions appears to should have work, but since it didn't I'm providing an alternate solution.
You can use a for-each
loop to "manually" create an output List
that you can pass to your Column
widget. Ex.
List<Widget> columnList = List();
for(Map field in fields) {
columnList.add(Text(field['title']);
columnList.add(Padding(padding: const EdgeInsets.only(bottom: 4.0)));
}
Upvotes: 0
Reputation: 3842
I think what you're looking for is .map()
, but there's a cleaner way to do it :
items: [
for(var field in fields)
...[
Text(field['title']),
Padding(padding: const EdgeInsets.only(bottom: 4.0)),
]
]
Make sure your minimum SDK version is 2.6.0 or above in the pubspec.yaml
Upvotes: 1
Reputation: 376
As @christopher-moore noted, adding <Widget>
after expand
does work. The reason I thought it was not working was that I kept getting the error, but for a different place where I still had the same statement but without that addition.
Upvotes: 0