I'm creating two dropdown menues with the condition that the values in the second dropdown menu changes according to selected value in the first dropdown menu. I however keep getting this errro that LateInitializationError: Field 'selecItem' has not been initialized. This happens after I select the value in the first dropdown menu.
I don't understand it. can someone please explain it to me?
late List<String> department;
late String? selectedDepartment;
late List<String> adminTitle;
late List<String> technicalTitle;
@override
void initState(){
super.initState();
department = [
widget.technicalDept,
widget.adminDept
];
selectedDepartment = department[0];
if (selectedDepartment == department[0]) {
selecItem = [
widget.selectTitleString,
widget.backEndDevString,
widget.frontEndDevString,
widget.networkEngString,
widget.computerEngString,
];
values = technicalTitle[0];
}
if (selectedDepartment == department[1]) {
selecItem = [
widget.selectTitleString,
widget.regionalAdminString,
widget.sectorAdminString
];
values = adminTitle[0];
}
}
**in the build widget**
Row( children: [
SizedBox(
width: screenWidth * 0.1,//I defined media query for this
child: Text("${widget.departmentString}:")),
DropdownButton<String>(
value: selectedDepartment,
items: department.map((e) {
return DropdownMenuItem(value: e, child: Text(e));
}).toList(),
onChanged: (value) {
setState(() {
selectedDepartment = value;
});
},
),
selectedDepartment != department[0]
? Row(
children: [
SizedBox(
width: screenWidth * 0.1,
child:
Text("${widget.selectTitleString}:")),
DropdownButton<String>(
value: values,
items: selecItem!.map((e) {
return DropdownMenuItem(
value: e, child: Text(e));
}).toList(),
onChanged: (value) {
setState(() {
values = value;
});
},
),
],
)
: const SizedBox()
],
),
your code failed due to an uninitialized late variable (selecItem) Make selecItem nullable and initializing it in initState and within the onChanged callback of the first dropdown to ensure it's always set before use
Here is sample
You can make a sample call here