firebase Flutter- CastError(空值上使用的空检查运算符)

lnlaulya  于 2023-01-05  发布在  Flutter
关注(0)|答案(3)|浏览(114)

我正在为一个flutter应用程序构建一个配置文件页面,用户从他们的图库上传一张图片,然后图片被上传到FirebaseStorage。我遇到了一个问题,我收到了一个CastError,这是基于对空值使用空值检查操作符。问题变量是imageFile,但我已经使用If语句进行了检查,但我还是收到了这个错误。
下面是我的代码:

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

yb3bgrhw1#

即使你选中了,你还是会继续执行函数,如果你想让函数在这里停止,你需要返回函数,就像

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

例如

qvtsj1bj

qvtsj1bj2#

您正在检查,但控件正在进一步流动,因此return或在imageFile!.path之前使用内联if条件

溶液1:
String fileName = imageFile!=null ? Path.basename(imageFile!.path):'';
溶液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
}
txu3uszq

txu3uszq3#

相反,我认为只需将其命名为_uploadImageToFirebase(),使用下面的内容就可以解决您的问题。

imageFile!=null?
    _uploadImageToFirebase():
    Fluttertoast.showToast(msg: 'Please upload an image');

相关问题