如何解析意外的空值



我在我的应用程序中添加了一个浮动按钮,同时单击它两个文本字段出现,而不添加formKey按钮工作,但当我使用它来控制字段文本是否为空或不通过if语句if (formKey. currentstate !.validate())在调试控制台我得到这个错误

════════ Exception caught by gesture ═══════════════════════════════════════════
Unexpected null value.
═══════════════════════════════════════════════════════════════════════════════

这是浮动按钮的代码

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,
)),

出现了意想不到的null值,因为您在验证formKey.currentState之前断言它不是null,所以如果currentState等于null,它将抛出该错误。

我建议在调用validate方法之前先检查formKey.currentState != null

最新更新