如何在flutter下拉按钮中使用Json列表



我有这个代码的工作和打印列表,但当我在一个下拉按钮中使用它时,它抛出空红屏幕错误,而运行应用程序。

Future<void> readJson() async {
final response = await rootBundle.loadString('assets/json/units.json');
final data = await json.decode(response);
setState(() {
List jsonList = data["length"] as List;
print(jsonList);
});
}

Json文件结构如下

{
"length" : [
{
"name": "Meter",
"conversion": 1.0,
"base_unit": true
},
{
"name": "Millimeter",
"conversion": 1000.0
},
{
"name": "Centimeter",
"conversion": 100.0
}
]
}

下面是下拉按钮的样子

Widget customJsonDropDown(String value, void onChange(val)) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(9),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: SizedBox(
//width: 80,
height: 50,
child: DropdownButton<String>(
value: value,
onChanged: (val) {
onChange(val);
},
items: jsonList?.map((item) {
return DropdownMenuItem(
child: Text(item['name']),
value: item['conversion'].toString(),
);
}).toList() ??
[],
underline: Container(),
isExpanded: true,
))));
}

非常感谢您的帮助。

作为value参数发送给customJsonDropDown的是什么?错误消息是说,您传递给DropdownButton的任何itemsvalue属性都与DropdownButton本身设置的值不匹配,或者不止一个。你能确认item['conversion'].toString()的计算结果是多少吗?如果其中一个值恰好与DropdownButtonvalue匹配?

编辑:让我试着澄清一下:

Widget customJsonDropDown(String value, void onChange(val)) {
return ...
child: DropdownButton<String>(
value: value, // <-- this needs exactly one corresponding DropdownMenuItem, or be null
onChanged: (val) {
onChange(val); // <-- this needs to update the value above to a value that also matches exactly one of the items you set below, or null
},
items: jsonList?.map((item) {
return DropdownMenuItem(
child: Text(item['name']),
value: item['conversion'].toString(), // <-- exactly one of these has to match the DropdownButton's value above, if not null
);
}).toList() ??
[],
// ...

最新更新