【问题标题】:Flutter desktop windows get application pathFlutter 桌面窗口获取应用程序路径
【发布时间】:2020-05-06 20:07:36
【问题描述】:

我正在为 Windows 创建一个 Flutter Desktop 应用程序,并且我正在尝试检索 exe 所在的应用程序目录。我尝试使用 path_provider 但只能获取 Documents 目录。任何帮助我都将不胜感激。

【问题讨论】:

  • 您想要那个位置的原因是什么?如果您尝试加载与应用位置相关的资源,则有标准的 Flutter 机制来加载捆绑的资源。

标签: flutter dart


【解决方案1】:

使用 Platform.resolvedExecutabledart:io)。

我已经在 Flutter/Windows 中对其进行了测试,并且可以正常工作。 奇怪的是,Platform.executable 反而返回了null。我说得很奇怪,因为它的类型是 String 不可为空。这个意外的 null 值可能会导致难以检测的崩溃或错误(但最终 Flutter 桌面不在稳定通道中)。

【讨论】:

    【解决方案2】:
    String dir = Directory.current.path;
    print(dir);
    

    Directory.current.path(在dart:io 包中)返回项目文件夹的当前工作目录(开发时)或从发布版本运行时的可执行目录。

    【讨论】:

    • 请考虑添加额外的 cmets 来说明为什么这是正确的答案。仅代码的答案会降低它的用处。
    • 这个答案不正确;这将返回当前工作目录,该目录可能与应用程序的位置有关,也可能无关。
    • 这个和Platform.resolvedExecutable(来自dart:io)的区别在于Directory.current.path在开发时默认为项目文件夹的根目录,但在发布时默认为可执行文件所在的文件夹(开发时是runner文件夹)。另外Platform.resolvedExecutable 是.exe 的绝对路径而不是目录,所以你必须在那里做一些小工作。两者都会让你到达那里。
    【解决方案3】:

    试用包:path_provider

    1. 在 pubspec.yaml 中设置此代码
    dependencies:
      path_provider: ^1.6.27 # get last Version From https://pub.dev/packages/path_provider/install
    
    1. 代码
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path; //C:\Users\USER_NAME\AppData\Local\Temp
    
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path; //C:\Users\USER_NAME\Documents
    //Warning: on debug mode this code get location project but in release mode will get your location app correctly
    String dir = Directory.current.path; // PATH_APP
    

    【讨论】:

    • Directory.current 返回当前目录,它可能是也可能不是应用程序的位置。例如,如果我的应用在C:\my_app_folder 中,我使用终端从C: 启动应用,执行my_app_folder\my_app.exe,则Directory.current 返回`C:`
    猜你喜欢
    • 2020-10-14
    • 2016-10-07
    • 2022-08-07
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多