DropdownButton throwing an error on initializing

44 Views Asked by At

I have a dropdownButton that is throwing an error: enter image description here

Here is the code for the dropdown:

StreamBuilder<QuerySnapshot>(
                    // Get a list of available companies to assign the new user to a company
                    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 CircularProgressIndicator();
                      }
                      return DropdownButton<String>(
                        hint: const Text("Select Company"),
                        value: _selectedCompany,
                        onChanged: (companyValue) {
                          setState(() {
                            _selectedCompany = companyValue;
                            ref
                                .read(globalsNotifierProvider.notifier)
                                .updatecompanyId(companyValue!);
                          });
                        },
                        items: companyItems,
                      );
                    }),

I am getting the data from the DB ok. I have even tried initializing _selecedCompany like this but I still get the error.

String? _selectedCompany ='Select Company';

How do I get rid of this error? Thanks

UPDATE: I have updated my code to this:

String? _selectedCompany;

but I still get the error.

1

There are 1 best solutions below

2
On

The error says that the dropdown value has been found zero, two or more times and the dropdown should only have one time that value in the items list.

So you would just need to wait for the value of the selected company to be updated or initialize with a valid value:

String? _selectedCompany; // so the dropdown starts with a null value (no selection)

or maybe in the logic that populates the dropdown:

for (var company in companyList) {
  if(company.isSelected){
    _selectedCompany = company.id;
  }
  companyItems.add(
    DropdownMenuItem(
      value: company.id,
      child: Text(
        company['name'],
      ),
    ),
  );

}