A. Validator should return a boolean, not a string
B. Missing null check for value before calling isEmpty
C. TextFormField requires an onChanged callback
D. Validator cannot be used without a Form widget
Solution
Step 1: Check validator parameter type
The validator receives a nullable String? value, so it can be null.
Step 2: Identify missing null check
The code calls value.isEmpty without checking if value is null, causing a runtime error.
Final Answer:
Missing null check for value before calling isEmpty -> Option B
Quick Check:
Always check for null before isEmpty [OK]
Hint: Check for null before using isEmpty on value [OK]
Common Mistakes:
Ignoring nullable value in validator
Expecting validator to return boolean
Thinking onChanged is mandatory
5. You want to create a form with a TextFormField that only accepts numbers and shows a hint 'Enter age'. Which code snippet correctly implements this?
hard
A. TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(hintText: 'Enter age'),
validator: (value) {
if (value == null || value.isEmpty) return 'Age required';
if (int.tryParse(value) == null) return 'Enter a valid number';
return null;
},
)
Step 1: Identify required properties for numeric input with hint
The correct implementation requires keyboardType: TextInputType.number, decoration: InputDecoration(hintText: 'Enter age'), and a validator checking for null/empty and valid integer parse.
Step 2: Verify validator handles all cases
Validator must return error for null, empty, or non-numeric input using if (value == null || value.isEmpty) and int.tryParse(value) == null.
Final Answer:
TextFormField(
keyboardType: TextInputType.number,
decoration: InputDecoration(hintText: 'Enter age'),
validator: (value) {
if (value == null || value.isEmpty) return 'Age required';
if (int.tryParse(value) == null) return 'Enter a valid number';
return null;
},
) -> Option A
Quick Check:
number keyboard + exact hint + null/empty/parse validator [OK]
Hint: Use keyboardType.number and validate parsing for numbers [OK]
Common Mistakes:
Using text keyboard for numeric input
Not validating numeric format
Confusing hintText and labelText
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.