【问题标题】:How to handle null safety for File in flutter?如何在颤动中处理文件的空安全性?
【发布时间】: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


【解决方案1】:

花了几个小时后,我得到了一些解决方案,我希望这对其他人也有帮助:

  1. 通过编辑 pubspec.yml sdk: ">=2.3.0 <3.0.0" 删除空安全性
  2. 为登录和注册创建 2 个不同的函数,而不是单个 SubmitForm()
  3. 正如@ZeeshanAhmad 建议的File? _userImageFile = File('');

【讨论】:

  • 如果你使用_userImageFile = File(''),那么_userImageFile应该使用不可为空的类型。
猜你喜欢
  • 1970-01-01
  • 2021-07-14
  • 2021-12-08
  • 2021-12-14
  • 2021-06-12
  • 2017-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
相关资源
最近更新 更多