简体   繁体   中英

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

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

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

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM