I am trying to use this dropdown menu that has a list populated from a QuerySnapshot. I think I have it all set up right but it is causing this error:
There should be exactly one item with [DropdownButton]'s value: .
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
I think this error has to do with the initialization of the Dropdown.
This is where I set the initial state of the dropdown. I assign the value from a document if it exists:
setState(() {
_selectedInspectorCompany =
trxnSnapshot.data()?['inspectorCompanyId'] ?? "";
});
This is the code for the dropdown.
Wrap(
children: [
const Text(
'Inspector Company: ',
),
StreamBuilder<QuerySnapshot>(
stream: _db.collection('inspectorCompany').snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
List<DropdownMenuItem<String>> inspectorCompanyItems =
[];
if (snapshot.hasData) {
final inspectorCompanyList = snapshot.data!.docs;
for (var inspectorCompany in inspectorCompanyList) {
inspectorCompanyItems.add(
DropdownMenuItem<String>(
value: inspectorCompany.id,
child: Text(
inspectorCompany['inspectorCompanyName'],
),
),
);
}
return DropdownButton<String>(
hint: const Text("Select Inspector"),
value: _selectedInspectorCompany,
onChanged: (inspectorCompanyValue) {
setState(() {
_selectedInspectorCompany =
inspectorCompanyValue;
});
ref
.read(trxnNotifierProvider.notifier)
.updateInspectorCompanyId(
_selectedInspectorCompany!);
},
items: inspectorCompanyItems,
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
],
),
I think I am doing this correct but why am I getting the error?
Thanks
UPDATE:
If I add an inspectorCompany id to the transaction document so that it matches one of the inspectorCompany ids in the list of inspector companies it works fine.
What am I doing wrong? I think it may have to do with how I am initializing the _selectedInspectorCompany variable in the first code snippet but I don’t know what I am doing wrong.
Thanks.
2
Answers
The error you have is because you have more than one value in the list. checks if there is a repeating value in the list that the DropdownButton loads.
I think the initial value of
_selectedInspectorCompany
is empty or null. Make it null when you initialise and try adding a null check and assign the first value like the following