在我的申请中,我想根据动物的种类(如果是狗或猫)展示疫苗。我遇到一个错误:在null上调用了“ map ”方法。尝试调用:映射DropdownMenuItem。为什么会这样呢?我已经在方法中放置了异步并等待,我不明白为什么它仍然为空。下面是我的代码:
1)在这里我在初始化中调用我的DropdownContent类以准备小部件内行中的DropdownMenuItem
class _VaccineDetailFormState extends State<VaccineDetailForm> {
final DataRepository repository = DataRepository();
String selectedVaccine = "Select";
List<String> vaccinesBySpecie;
initState() {
DropdownContent.getVaccines(widget.selectedPetID).then((value) => vaccinesBySpecie = value);
}
@override
Widget build(BuildContext context) {
return Scaffold(
[...]
new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new DropdownButton<String>(
value: widget.vaccine.name == null ? selectedVaccine: widget.vaccine.name,
underline: Container(
height: 2,
color: Colors.grey,
),
onChanged: (String newValue) {
setState(() {
selectedVaccine = newValue;
widget.vaccine.name = newValue;
});
},
items: vaccinesBySpecie.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
)
]),
[...]
2)这是DropdownContent类,该类在getVaccines()方法内部,搜索存储库以找出当前动物的种类,然后返回适当的疫苗列表。
class Dropdown content
static Future<List<String>> getVaccines(String petId) async {
final DataRepository repository = DataRepository();
String currentSpecie = await repository.getSpecie(petId);
if (currentSpecie.contains('Dog')) {
return listOfVaccinesForDogs();
}
if (currentSpecie.contains('Cat')) {
return listOfVaccinesForCats();
}
}
3)最后,搜索动物种类的存储库类
class Repository
Future<String> getSpecie(String petId) async {
DocumentReference documentReference = petCollection.document(petId);
await documentReference.get().then((snapshot) {
return snapshot.data['specie'].toString();
});
}
最佳答案
尽管您的initState方法可能是异步的,但您的构建方法却不是。因此,在调用build方法时,您的vacantsBySpecie方法为空。
解决此问题的最佳方法是像List<String> vaccinesBySpecie
这样初始化List<String> vaccinesBySpecie = [];
。这样,在调用build方法时,它就不会为null。
附带说明一下,如果可能的话,我建议您使用FutureBuilder或StreamBuilder,这样您就可以处理没有值时(即它为null)与有值时(即它不为null)
关于android - Flutter Firebase-DropdownMenuItem:在空方法上调用了 'map'方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62160096/