Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path to current file in Dart

Tags:

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?

like image 219
rid Avatar asked Mar 30 '19 07:03

rid


People also ask

How do I get the current directory on DART?

Directory. current. path does it if you want a string, Directory. current for a Directory.

How do you find the path of a File in flutter?

/data/user/0/ is a path to the internal Android directory with private folders and apps data, /storage/emulated/0/ is a path to the app storage for documents, downloads and other common folders.

How do I open a dart File?

Open the file with openRead, which returns a stream that provides the data in the file as chunks of bytes. Read the stream to process the file contents when available. You can use various transformers in succession to manipulate the file content into the required format, or to prepare it for output.


1 Answers

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
like image 175
mezoni Avatar answered Sep 22 '22 00:09

mezoni