【问题标题】:My function not working even if it meets the condition flutter即使满足条件,我的功能也无法正常工作
【发布时间】:2021-10-27 22:28:18
【问题描述】:

我尝试添加一个功能,允许用户在我的应用中添加个人资料图片。

  late String? profileURL = '';
  late File userProfilePicture;

  ...

  Future pickAndUploadImage() async {
      final ImagePicker _picker = ImagePicker();
      try {
        XFile? image = (await _picker.pickImage(source: ImageSource.gallery));
        print('eee');
        await new Future.delayed(const Duration(seconds: 2));
        userProfilePicture = File(image!.path);
        print(userProfilePicture);
        print(File(image.path));

        if (userProfilePicture != File(image.path)) {
          print('It didnt work sorry');
          Navigator.pop(context);
        } 
        else {
          print('Should be startting to put file in');
          var snapshot = await storage
              .ref()
              .child('userProfiles/$userEmail profile')
              .putFile(userProfilePicture);
          print('file put in!');
          profileURL = await snapshot.ref.getDownloadURL();
        }

        setState(() {
          DatabaseServices(uid: loggedInUser.uid).updateUserPhoto(profileURL!);
          print(profileURL);
        });
      } catch (e) {
        print(e);
      }
    }

问题是,这条线:if (userProfilePicture != File(image.path)) 看起来不起作用。我不知道为什么,但这是我的输出:

> flutter: eee  
>flutter: 2 File: '/Users/kongbunthong/Library/Developer/CoreSimulator/Devices/..../tmp/image_picker_3912CA1D-AC60-4C84-823F-EB19B630FD1C-11650-0000061E644AD3FA.jpg'
> flutter: It didnt work sorry

第二行显示有2个文件相互重叠,这不是说这2个文件是一样的吗?

并且如果相同,应该打印出Should be starting to put the file in。但相反,它会打印出:It didn't work sorry

非常感谢任何帮助!

【问题讨论】:

  • userProfilePicture != File(image.path) 将永远为真。 File 继承了默认的 Object.operator == 实现,它检查对象身份,并且现有对象永远不会等于新构造的对象。你应该比较userProfilePicture.absolute.path != File(image).absolute.path。 (或者只是userProfilePicture.path != image.path,如果你能保证两者都已经是绝对路径。)

标签: firebase flutter dart google-cloud-firestore firebase-storage


【解决方案1】:

这两个文件是不同的File 对象,因此相等性检查将失败。

您可以像这样检查两个File 路径是否相同:

if (userProfilePicture.path != image.path)

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 2023-03-11
    • 2022-11-29
    • 2019-04-05
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多