首页 > 解决方案 > 为 Flutter Dart 列表中的每个项目创建小部件

问题描述

我正在从 Dart 中的 json 数据填充一个数组

 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);
    }

这给了我一个单词列表。现在如何在小部件中使用它?以下是我目前拥有的代码

 @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 
            ],
          )
         ])
         );

我尝试遵循这个,但我不确定如何将 json 数组转换为小部件

标签: dartflutter

解决方案


只需maptoList()

Row(
  children: words.map((word)=> Text(word)).toList()
);

map一次只说一个词

=>是缩写,return所以你可以写

Row(
   children: words.map((word){
                returnText(word)}
                ).toList()
  );

最后,Row期望一个List小部件,而map给出一个Iterable因此我们toList()用来获取小部件列表。


编辑:

如果您需要访问元素的索引,那么

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(),
    );
  }
}

推荐阅读