Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use Firestore package and StreamBuilder to achieve this in your Flutter application. Here is a solution:

  1. Create two List variables to hold the selected options.

    List<String> firstList = [];
    List<String> secondList = [];
    
  2. 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,
        );
      },
    );
    
  3. 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.

  4. 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(),
          ),
        ),
      ],
    )
    
  5. 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.