1

_formKey.currentState!.validate()

currentState is a State: https://api.flutter.dev/flutter/widgets/State-class.html

So, what is the use of ! after currentState?
! is used in front of boolean variables but State is not a boolean.

Please explain what is happening here.

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

4

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

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134