[英]create widget for each item in the list in Flutter Dart
I am populating an array from json data in 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);
}
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我尝试按照此操作,但我不确定如何将 json 数组转换为小部件
Use map function.使用地图功能。
Example:例子:
Row(
children: words.map<Widget>((word)=>Container(child: Text(word))).toList()
);
Just use map
with toList()
只需将map
与toList()
Row(
children: words.map((word)=> Text(word)).toList()
);
map
will take one word at a time map
只能输入一个词
=>
is short for return
so you could have written =>
是return
缩写,所以你可以写
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.最后, Row
需要一个小部件List
,而map
提供一个Iterable
因此我们使用toList()
来获取小部件列表。
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(),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.