我有一个值列表,这些值打算通过rest API中的JSON解析为一个下拉按钮。可以很好地解析值,但是我施加了一个条件,即当没有可显示的值列表时,它应该仅在下拉菜单中显示一个文本,即“无设备”。但是由于某种原因,这是行不通的。
我的代码:
List data = List();
Future<String> getSWData() async {
setState(() {
isLoading = true;
});
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
resBody = json.decode(res.body);
setState(() {
data = resBody;
isLoading = false;
});
return "Sucess";
}
child: DropdownButton(
hint: new Text(
"Select Equipment",
style: style,
),
style: style,
onChanged: (newVal) {
setState(() {
_mySelectionEquipment = newVal;
});
},
value: _mySelectionEquipment,
items: data.map((item) {
return new DropdownMenuItem(
child: Row(
children: <Widget>[
Text(item['EquipmentMake'] ??
"No Equipment Registered"),
SizedBox(
width: 5,
),
SizedBox(
width: 5,
),
Text(item['EquipmentModel'] ?? ""),
],
),
value: item['EquipmentID'].toString(),
);
}).toList(),
isExpanded: false,
),
答案 0 :(得分:2)
您在空列表中调用Map
尝试这样的事情:
items: data.length > 0
? data.map((item) {
return new DropdownMenuItem(
child: Row(
children: <Widget>[
Text(item['EquipmentMake'] ??
"No Equipment Registered"),
SizedBox(
width: 5,
),
SizedBox(
width: 5,
),
Text(item['EquipmentModel'] ?? ""),
],
),
value: item['EquipmentID'].toString(),
);
}).toList()
: [
DropdownMenuItem(
child: Row(
children: <Widget>[
Text("No Equipment Registered"),
SizedBox(
width: 5,
),
SizedBox(
width: 5,
),
Text(""),
],
),
value: 0.toString())
],