rid
rid

Reputation: 63442

Path to current file in Dart

How can I get the path to the current file? (similar to the __FILE__ constant in PHP or macro in C) For example:

a.dart:

import './b.dart';

void main() => print(path());

b.dart:

import 'dart:io';

String path() => Platform.script.toFilePath();

The above code prints the path to the invoking script, a.dart. How can I change b.dart to get the path to b.dart instead, such that wherever I call path() from within the project, I'll always get the correct path to b.dart?

Upvotes: 7

Views: 1470

Answers (1)

mezoni
mezoni

Reputation: 11220

This may not work in all cases (I means the platforms and executable formats), but it is as easy as shelling pears:

import 'package:stack_trace/stack_trace.dart';

void main(List<String> args) {
  final frame = _frame(); // <==== /E:/prj/dart_test/bin/main.dart at line 4
  print('file: ${frame.uri.path}');
  print('lime: ${frame.line}');
}

Frame _frame() {
  return Frame.caller(1);
}

Result:

file: /E:/prj/dart_test/bin/main.dart
lime: 4

Upvotes: 5

Related Questions