There was an error when I inserted the DropdownButton code into my code.
Outside the code containing the body, they declared it as a class, and when I put the class declared in the code, an error message appeared as below.
'_AssertionError ('package:flutter/src/material/dropdown.dart': Failed assertion: line 890 pos 15: 'items == null || items.isEmpty || value == null ||
items.where((DropdownMenuItem<T> item) {
return item.value == value;
}).length == 1': There should be exactly one item with [DropdownButton]'s value: sex.
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value)'
Below is my code.
.....
....
onChanged: (_) {
setState(() {});
}
),
SelectButton(),
],
),
),
class SelectButtonState extends State<SelectButton> {
final List<String> _valueList = ['M', 'F'];
String _selectedValue = 'sex';
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
value: _selectedValue,
items: _valueList.map((value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedValue = value!;
});
},
);
}
}
class SelectButton extends StatefulWidget {
const SelectButton ({Key? key}) : super(key: key);
@override
State<SelectButton> createState() => SelectButtonState();
}
I want to make sex select button…
2
Answers
Your _valueList contains [‘M’, ‘F’] only and you are creating a DropDownButton out of it. When compiler finds initial value as "Select Sex" which is not available in the _valueList array, you get NULL error.
Solution -> Use ‘Select Sex’ as dropdown hint. Keep _selectedValue as null in intial declaration so that hint will be displayed.
Setting _selectedValue as null with null check:
Try this one