在Flutter中执行OnChanged函数后调用Future



我想在onChanged函数执行之后立即执行Future,因为在为petType找到的新petRaces调用api之前,我需要首先更改selectedPetValueType。示例:

如果我选择了查找petType = dog,但在此之前我选择了petType = cat,它将显示猫种族而不是狗,如果我再次将其更改为猫,它会显示狗,因为它在onChange函数之前存储了最后一个值。

此处编码:

Widget obtainPetsTypeDropdownButton() {
return FutureBuilder(
future: ApiPets.retreivePetRaces(selectedValuePetType.index),
builder: (context, snapshot) {
return Container(
width: 100.0,
child: DropdownButton<PetType>(
style: TextStyle(color: Colors.white),
dropdownColor: Colors.blue[800],
value: selectedValuePetType,
onChanged: (PetType newValue) {
selectedValuePetType = newValue;
isRaceVisible = selectedValuePetType != PetType.Otro;
if (snapshot.connectionState == ConnectionState.done) {
loadedRaces = snapshot.data;
selectedValuePetRace = loadedRaces.first.petRaceId;
setState(() {});
}
},
items: PetType.values.map((PetType classType) {
return DropdownMenuItem<PetType>(
value: classType, child: Text(classType.name));
}).toList()));
},
);
}

因此,使onChanged函数异步是解决问题的方法

onChanged: (PetType newValue) async {
selectedValuePetType = newValue;
isRaceVisible = selectedValuePetType != PetType.Otro;
await updatePetRaces(selectedValuePetType.index);
setState(() {});
},

最新更新