skip to Main Content

I am building a profile page for a flutter app where a user uploads an image from their gallery and it gets uploaded to FirebaseStorage. I am facing a problem where I’m getting a CastError that’s based on using the null check operator on a null value. The variable in question is imageFile but I already did a check using an If statement but I’m getting that error.

Here’s my code:

  String name = '';
  String email = '';
  String? image = '';
  File? imageFile;
  String? imageUrl;
  String? userNameInput = '';

  //Upload image to Firebase
  Future<String?> _uploadImageToFirebase() async {
    if (imageFile == null) {
      Fluttertoast.showToast(msg: 'Please upload an image');
    }
**//This is where I'm getting the CastError**
    String fileName = Path.basename(imageFile!.path);

    var reference =
        FirebaseStorage.instance.ref().child('profileImages/$fileName');
    UploadTask uploadTask = reference.putFile(imageFile!);
    TaskSnapshot taskSnapshot = await uploadTask.whenComplete(() => null);
    await taskSnapshot.ref.getDownloadURL().then((value) {
      imageUrl = value;
    }).catchError((e) {
      Fluttertoast.showToast(msg: e.toString());
    });

    FirebaseFirestore.instance
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .set({'userImage': imageUrl});
    return imageUrl;
  }

3

Answers


  1. Even though you check you still continue the function after it. You need to return the function if you want it to stop there, so like

    if (imageFile == null) {
      Fluttertoast.showToast(msg: 'Please upload an image');
      return null;
    }
    

    for example

    Login or Signup to reply.
  2. You are checking, but the control is flowing further so either return or use inline if condition before imageFile!.path

    Solution 1 :

     String fileName = imageFile!=null ? Path.basename(imageFile!.path):'';
    

    Solution 2:

    if (imageFile == null) {
      Fluttertoast.showToast(msg: 'Please upload an image');
      return null;  👈 return here ,use this only when you want to stop the rest of the execution of the function if the imageFile is null
    }
    
    Login or Signup to reply.
  3. Instead just calling this _uploadImageToFirebase() Use something like below will solve your problem I think.

    imageFile!=null?
        _uploadImageToFirebase():
        Fluttertoast.showToast(msg: 'Please upload an image');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search