In my code, I have this DropdownFormField
so the user can select their gender:
DropdownButtonFormField<String>(
decoration: InputDecoration(labelText: 'Select gender'),
validator: (val) => val!.isEmpty ? 'Fill the field' : null,
isExpanded: true,
value: _selectedValue,
items: items.map(buildMenuItem).toList(),
onChanged: (val) {
setState(() {
gender = val;
});
},
)
in onChanged: (val)
, val
is expected to be a String?
, but gender
is a String
. is a use val as String
as gender = val as String
, apparently it works. But, if I press the save button without selecting an option, I get an error:
Null check operator used on a null value
As if the item isn"t going through validator
CodePudding user response:
The !
operator after a nullable value tells flutter to assume the value is not null and to throw an error if it is.
(val) => val!.isEmpty ? 'Fill the field' : null,
so when you call this with an empty option, it throws an error because val is null at this point in time. To fix this, simply change the validator to something like this:
(val) => (val==null || val.isEmpty) ? 'Fill the field' : null,
Also, something else is that there is no need to say val as String
if your type is String?
, that is literally the reason why !
exists, for situations in which you already know a nullable value is not null:
gender = val!;