【问题标题】:Flutter - CastError (Null check operator used on a null value)Flutter - CastError(用于空值的空检查运算符)
【发布时间】:2023-01-05 18:47:17
【问题描述】:

我正在为一个 flutter 应用程序构建一个配置文件页面,用户在其中从他们的图库上传图像并将其上传到 FirebaseStorage。我遇到一个问题,我得到一个基于对空值使用空检查运算符的 CastError。有问题的变量是图像文件但我已经使用 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;
  }

【问题讨论】:

    标签: flutter firebase dart google-cloud-firestore


    【解决方案1】:

    即使你检查你仍然继续它之后的功能。如果你想让它停在那里,你需要返回函数,就像

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

    例如

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 2021-02-25
      • 2022-06-15
      • 2022-01-05
      • 2021-08-30
      • 2021-11-06
      • 2021-06-17
      • 2021-01-24
      相关资源
      最近更新 更多