How do I populate this array list into a dropdown button?
I want to populate this list of the location to the dropdown button. [here is how my database looks like] https://i.stack.imgur.com/S5yDh.png
How do I populate this array list into a dropdown button?
I want to populate this list of the location to the dropdown button. [here is how my database looks like] https://i.stack.imgur.com/S5yDh.png
I know, it's too late to answer your question. But maybe, mine is for anybody who seeks an answer.
Just use streambuilder to stream firestore data in your dropdown. Here is my example:
StreamBuilder(
stream: Firestore.instance.collection('your collectionName').document('yourDocument').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return textCustom('Loading', Colors.black87, 16, 'Montserrat');
} else {
final data = snapshot.data['data'];
return Theme(
data: Theme.of(context).copyWith(
canvasColor: Color(0xFF221F1F),
),
child: DropdownButtonFormField(
style: TextStyle(color: Colors.white70),
value: _value,
items: data
.map<DropdownMenuItem<String>>(
(x) => DropdownMenuItem(
child: textCustom(
x, Colors.white, 16, 'Montserrat'),
value: '${x}',
),
)
.toList(),
onChanged: (val) => setState(() {
_value = val;
}),
),
);
}
},
)
I recommend the flutter_form_bloc package. It's very helpful and you can asynchronously add items to a dropdown array so you can fetch them from an API or for your needs, Firebase.
If you do not want to use a package however, you could create an empty list and assign it to the items parameter initially. In your initState method, you could then populate that list with items and then call setState.
This is not the best way, but gets the work done. Create a temporary list, then use that list to do a for each.
tempList = returnedDoc['location'];
tempList.forEach((element) {
Locations.add(element);
}),
You can create a dropdown button in following way.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: MyApp(),
));
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String dropdownValue;
List<String> listOfStrings = ["apple", "banana", "strawberry", "cherry"];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: listOfStrings.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
}
}