Flutter Form controller throws "The method 'validate' was called on null"
220
Have you tried building a custom validator function and then directly calling it from the validator property.
For example :-
Validator (String value) {
print(LOG + "validator called");
if(int.tryParse(value.trim()) == null) {
inputCompletionAlert += "But your default item deposit is not a number, please correct.\n";
return 'Not a £-- whole number monetary amount';
}
}
Author by
Sam
Updated on December 28, 2022Comments
-
Sam over 1 year
The method 'validate' was called on null. Receiver: null Tried calling: validate()
I don't understand this. I thought maybe the problem was the Form isn't the root element of the class, it's not
return Form(child: Column(children: [...
So I tried making the Form Widget the root, it stopped the error, but didn't activate the TextFormField validator or save, it just said 'everything fine, move along'.It's just one field I presently wish to validate. I've looked up other such queries, both the Form widget & the TextFormField have keys, so I'm stuck.
I declare the form key with
final _formKeyForDeposit = GlobalKey<FormState>();
And here is the un-cooperative form:
Form(key: _formKeyForDeposit, child: TextFormField( controller: _controllerDefaultDeposit, key: Key('defaultLoanDeposit'), decoration: InputDecoration( //icon: Icon(Icons.location_city), labelText: 'Per item deposit', hintText: 'Whole numbers', suffixIcon: IconButton( icon: Icon(Icons.clear), onPressed: () { _controllerDefaultDeposit.clear(); }, ), ), keyboardType: TextInputType.numberWithOptions(decimal: false, signed: false), onSaved: (String amountStr) { print("saving deposit"); user.defaultItemDeposit = int.parse(amountStr.trim()); }, validator: (String value) { print(LOG + "validator called"); if(int.tryParse(value.trim()) == null) { inputCompletionAlert += "But your default item deposit is not a number, please correct.\n"; return 'Not a £-- whole number monetary amount'; } if(value == "" || value == "0") { print(LOG + 'deposit validator called, should launch Dialog from here'); inputCompletionAlert += "Would you like to set a default deposit?"; return "Would you like to set a deposit?"; } return null; }, ), ),
-
Aman khan Roohaani about 3 yearsAlso what are you using int.tryParse() for??
-
Sam about 3 yearsTo detect whether the user hasn't given me a number, it returns null if it can't convert it to a number, at which point I fail validation, whilst avoiding throwing an exception. "tryParse: Parses a string containing a number literal into a number. Like parse except that this function returns null for invalid inputs instead of throwing."