【发布时间】:2021-10-01 04:41:26
【问题描述】:
我正在使用 Firebase,我有这样的 submitForm 方法:
// File variable declaration
File? _userImageFile;
void _submitForm() {
try {
final isVaild = _formKey.currentState!.validate();
// To close soft keyboard
FocusScope.of(context).unfocus();
if (_userImageFile == null && !_isLogIn) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Please pick an image'),
backgroundColor: Colors.black,
),
);
return;
}
if (isVaild) {
_formKey.currentState!.save();
widget._submitAuthForm(
_userName.trim(),
_userImageFile!,
_userEmail.trim(),
_userPassword.trim(),
_isLogIn,
);
}
} catch (e) {
print(e.toString());
}
}
我已经使用相同的表单处理了注册和登录,所以当我登录时_userImageFile 的值将为空,所以它给出了异常:Null check operator used on a null value
在这里我无法弄清楚如何处理这个问题?
【问题讨论】:
-
不使用“!”它给出了编译时错误,所以它不会工作。
-
不要使用
if (_userImageFile == null && !_isLogIn),您还应该检查文件路径是否为空。像那样if ((_userImageFile == null || _userImageFile.path.isEmpty) && !_isLogIn) -
这不会有任何区别。
-
如何让 _userImageFile 不可为空(
File? _userImageFile = File('');),用空路径初始化它,并在用户选择图像时更新其路径? -
感谢@ZeeshanAhmad 文件? _userImageFile = 文件('');这对我有用。
标签: flutter dart flutter-test dart-null-safety flutter-image