gpt4 book ai didi

dart - 在 Flutter Dart 中为列表中的每个项目创建小部件

转载 作者:IT王子 更新时间:2023-10-29 07:11:40 25 4
gpt4 key购买 nike

我正在用 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 数组转换为小部件

最佳答案

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

关于dart - 在 Flutter Dart 中为列表中的每个项目创建小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com