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

2 Answers 2

8

Use map function.

Example:

Row(
  children: words.map<Widget>((word)=>Container(child: Text(word))).toList()
);
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget the .toList() ad the end of the .map<> . Totally oversaw this on the first reading :)
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(),
    );
  }
}

2 Comments

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 yes, there also is a mapIndexed function that provides the index and the item at that index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.