[英]Flutter DropdownButton not showing items
i'm trying to get a list of elements from the cloud firestore and then pass them into DropdownButtonFormField items, the thing is that i'm able to print them in the console but they are not being shown in the DropdownButtonFormField.我正在尝试从云 firestore 获取元素列表,然后将它们传递到 DropdownButtonFormField 项目中,问题是我能够在控制台中打印它们,但它们没有显示在 DropdownButtonFormField 中。
Here is my code:这是我的代码:
List<String> companies = [];
Future getCompanies() async {
await FirebaseFirestore.instance
.collection('users_web')
.get()
.then((value) {
value.docs.forEach((element) {
companies.add(element['nom']);
print(companies.toList());
});
});
}
@override
void initState() {
getCompanies();
super.initState();
}
The DropdownButtonFormField:下拉按钮表单字段:
DropdownButtonFormField<String>(
decoration: InputDecoration(
border: InputBorder.none,
),
hint: Text('Sélectionner votre société'),
items: companies.map(buildMenuItem).toList(),
onChanged: (value) {
setState(() {
company = value!;
});
},
validator: (value) {
if (!isChecked) {
if (value == null) {
return 'Ce champ ne doit pas être vide';
}
}
},
value: company,
isExpanded: true,
iconSize: 26,
icon: Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Icon(
Icons.arrow_drop_down,
color: Colors.black,
),
),
),
I'd be grateful for any help, thanks in advance!如果有任何帮助,我将不胜感激,在此先感谢!
The problem is that your data is fetched async.问题是您的数据是异步获取的。 Your screen is build before the
getCompanies
is finished.您的屏幕是在
getCompanies
完成之前构建的。 The best way would be to use a FutureBuilder
but calling a setState
after the data is loaded might be good enough for your case最好的方法是使用
FutureBuilder
但在加载数据后调用setState
可能足以满足您的情况
Future getCompanies() async {
await FirebaseFirestore.instance
.collection('users_web')
.get()
.then((value) {
value.docs.forEach((element) {
companies.add(element['nom']);
print(companies.toList());
});
});
setState((){});
}
// example of your data
List<String> companies = ['item 1','item 2','item 3'];
DropdownButtonFormField<String>(
decoration: InputDecoration(
border: InputBorder.none,
),
hint: Text('Sélectionner votre société'),
items: List.generate(companies.length, (index) {
return DropdownMenuItem(
child: Text(companies[index]),
value: companies[index],
);
}),
onChanged: (value) {},
validator: (value) {},
value: companies.length > 0 ? companies[0] : null,
isExpanded: true,
iconSize: 26,
icon: Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Icon(
Icons.arrow_drop_down,
color: Colors.black,
),
),
)
companies is a List of Strings so you can put it as is in the items: field companies 是一个字符串列表,因此您可以将其按原样放在 items: 字段中
BEFORE:
items: companies.map(buildMenuItem).toList(),
AFTER:
items: companies,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.