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
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
for example
You are checking, but the control is flowing further so either
return
or use inline if condition beforeimageFile!.path
Solution 1 :
Solution 2:
Instead just calling this
_uploadImageToFirebase()
Use something like below will solve your problem I think.