【问题标题】:create widget for each item in the list in Flutter Dart为 Flutter Dart 列表中的每个项目创建小部件
【发布时间】:2019-05-07 16:17:17
【问题描述】:

我正在从 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 
            ],
          )
         ])
         );

我尝试关注this,但我不确定如何将 json 数组转换为小部件

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    使用地图功能。

    例子:

    Row(
      children: words.map<Widget>((word)=>Container(child: Text(word))).toList()
    );
    

    【讨论】:

    • 不要忘记 .toList() 广告 .map 的结尾。在一读时完全监督了这一点:)
    【解决方案2】:

    只需将maptoList() 一起使用

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

    map 一次只接受一个词

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

    【讨论】:

    • 有没有办法获取映射中的索引?例如在反应中你可以做 words.map((word, idx) 和 idx 是索引
    猜你喜欢
    • 2019-09-29
    • 2021-07-06
    • 1970-01-01
    • 2021-06-30
    • 2021-08-03
    • 2017-11-18
    • 2021-11-01
    • 2014-07-24
    • 2021-08-07
    相关资源
    最近更新 更多