30

I have a class:

class Dog {

Dog() {
  print("Current classname is: ${this.className}");
}

}

It seems this.className is not allowed. Is there something equivalent ?

4 Answers 4

53
this.runtimeType

or just

runtimeType

returns the name of the current class.

1
  • 1
    This does not work for static methods. (The use case is for log messages and meta data)
    – Worik
    Oct 31, 2022 at 20:03
3

If you want to initialize a variable at the beginning of the class and not in the build method (for instance), the way to go is simply doing as follows:

String className = (YourClass).toString();
1

Please see the attached picture of standalone code that shows an implementation of just getting the class name from this function:

void printArea(Shape shape){
  String shapeClass = (shape).runtimeType.toString();
  print('The area of the $shapeClass is: ${shape.area}');
}

Full code on DartPad

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 3, 2022 at 6:04
1

You can print the class name using this:

print('$runtimeType');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.