1 | initial version |
You can use Firestore
package and StreamBuilder
to achieve this in your Flutter application. Here is a solution:
Create two List
variables to hold the selected options.
List<String> firstList = [];
List<String> secondList = [];
Create a StreamBuilder
that listens to changes in the Firestore document that contains the dropdown options.
StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance.collection('options').document('dropdown').snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
List<dynamic> options = snapshot.data['options'];
return DropdownButtonFormField(
value: null,
items: options.map((option) {
return DropdownMenuItem(
value: option,
child: Text(option),
);
}).toList(),
onChanged: (value) {
setState(() {
if (firstList.contains(value)) {
firstList.remove(value);
secondList.add(value);
} else if (secondList.contains(value)) {
secondList.remove(value);
firstList.add(value);
} else {
firstList.add(value);
}
});
},
decoration: InputDecoration(
labelText: 'Select options',
border: OutlineInputBorder(),
),
isDense: true,
isExpanded: true,
multiple: true,
);
},
);
In the onChanged
callback of the DropdownButtonFormField
, check if the value is already selected in firstList
or secondList
. If it is, remove it from that list and add it to the other list. If it is not, add it to firstList
.
Update the UI to display the selected options.
Row(
children: [
Expanded(
child: ListView(
shrinkWrap: true,
children: firstList.map((option) {
return Text(option);
}).toList(),
),
),
SizedBox(width: 16.0),
Expanded(
child: ListView(
shrinkWrap: true,
children: secondList.map((option) {
return Text(option);
}).toList(),
),
),
],
)
Wrap the entire StreamBuilder
and UI in a Scaffold
widget if you want to provide additional widgets around the dropdown and selected options.
That's it! You can now update two lists with different values simultaneously when selecting options from a dropdown menu that allows multiple selections from Firebase Firestore in your Flutter application.