A. currentState can be null, should use currentState! to avoid error
B. validate() should be validate without parentheses
C. Validator function must return a boolean, not a string
D. TextFormField missing controller property
Solution
Step 1: Check usage of currentState
currentState can be null if the form is not mounted, so calling validate() without null check causes error.
Step 2: Identify correct null safety usage
Using _formKey.currentState!.validate() asserts non-null and avoids runtime error.
Final Answer:
currentState can be null, should use currentState! to avoid error -> Option A
Quick Check:
Use currentState! to safely call validate() [OK]
Hint: Use currentState! to avoid null errors on validate() [OK]
Common Mistakes:
Calling validate() without null check
Thinking validator returns boolean
Misusing validate as property
5. You want to submit a form and show a success message only if all fields are valid. Which Flutter code snippet correctly performs this action?
hard
A. if (_formKey.currentState.validate) {
print('Success!');
}
B. if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Success!'))
);
}
C. if (_formKey.validate()) {
showDialog(context: context, builder: (_) => Text('Success!'));
}
D. if (_formKey.currentState!.validate()) {
Navigator.pushNamed(context, '/success');
}
Solution
Step 1: Validate form state correctly
Use _formKey.currentState!.validate() to check all fields are valid.
Step 2: Show success feedback
Use ScaffoldMessenger.of(context).showSnackBar() to display a success message to the user.
Step 3: Check other options
if (_formKey.currentState.validate) {
print('Success!');
} misses parentheses and null safety, C uses invalid method, D navigates instead of showing message.
Final Answer:
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Success!'))
);
} -> Option B
Quick Check:
Validate then show SnackBar for success [OK]
Hint: Validate with currentState! then show SnackBar for feedback [OK]
Common Mistakes:
Calling validate without parentheses or null check
Using invalid methods on form key
Showing message without ScaffoldMessenger
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.