Search code examples
flutterfirebasegoogle-cloud-firestoredropdownstream-builder

How Can I Remove Duplicates From DropdownMenuItem in Flutter


I'm having an issue with duplicate DropdownMenuItem while getting the menu item's value from Firestore.

My Firestore DB Structure

I want to get all the 'from' attributes values from 'routes' collection excluding the duplicates. And i want to show them inside my DropDownButton.

My Sample Code:

late final Stream<QuerySnapshot> routes = Database().getRoutes();


StreamBuilder<QuerySnapshot>(
stream: routes,
builder: (
    BuildContext context,
    AsyncSnapshot<QuerySnapshot> snapshot,
    ) {

  final data = snapshot.requireData;

  fromValue.value = data.docs[0]['from'];
  destinationValue.value = data.docs[0]['to'];

  return Column(
    children: [
      Obx(() {
        return DropdownButton(
          // Initial Value
          value: fromValue.value,
          // Down Arrow Icon
          icon: const Icon(Icons.keyboard_arrow_down),
          alignment: AlignmentDirectional.center,
          underline: Container(
            height: 1,
            color: Colors.deepPurple.shade100,
          ),
          // list of items
          items: data.docs.map(
                  (DocumentSnapshot doc) {
                return DropdownMenuItem<
                    String>(
                    value: doc['from']
                        .toString(),
                    child:
                    Text(doc['from']));
              }).toList(),
          // After selecting the desired option,it will
          // change button value to selected value
          onChanged: (newValue) {
            fromValue.value = newValue.toString();
          },
        );
      }),
    ],
  );
}),

Method Used To Fetch Firestore Data:

getRoutes() {
  final Stream<QuerySnapshot> routes = db
    .collectionGroup("routes")
    .snapshots();

    return routes;
  }

Solution

  • I have used factionDatabaseSnapshot.map((DocumentSnapshot document) => document['name']).toSet().toList().map((name)

    to make all items unique. Thanks to Md. Yeasin Sheikh