Is there a way to get the class name of a dart class
as a String
or a Type
object..?
class MyClass {
}
var myClass = MyClass();
I know the property
, runtimeType
which return the type of the object as a Type
object. But is there a similar function for classes?
print(myClass.runtimeType.toString());
What I currently do is creating an object of the class and use runtimeType
.
String type = MyClass().runtimeType.toString();
Note: In python
there is a variable called __name__
in every class, which does what I need.
My final goal is to create dart objects using previously saved class names. In this issue they have proposed a method using Map
s.
The thing is that I have lots of classes and that method looks messy in my situation.
What I currently do is, save the object type by:
var saving = myClass.runtimeType.toString();
And when loading:
if (saving == MyClass().runtimeType.toString()) {
return MyClass();
}
From your experiences and opinions, can you propose a better solution?
String type = MyClass(). runtimeType. toString();
Dart objects have runtimeType property which returns Type . To check whether the object has a certain type, use == operator. Unlike is , it will only return true if compared to an exectly same type, which means comparing it with its super class will return false .
Type class Null safety Runtime representation of a type. Type objects represent types. A type object can be created in several ways: By a type literal, a type name occurring as an expression, like Type type = int; , or a type variable occurring as an expression, like Type type = T; .
Type class - dart:core library - Dart API Dart dart:core Type abstract class Type description Typeclass Null safety Runtime representation of a type. Type objects represent types. A type object can be created in several ways:
To check data type in dart language we can use root class property.Object is the base class in dart language every class automatically extends the object class.
Dart Programming - String. The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units. String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes.
Use the ‘.’ dot notation (called as the period) to access the data members of a class. Take a look at the following example to understand how to access attributes and functions in Dart −
The class type can be used as a Type
:
Type myType = MyClass;
You can use:
var runtimeTypeName = (MyClass).toString();
or for generics:
var runtimeTypeName = T.toString();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With