Symbol object is used to specify an operator or identifier declared in a Dart programming language. Generally, we do not need to use symbols while Dart programming, but they are helpful for APIs. It usually refers to identifiers by name, because identifier names can vary but not identifier symbols.
Dart symbols are dynamic string name that is used to derive the metadata from a library. It mainly accumulates the connection between human-readable strings that are enhanced to be used by computers.
Symbols have a term which is called Reflection; it is a technique that used to the metadata of at run-time, for example - the number of methods used in class, a number of constructors in a class, or numbers of arguments in a function.
The dart:mirrors library has all of the reflection related classes. It can be used with the command-line applications as well as web applications.
The hash(#) symbol, followed by the name is used to define Symbol in Dart. The syntax is given below.
Here, the valid identifier such as function, valid class, public member name, or library name can be used in place of name value.
Let's understand the following example.
In the above code, we have declared a class Foo in a library foo_lib. The class contains the methods m1, m2, and m3. We save the above file as foo.dart.
Now, we are creating new file FooSymbol.dart and run the following code.
The above code will show the following output.
Found Library checkng...class details.. No of classes found is : 1 Symbol("Foo") // Displays the class name class found..
Example - 2 : Print the number of instance methods of class
In the following example, The Dart provides predefine class ClassMirror which helps us to display the number of instance methods of class.
Found Library checkng...class details.. No of classes found is : 1 Symbol("Foo") found class No of instance methods found is 8 Symbol("==") Symbol("hashCode") Symbol("toString") Symbol("noSuchMethod") Symbol("runtimeType") Symbol("m1") Symbol("m2") Symbol("m3")
Dart Convert Symbol to String
We can convert the Dart symbol into the string by using a built-in class MirrorClass, which is provided by the dart:mirror package. Let's understand the following example.