fvisticot
fvisticot

Reputation: 8536

How to retrieve current className in flutter?

I have a class:

class Dog {

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

}

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

Upvotes: 37

Views: 21405

Answers (6)

Sohaib Baig
Sohaib Baig

Reputation: 21

object.runtimeType.toString() or typeObject.toString() (for when the type is inferred from a Generic for example) does not work in release mode for Flutter for Web.

Flutter web runs on dart2js, which will minify your code to reduce the size of your code files. This cannot be turned off in release mode. Since minifying changes class, object and method names, your runtimeType.toString() will become meaningless and unrecognizable.

Ultimately, either avoid taking this path, pass class names as String, or if you absolutely must do this on Flutter web, build in profile mode (as this gives maximum performance with minification turned off).

Upvotes: 0

Baraa Aljabban
Baraa Aljabban

Reputation: 1152

I would like to add to the correct asnwer that is up there

this.runtimeType

is that for if you are dealing with statfull widgets and you want to know the page/widget name you can use the following as well to get the wiget name

widget.toString()

we do use it for a tracking purpose to track the most pages clicked on etc..

Upvotes: 3

ahmnouira
ahmnouira

Reputation: 3391

You can print the class name using this:

print('$runtimeType');

Upvotes: 1

sdennis0428
sdennis0428

Reputation: 11

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

Upvotes: 1

Ivan Yoed
Ivan Yoed

Reputation: 4395

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();

Upvotes: 3

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657058

this.runtimeType

or just

runtimeType

returns the name of the current class.

Upvotes: 69

Related Questions