我有一个对象列表,有没有方法在卡片小部件上循环,以便对于这个列表中的每个对象,使用这个感兴趣的小部件的属性创建一张新的卡片。
下面的代码肯定不起作用,它只是一个示例,展示了我试图实现的目标背后的逻辑
//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;
}
我得到以下错误:
类“CardInfo”没有实例方法“map”。