dart - 为 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 数组转换为小部件
解决方案
只需map
与toList()
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(),
);
}
}
推荐阅读
- entity-framework - Entity Framework Core 3.1 DbCommandInterceptor 仅记录 SELECT 查询
- hazelcast - 带有同步备份的嵌入式 Hazelcast 备份读取
- javascript - 提交成功或失败后如何在反应表单中显示 toastr 警报?
- javascript - 使用 node.js + express.js 网站减小字体大小
- sql - presto sql比较不同表的列并过滤掉不匹配的
- vim - Vim 运行的语言是如何工作的?
- swift - 如何使用 Swift 每秒有效地修改 5000 像素的大 UIImage 60 次
- c# - DSharpPlus 如何在 C# 中为 NSFW 创建或设置不和谐频道
- python - 为大量线程类实现线程池
- python - /posts/12/tesing/like/quote_from_bytes() 预期字节处的 TypeError