In Dart, Symbols are basically an object representation of either an identifier or operator. The symbols in dart are opaque and dynamic string names that cannot be changed and remains constant throughout the compile time. It can be used for reflecting the metadata on a type, such as a library or class. They are generally used for creating APIs and establish a relationship between a string that is understandable to humans and a string that can be used by computers.
Symbols can be used to get various information about a type (library, class, etc) such as a list of instance methods, constructors, etc.
Symbols can be created in 2 different ways –
1. Adding a Hash (#) symbol to an identifier would convert it into a Symbol
2. Otherwise, a symbol can be created explicitly using the Class constructor.
Symbol mySymbol = Symbol('mysymbol'); print(mySymbol);
In this example, we’ll be creating a Custom Library and then show its metadata using Symbols.
Here, we have first created a Dart File Custom.dart containing a library custom_lib, which consists of a class called CustomClass having methods customFunction1 and customFunction2.
Next, we’ll create the main.dart file, which will import the Custom. dart file along with a couple of other libraries such as dart:core and dart:mirror
- First, we’ll create 2 symbols. One for the custom library and the other for the custom class.
- Next, we’ve to initialize the mirror system, and create a mirror reference to our custom_lib library, and then using that, to our CustomClass class.
- Using classMirror, we can now extract some data i.e. a list of methods present in our class. That includes –
- User created methods such as customFunction1
- In-build methods such as toString
Total number of methods = 7 Symbol("==") Symbol("hashCode") Symbol("toString") Symbol("noSuchMethod") Symbol("runtimeType") Symbol("customFunction1") Symbol("customFunction2")