我有一个返回公司json的url,我使用公司列表来填充下拉列表。还有另一个url,它带有一个返回仓库列表的参数。获取仓库的第二个方法返回一个空json。
以下是获取公司的代码。工作正常
String? _mySelection;
final String url = "http://url:8000/companies"
Future<String> getCompanies() async {
var res = await http
.get(Uri.parse(url), headers: {
'Content-Type': 'application/json'
});
var resBody = json.decode(res.body)["data"]; // data = map["data"];
print(resBody);
setState(() {
data = resBody;
});
print(res);
return "Sucess";
}
获取仓库的代码类似。
Future<String> getWarehouses(company) async {
late String warehousesUrl = "http://myWarehouseurl?company=$company";
var warehouseRes = await http
.get(Uri.parse(warehousesUrl), headers: {
'Content-Type': 'application/json'
});
var warehouseResBody = json.decode(warehouseRes.body)["data"]; // data = map["data"];
print(warehouseResBody);
setState(() {
warehouseData = warehouseResBody;
});
print(warehouseRes);
return "Sucess";
}
我的initState方法
@override
void initState() {
super.initState();
this.getCompanies();
this.getWarehouses(_mySelection);
}
下降
new DropdownButton(
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['company_name']),
value: item['company_name'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal.toString();
getWarehouses(_mySelection);
});
},
value: _mySelection,
),
_mySelection != "" ? DropdownButton(
items: warehouseData.map((item) {
return new DropdownMenuItem(
child: new Text(item['warehouse_name']),
value: item['name'].toString(),
);
}).toList(),
onChanged: (newVal) {
setState(() {
_mySelection = newVal.toString();
});
},
value: _mySelection,
) : Container(),
我不知道为什么我无法获得第二个下拉列表的值,当我在公司下拉列表的onchange方法中调用该方法来获得仓库的值时,仓库的数据会打印到控制台,但应用程序会崩溃。
我想你错过了async/await
,让我们试试
new DropdownButton(
items: data.map((item) {
return new DropdownMenuItem(
child: new Text(item['company_name']),
value: item['company_name'].toString(),
);
}).toList(),
onChanged: (newVal) async{ // here need the change
setState(() {
_mySelection = newVal.toString();
await getWarehouses(_mySelection); // also here add the await
});
},
value: _mySelection,
),