Reputation: 152
I added a float button in my application while clicking on it two text-field appear , without adding formKey the button works but when i use it to controle if the field text are empty or not by if statement if (formKey.currentState!.validate()) in the Debug Console i get this error
════════ Exception caught by gesture ═══════════════════════════════════════════
Unexpected null value.
═══════════════════════════════════════════════════════════════════════════════
this the code of floating button
floatingActionButton: FloatingActionButton(
onPressed: () {
if (isBottomSheetShown) {
if (formKey.currentState!.validate()) {
Navigator.pop(context);
isBottomSheetShown = false;
setState(() {
fabIcon = Icons.edit;
});
}
} else {
scaffoldKey.currentState!.showBottomSheet(
(context) => Container(
color: Colors.grey[100],
padding: const EdgeInsets.all(20),
child: Form(
key: formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: titleController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.title),
hintText: 'write a title',
labelText: 'Title',
border: OutlineInputBorder(),
),
),
SizedBox(
height: 15,
),
TextField(
controller: timeController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.watch_later_outlined),
hintText: 'write a time',
labelText: 'Time',
border: OutlineInputBorder(),
),
onTap: () {
showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
).then((value) {
timeController.text =
value!.format(context).toString();
print(value!.format(context));
});
},
),
],
),
),
),
);
}
isBottomSheetShown = true;
setState(() {
fabIcon = Icons.add;
});
},
child: Icon(
fabIcon,
)),
Upvotes: 4
Views: 5363
Reputation: 339
The Unexpected null value is occurring because you're asserting that formKey.currentState
is not null before you validate it, so if currentState equals null, it will throw that error.
I'd suggest first checking if formKey.currentState != null
before calling the validate method.
Upvotes: 1