'Flutter formkey exception displayed _CastError (Null check operator used on a null value)
I have created a form by wrapping a column widget in Form() as so
Form(
key: formKey,
child: Column(
children: [
But when I try to set final isValid = formKey.currentState!.validate(); to check, I get an exception has occured message _CastError (Null check operator used on a null value)
Any advice? Example Pic
Solution 1:[1]
Thanks in part to Void Void the solution is instead of declaring a variable isVaild. Check formKey.currentState!.validate() on press for the button as so
onPressed: () {
if (!formKey.currentState!.validate()) return;
AccountUpdate.updatePassword(
_confirmController.text, context);
},
Solution 2:[2]
At that point the currentState is null, you are attempting to validate the form before it's built. It would make more sense to validate the form in a callback when some submit button is clicked, etc. Check Link to flutter docs for an example.
Solution 3:[3]
you need to create function like this and call when some submit button is clicked, etc. Thanks.
void _saveForm() {
final isValid = formKey.currentState!.validate();
if (!isValid) {
// ignore: avoid_returning_null_for_void
return null;
}
_form.currentState!.save();
// .... extra code
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JoeCodes |
| Solution 2 | void void |
| Solution 3 | Meet Patel |
