skip to Main Content

I have a dropdown that currently has 2 items in it.

I am getting an error when I select one of the items in the dropdown.

Here is the error:

════════ Exception caught by widgets library ═══════════════════════════════════
There should be exactly one item with [DropdownButton]'s value: CTsaGabEp69DuVLwHsFM. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 948 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

Here is the dropdown code:

StreamBuilder<QuerySnapshot>(
  stream: _db.collection('company').snapshots(),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    List<DropdownMenuItem<String>> companyItems = [];
    if (snapshot.hasData) {
      final companyList = snapshot.data.docs;
      for (var company in companyList) {
        companyItems.add(
          DropdownMenuItem(
            value: company.id,
            child: Text(
              company['name'],
            ),
          ),
        );
      }
    } else {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }
    return DropdownButton<String>(
      hint: const Text("Select Company"),
      value: _selectedCompany,
      onChanged: (companyValue) {
        setState(() {
          _selectedCompany = companyValue;
        });
      },
      items: companyItems,
    );
  }),

This is the error on the screen:

Error on the screen

The error is thrown after I select one of the items in the dropdown. The dropdown value is not null.

What is wrong with this and how do I fix it?

UPDATE:
Here is the updated code:

StreamBuilder(
                    stream: _db.collection('company').snapshots(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      List<DropdownMenuItem<String>> companyItems = [];
                      if (snapshot.hasData) {
                        final companyList = snapshot.data.docs;
                        for (var company in companyList) {
                          companyItems.add(
                            DropdownMenuItem(
                              value: company.id,
                              child: Text(
                                company['name'],
                              ),
                            ),
                          );
                        }
                        return DropdownButton<String>(
                          hint: const Text("Select Company"),
                          value: _selectedCompany,
                          onChanged: (companyValue) {
                            setState(() {
                              _selectedCompany = companyValue;
                              // ref
                              //     .read(globalsNotifierProvider.notifier)
                              //     .updatecurrentUserId(userValue!);
                            });
                          },
                          items: companyItems,
                        );
                      } else {
                        return const CircularProgressIndicator();
                      }
                    }),

2

Answers


  1. You need to move your dropdown widget inside the if statement, because when you call setstate, the stream is refreshed, and the companyList is empty for a few seconds.

        StreamBuilder<QuerySnapshot>(
                    stream: _db.collection('company').snapshots(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      List<DropdownMenuItem<String>> companyItems = [];
                      if (snapshot.hasData) {
                        final companyList = snapshot.data.docs;
                        for (var company in companyList) {
                          companyItems.add(
                            DropdownMenuItem(
                              value: company.id,
                              child: Text(
                                company['name'],
                              ),
                            ),
                          );
                        }
                      return DropdownButton<String>(
                        hint: const Text("Select Company"),
                        value: _selectedCompany,
                        onChanged: (companyValue) {
                          setState(() {
                            _selectedCompany = companyValue;
                          });
                        },
                        items: companyItems,
                      );
    
                      } else {
                        return const Center(
                          child: CircularProgressIndicator(),
                        );
                      }
                      return SizedBox();
                    }),
    

    Second Method:

    you can declare your companyList globally also, make sure to clear old items first

    Login or Signup to reply.
  2. The error says that "There should be exactly one item with [DropdownButton]’s value: CTsaGabEp69DuVLwHsFM.
    Either zero or 2 or more [DropdownMenuItem]s were detected with the same value".

    which occurs when the "value" you are using in DropDownMenuItem is different from the "value" of DropDownButton i.e. the value receiving in your DropDownMenuItem’s "value" is "CTsaGabEp69DuVLwHsFM"

    To understand this here’s an example code

    class HomeView extends StatefulWidget {
      const HomeView({super.key});
    
      @override
      State<HomeView> createState() => _HomeViewState();
    }
    
    class _HomeViewState extends State<HomeView> {
    final List<String> companyList = ["one", "two", "three"];
    
    List<DropdownMenuItem<String>> data = [];
    
    String value = "one";
    
    @override
    void initState() {
    for (var companyName in companyList) {
      data.add(DropdownMenuItem(value: companyName, child: 
     Text(companyName)));
    }
    super.initState();
     }
    
    @override
    Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: DropdownButton(
          value: value,
          items: data,
          onChanged: (val) {
            setState(() {
              value = val!;
            });
          },
        ),
      ),
    );
    }
    }
    

    Now, if you change the value of DropDownItem’s value to "four" then you’ll get the same error again or if you change the String value = "four" the error will be the same.

    So in your code, make sure that the "value: company.id," within your DropDownItem() should be an item from company list.
    and try to change this:

     DropdownMenuItem(
            value: company["name"],
            child: Text(
              company['name'],
            ),
          ),
    

    and also make sure that your "_selectedCompany" is one item from your company list.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search