Flutter接入Firebase实现登录注册 文件为空时无法登录报错
问题根因
错误由登录模式下_userImage强制解空触发:注册模式下有前置的_userImage非空判断逻辑,只有图片不为空才会走到后续提交逻辑,因此不会报错;但登录模式会跳过图片非空校验,此时_userImage大概率为null,你在传参时直接用_userImage!强制解包空值,就会抛出Null check operator used on a null value错误。
修复方案
修改提交时的_userImage传参逻辑,登录模式下直接传null即可,修改后的完整代码如下:
bool isLoginMode = true; String? _userEmailId; String? _userName; String? _userPassword; File? _userImage; void _submitForm() { final isValid = _form.currentState!.validate(); FocusScope.of(context).unfocus(); if (_userImage == null && !isLoginMode) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Please select Image')), ); return; } if (isValid) { _form.currentState!.save(); widget.submitFn( _userEmailId!, _userName ?? '', _userPassword!, // 仅注册模式传非空图片,登录模式传空 isLoginMode ? null : _userImage!, isLoginMode, context, ); } }
补充注意事项
- 同步检查
submitFn方法的入参定义,确保图片参数类型为可空的File?,如果之前定义为非空File需要同步修改,否则会出现编译错误 - 可额外对
_userEmailId、_userPassword增加空校验兜底,避免表单保存异常时同样出现强制解包空值的错误
内容的提问来源于stack exchange,提问作者Mustafa Shaikh
相关产品推荐
相关产品推荐

