我有一个客户的json:
customer.json
[
{
"name": "Customer 1",
"id": "1"
},
{
"name": "Customer 2",
"id": "2"
},
{
"name": "Customer 3",
"id": "3"
}
]
这是使用此json数据的dart文件:
customerslist.dart
未来方法
Future<String> loadCustomers() async{
var res = await http.get(
Uri.encodeFull(url),
headers: {"Accept": "application/json"});
return res.body;
}
窗口小部件
widgets.add(new FutureBuilder(
future: loadCustomers(),
builder: (context, snapshot){
if(snapshot.hasData){
//get snapshot data from JSON tree
var jsondecode = json.decode(snapshot.data);
return new ListView.builder(
shrinkWrap: true,
itemCount: jsondecode.length,
itemBuilder: (context, index){
String name = jsondecode[index]["name"];
String id = jsondecode[index]["id"];
if(name == "Customer 2"){
return new Column(
children: <Widget>[
new ListTile(
title: new Text("Name"),
trailing: new Text(name),
),
new ListTile(
title: new Text("ID"),
trailing: new Text(id),
)
],
);
}
});
}else{
return new Center(
child: new CircularProgressIndicator(),
);
}
}));
我想要做的是在if(name == "Customer 2")
中看到名称匹配的值。
但我遇到的问题是:
当我将if语句更改为if(name == "Customer 1")
时,输出正如您所期望的那样:
但如果我要将其更改为if(name == "Customer 2")
,输出结果为空白:
有人可以解释为什么会这样,或者我可以采取另一种方法来解决这个问题吗?
我认为这是因为Column
小部件正在全力以赴。您可以尝试使用列的最小高度并添加其他条件。
if(name == "Customer 2"){
return new Column(
children: <Widget>[
new ListTile(
title: new Text("Name"),
trailing: new Text(name),
),
new ListTile(
title: new Text("ID"),
trailing: new Text(id),
)
],
);
} else {
return new Container();
}
当您使用“客户1”时,它工作正常,因为您的第一个元素是“客户1”,可能您的控制台上有错误,因为其他项目没有返回的小部件。
对于“客户2”,不会返回第一个项目,因此请检查控制台日志。
itemBuilder
希望您返回所有案例的小部件。
您只需将var字符串转换为list
var jsondecode = json.decode(snapshot.data);
List list = jsondecode;
String name = list[index]["name"];
String id = list[index]["id"];
然后传递列表以获取索引可能这将工作bocasue var类型可能只获取第一个json字符串
enter code here