Reputation: 7289
I am populating an array from json data in Dart
String url="http://someapi.com/words";
List<Word> words=new List<Word>();
final res = await http.get(url, headers: {"Accept": "aplication/json"});
final wordsList = json.decode(res.body);
for (var h in wordsList) {
Word word = new Word(title: h['title'].toString());
words.add(word);
}
This gives me a list of Words. Now how can I use it in the widget? Below is the code that I currently have
@override
Widget build(BuildContext context) {
final response=fetchWords(); //this response will have list of words
return new Container(
padding: new EdgeInsets.symmetric(vertical: 15.0,
horizontal: 15.0),
child: Column(children: <Widget>[
new Row(
children: <Widget>[
//I want to add a container for each for words here
],
)
])
);
I tried following this, but I am not sure how to convert the json array into widgets
Upvotes: 3
Views: 11056
Reputation: 11651
Just use map
with toList()
Row(
children: words.map((word)=> Text(word)).toList()
);
map
will take one word at a time
=>
is short for return
so you could have written
Row(
children: words.map((word){
returnText(word)}
).toList()
);
Lastly, Row
expects a List
of widgets whereas map
gives an Iterable
thus we use toList()
to get a list of widgets.
EDIT:
If you need to access the index of element, then
class MyWidget extends StatelessWidget {
final words = ['foo', 'bar', 'baz'];
@override
Widget build(BuildContext context) {
return ListView(
children: words
.asMap()
.entries
.map(
(e) => Text("${e.value} at index ${e.key}"),
)
.toList(),
);
}
}
Upvotes: 7
Reputation: 3364
Use map function.
Example:
Row(
children: words.map<Widget>((word)=>Container(child: Text(word))).toList()
);
Upvotes: 8