How to handle null safety for File in flutter?

Issue

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('');

Answered By – Divyesh_08

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.