Home > database >  Flutter - CastError (Null check operator used on a null value)
Flutter - CastError (Null check operator used on a null value)

Time:01-05

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;
  }

CodePudding user response:

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

CodePudding user response:

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;             
  • Related