我有一个对象列表,有没有办法循环使用Card小部件,以便为此列表中的每个对象创建一个使用此小部件属性创建的新卡。
下面的代码肯定不起作用,它只是作为一个例子来展示我想要实现的目标背后的逻辑
//function declaration and body...
List<CardInfo> list = new List();
for (var i in cardInfo){ //cardInfo is a list of json created previously.
list.add(new CardInfo.fromJson(i));
print (list); }//tested the list and it contains the objects I want
return list;
}
...
//my widget{
@override
Widget build(BuildContext context) {
return new Dismissible(
for (i in list){
child: new Card(
child:
new ListTile(leading: new Icon(Icons.star, color: Colors.yellowAccent,),
title: new Text(list(i).field1),//field1 is a string in CardInfo
subtitle: new Text(list(i).field2),//field2 is a string in CardInfo
这是可行的吗?
更新
我想出将每个JSON转换为对象然后直接使用对象,现在_loadData()函数在每次迭代时返回一个对象
_loadData() async {
var url = 'myurl';
var httpClient = createHttpClient();
var response =await httpClient.get(url);
List cardInfo = JSON.decode(response.body);
List<CardInfo> list = new List();
for ( var i in cardInfo){
var ci = new CardInfo.fromJson(i);
list.add(new CardInfo.fromJson(i));
return ci;
}
//return list;
}
....
那么有没有办法设置我的类构造函数,以便它允许我访问返回对象的字段?像这样的东西:
title: new Text(new CardInfo(_loadData()).field)
更新2:
@override
Widget build(BuildContext context) {
return new FutureBuilder(
future: _loadData(),
builder: (BuildContext context, AsyncSnapshot<List> jsonList){
if (jsonList.hasData==true){
var cardInfo = jsonList.data[0];//is this right ?
print (cardInfo);
return new Dismissible(
child: new Column(
children:
cardInfo.map(
(CardInfo info)=>
new Card(
child: new ListTile(leading: new Icon(Icons.star, color: Colors.yellowAccent,),
title: new Text(info.field),
subtitle: new Text("Subtitle"),)
) ), ),....
我的功能位于顶部,如下所示:
_loadData() async {
var url = 'myurl';
var httpClient = createHttpClient();
var response = await httpClient.get(url);
List cardInfo = JSON.decode(response.body);
List<CardInfo> list = new List();
for (var i in cardInfo) {
list.add(new CardInfo.fromJson(i));
}
return list;
}
我收到以下错误:
Class&#39; CardInfo&#39;没有实例方法&#39; map&#39;。
答案 0 :(得分:1)
您可以使用Iterable.map
方法执行此操作。例如:
new Column(
children: list.map(
(CardInfo info) => new Card(child: new Text(info.field1)),
).toList()
)