【问题标题】:Convert String path to File FLUTTER将字符串路径转换为文件 FLUTTER
【发布时间】:2021-09-07 04:18:10
【问题描述】:

我的列表包含如下路径

/storage/emulated/0/Whatsapp/Media/Whatsapp Images/IMG-20210623-WA0016.jpg

将其转换为文件总是返回 false。

 for (var i = 0; i < tempLocations.length; i++) {
      print(tempLocations.length);

      File newFile = File(tempLocations[0]);
      if (await newFile.exists()) {
        print("true");
      } else {
        print("false");
      }
    }

如何将其转换为文件?

【问题讨论】:

    标签: firebase flutter file dart firebase-storage


    【解决方案1】:

    可以使用flutter_absolute_path获取excat路径

    在 iOS 或 Android 设备中查找文件绝对路径的 Flutter 插件。

    空安全版本

    flutter_absolute_path:
    git:
    url: https://github.com/kornperkus/flutter_absolute_path.git
    
         // Platform messages are asynchronous, so we initialize in an async method.
          Future<void> init() async {
            /// uri can be of android scheme content or file
            /// for iOS PHAsset identifier is supported as well
        
            List<Asset> assets = await selectImagesFromGallery();
            List<File> files = [];
            for (Asset asset in assets) {
    // asset.identifier replace with your path
              final filePath =
                  await FlutterAbsolutePath.getAbsolutePath(asset.identifier);
              files.add(File(filePath));
            }
        
            // If the widget was removed from the tree while the asynchronous platform
            // message was in flight, we want to discard the reply rather than calling
            // setState to update our non-existent appearance.
            if (!mounted) return;
        
            setState(() {
              _files = files;
            });
          }
    

    【讨论】:

    • 是的,我想过使用它,但它不支持空安全,所以即使我添加它也会在编译时抛出错误
    • 使用空安全版本更新了我的答案
    • 插件 flutter_absolute_path 使用了已弃用的 Android 嵌入版本。为避免意外的运行时失败或未来的构建失败,请尝试查看此插件是否支持 Android V2 嵌入。否则,请考虑将其删除,因为 Flutter 的未来版本将删除这些已弃用的 API
    • 在 repo 中有一个带有 nullsafety 和 v2 嵌入的 PR
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2012-11-23
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多