The !
is called the postfix null assertion “bang” operator. The property currentState
is of type T?
, which means it can be null. Therefore if you do:
final _formKey = GlobalKey<FormState>();
_formKey.currentState.validate();
You will get the following error:
The method 'validate' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!').
To solve it, you can use the postfix null operator:
_formKey.currentState!.validate();
The postfix exclamation mark (!) takes the expression on the left and casts it to its underlying non-nullable type. So the above is the same as doing:
(_formKey.currentState as FormState).validate();
Check the docs for more info:
https://dart.dev/null-safety/understanding-null-safety#null-assertion-operator