I'm new in Flutter with Firebase and I'm trying to load some arrays stored in Firebase into a DropdownButton.
This piece of code works when a I call it from a button. It returns a list of drinks that I can print on the screen:
Future<List<String>> get drinks async {
QuerySnapshot docs = await _constantes.getDocuments();
List<String> res = List();
List<Map<String, dynamic>> datos = List();
for (var d in docs.documents) {
datos.add(d.data);
}
for (var d in datos[0]['drinks'].toList()) {
res.add(d.toString());
}
return res;
}
But my problem is that I'd like to load this list into a DropdownButton, so the user could choose one of the drinks when the app shows him the form :
DropdownButtonFormField(
hint: Text('Choose a drink'),
value: _currentDrink ?? 'Water',
items: _db.drinks.then((drinks) {
List<DropdownMenuItem> datos = List();
for (var d in drinks) {
datos.add(DropdownMenuItem(
value: d,
child: Text(d),
));
}
return datos;
}),
onChanged: (val) => setState(() => _currentDrink = val),
),
But it doesn't work because the result is a Future.
How could I fix it?
Thanks.
Assign an empty list [] to dropdown until drinks are fetched and when fetched we will assign drinks list.Drinks list will get items after our future is completed.You need to call this future in initState of your method so when page is opened it fetches drinks and then assigns it to the drinks list.Dropdown will remain empty until drinks are fetched. (Incase you want to show progressindicator on dropdown until drinks are fetched wrap dropdown in a future builder)
List<String> drinks = List();
Future<List<String>> get drinks async {
QuerySnapshot docs = await _constantes.getDocuments();
List<String> res = List();
List<Map<String, dynamic>> datos = List();
for (var d in docs.documents) {
datos.add(d.data);
}
for (var d in datos[0]['drinks'].toList()) {
res.add(d.toString());
}
setState(() {
drinks = res;
});
return res;
}
DropdownButtonFormField(
hint: Text('Choose a drink'),
value: _currentDrink ?? 'Water',
items: drinks == null? []: drinks.map((drink) {
return DropdownMenuItem<String>(
child: Text(drink),
value: drink,
);
}).toList(),
onChanged: (val) => setState(() => _currentDrink = val),
),