You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter如何获取项目根目录路径?等价于Python的os.path.dirname(os.path.abspath(__file__))

Flutter 获取项目根目录的实现方式

Flutter 没有直接对应 Python 中 os.path.dirname(os.path.abspath(__file__)) 的通用方案,因为跨平台特性导致不同运行环境的目录结构差异很大,以下分场景给出可行实现:

开发环境(本地调试)

通过 flutter run 启动本地调试时,Directory.current 默认指向项目根目录(即包含 pubspec.yaml 的文件夹),直接调用即可获取:

import 'dart:io';

void main() {
  String projectRoot = Directory.current.path;
  print('项目根目录: $projectRoot');
}

⚠️ 注意:该方法仅在开发阶段有效,打包后的应用运行时,Directory.current 指向的是应用的运行目录,而非原项目根目录。

读取项目内资源文件(推荐方案)

如果目的是访问项目根目录下的资源文件,无需直接获取根目录,用 Flutter 资源系统更可靠:

  1. 在 pubspec.yaml 中声明资源:
assets:
  - config.json
  1. 通过 rootBundle 加载资源:
import 'package:flutter/services.dart';

Future<String> loadConfig() async {
  return await rootBundle.loadString('config.json');
}

打包后应用的本地存储目录

若打包后的应用需要本地存储目录,使用 path_provider 包获取对应平台的标准目录(如文档目录、临时目录):

import 'package:path_provider/path_provider.dart';

Future<String> getAppDocDir() async {
  final dir = await getApplicationDocumentsDirectory();
  return dir.path;
}

内容的提问来源于stack exchange,提问作者Orl13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:25:28