Search code examples
flutterdartflutter-testdart-null-safetyflutter-image

How to handle null safety for File in flutter?


I am working with Firebase and I have submitForm method like this:


// 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());
    }
  }

I have handled Signup & Login using same form, so when I am login value of _userImageFile will be null, so it gives exception: Null check operator used on a null value

Here I am not able to figure out how to handle this in flutter?


Solution

  • After spent couple of hours I have got few solutions, I hope this will help others too:

    1. Removing null safety by editing pubspec.yml sdk: ">=2.3.0 <3.0.0"
    2. Creating 2 different function for Login and Signup instead of single SubmitForm()
    3. As @ZeeshanAhmad suggested File? _userImageFile = File('');