我试图在下拉菜单中显示数据,但是我有一个奇怪的问题,我似乎无法弄清楚。问题是当打开包含下拉菜单的视图时,api数据从服务器获取数据,它按例外方式工作,但数据未首次显示在下拉菜单中,在调试模式下,当我按热区时,数据未显示在下拉菜单中,而是在视图首次显示时显示
下拉菜单
Flexible(
flex: 0,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 45,
width: 300,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
border: Border.all(
color: Color.fromRGBO(92, 52, 76, 1))),
child: DropdownButton<String>(
isExpanded: true,
itemHeight: 50,
underline: SizedBox(),
value: _selectedVehicle,
items: vehicle_list.map((vehicle) {
return DropdownMenuItem<String>(
value: vehicle.id,
child: new Text(
vehicle.model,
style: TextStyle(
fontSize: 15,
color: Color.fromRGBO(
92, 52, 76, 1)),
),
);
}).toList(),
hint: Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Please Select Vehicle"),
),
onChanged: (newValues) {
setState(() {
_selectedVehicle = newValues;
});
}),
),
),
)
API
Future<String> getVehicles() async {
vehicle_list.clear();
Future tokens = SharedPrefrence().getToken();
tokens.then((data) async{
token=data;
var response = await http.get(Urls.BASE_URL + Urls.GET_VEHICLES, headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
});
if (response.statusCode == 200) {
print("vechiles " + response.body.toString());
Map<String, dynamic> value = json.decode(response.body);
try {
var data = value['data'];
for (int i = 0; i < data.length; i++) {
var obj = data[i];
vehicle_list.add(VehicleModel(
obj['id'].toString(),
obj['user_id'].toString(),
obj['type'].toString(),
obj['model'],
obj['reg_no'],
obj['fuel_type'].toString()));
}
} catch (e) {
print(e.toString());
}
} else {
print(response.body.toString());
}
});
}
利用率
List<VehicleModel> vehicle_list = [];
String _selectedVehicle;
这就是我调用函数的方式
@override
void initState() {
// TODO: implement initState
super.initState();
getVehicles();
}
答案 0 :(得分:1)
我认为这可以解决您的问题:
const getVal = outer => accessor.split('.').reduce((a, prop) => a[prop], outer)
答案 1 :(得分:1)
您已在函数末尾调用setState
来修改状态!
像这样的东西
Future<String> getVehicles() async {
vehicle_list.clear();
Future tokens = SharedPrefrence().getToken();
tokens.then((data) async{
token=data;
var response = await http.get(Urls.BASE_URL + Urls.GET_VEHICLES, headers: {
"Authorization": "Bearer " + token,
"Content-Type": "application/json"
});
if (response.statusCode == 200) {
print("vechiles " + response.body.toString());
Map<String, dynamic> value = json.decode(response.body);
try {
var data = value['data'];
for (int i = 0; i < data.length; i++) {
var obj = data[i];
vehicle_list.add(VehicleModel(
obj['id'].toString(),
obj['user_id'].toString(),
obj['type'].toString(),
obj['model'],
obj['reg_no'],
obj['fuel_type'].toString()));
}
setState(() {});
} catch (e) {
print(e.toString());
}
} else {
print(response.body.toString());
}
});
}
希望有效!