Dart: Magic Constant Equivalents

261 Views Asked by At

PHP offers useful magic constants like:

__CLASS__
__FILE__
__METHOD__

and so on. Also the

get_class()

function provides a similar functionality.

Is there anything similar in Dart?

1

There are 1 best solutions below

0
On BEST ANSWER

Compiler constants similar to PHP not available. But you can do this manually (not constant value).

This slower but it works.

import 'package:stack_trace/stack_trace.dart';

void main() {
  print(__LINE__);
  print(__METHOD__);
  print(__FILE__);
  new Foo();
}

class Foo {
  Foo() {
    print(__CLASS__);
  }
}

String get __CLASS__ {
  var frames = new Trace.current().frames;
  if(frames.length > 1) {
    var member = frames[1].member;
    var parts = member.split(".");
    if(parts.length > 1) {
      return parts[1];
    }
  }

  return null;
}


String get __METHOD__ {
  var frames = new Trace.current().frames;
  if(frames.length > 1) {
    return frames[1].member;
  }

  return null;
}

String get __FILE__ {
  var frames = new Trace.current().frames;
  if(frames.length > 1) {
    return frames[1].uri.path;
  }

  return null;
}

int get __LINE__ {
  var frames = new Trace.current().frames;
  if(frames.length > 1) {
    return frames[1].line;
  }

  return null;
}
4
main
/home/andrew/dart/for_web/test/bin/test.dart
Foo