3

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

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

2 Answers2

8

Use map function.

Example:

Row(
  children: words.map<Widget>((word)=>Container(child: Text(word))).toList()
);
Aawaz Gyawali
  • 3,244
  • 5
  • 28
  • 48
  • 2
    Don't forget the .toList() ad the end of the .map<> . Totally oversaw this on the first reading :) – Bliv_Dev Mar 27 '20 at 00:29
7

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(),
    );
  }
}
Doc
  • 10,831
  • 3
  • 39
  • 63
  • Is there a way to get the index in the mapping? for example in react you could do words.map((word, idx) and idx is the index – user3808307 Oct 22 '20 at 00:44