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

如何在Dart中获取当前文件路径(类似PHP __FILE__/C宏)

How to get the path of the current Dart file (similar to FILE in PHP or C macros)

Great question! The issue with your current code is that Platform.script.toFilePath() returns the path of the entry script (the one you run directly, which is a.dart in your example), not the file where the path() function is defined (b.dart).

To fix this and make path() always return the path of b.dart no matter where it's called, you need to extract the file path from the current stack trace. Here's how you can do it:

Modified b.dart code

import 'dart:core';

String path() {
  // Capture the current stack trace
  final stackTrace = StackTrace.current;
  // Split the trace into individual lines
  final traceLines = stackTrace.toString().split('\n');
  
  // Find the line that corresponds to the `path()` function call
  // We skip the first line because it's the call to StackTrace.current itself
  final functionLine = traceLines.skip(1).firstWhere(
    (line) => line.contains('path'),
    orElse: () => throw StateError("Couldn't locate the path() function in the stack trace"),
  );
  
  // Use a regex to extract the file path from the line (format: (file_path:line:column))
  final filePathMatch = RegExp(r'\(([^:]+):\d+:\d+\)').firstMatch(functionLine);
  if (filePathMatch == null) {
    throw StateError("Failed to parse the file path from the stack trace");
  }
  
  return filePathMatch.group(1)!;
}

How it works:

  1. StackTrace.current captures the full call stack at the moment the function runs.
  2. We split the stack trace string into lines and look for the line that references our path() function.
  3. A regular expression extracts the file path from that line (the part before the line and column numbers).

Testing with a.dart

Your a.dart can stay exactly the same:

import './b.dart';
void main() => print(path());

When you run dart run a.dart, it will now print the full path to b.dart instead of a.dart.

Notes:

  • This method works perfectly in JIT mode (the default when using dart run). For AOT-compiled binaries (created with dart compile exe), stack traces might not include file paths (since debug info is stripped), so this approach won't work there. For compiled builds, you'd need to pass the file path as a constant at compile time if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:44:08