Open In App

Dart – Symbols

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.



Creating Symbols

Symbols can be created in 2 different ways –

1. Adding a Hash (#) symbol to an identifier would convert it into a Symbol



print(#mysymbol);

Output:

Symbol("mysymbol")

2. Otherwise, a symbol can be created explicitly using the Class constructor.

Symbol mySymbol = Symbol('mysymbol');
print(mySymbol);

Output:

Symbol("mysymbol")

Example:

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.




library custom_lib;
  
class CustomClass {
  void customFunction1() {
    print("Custom Function 1");
  }
  
  void customFunction2() {
    print("Custom Function 2");
  }
}

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




import 'dart:core';
import 'dart:mirrors';
import 'Custom.dart';
  
void main() {
    
  // Create symbols for library and class
  Symbol libraryName = Symbol('custom_lib');
  Symbol className = Symbol('CustomClass');
  
  // Init mirror system
  MirrorSystem mirrorSystem = currentMirrorSystem();
  LibraryMirror libMirror = mirrorSystem.findLibrary(libraryName);
  ClassMirror classMirror = libMirror.declarations[className];
  
  // Get and print methods
  final methods = classMirror.instanceMembers;
  print('Total number of methods = ${methods.length}');
  methods.forEach((symbol, method) {
    print(symbol);
  });
}

Output:

Total number of methods = 7
Symbol("==")
Symbol("hashCode")
Symbol("toString")
Symbol("noSuchMethod")
Symbol("runtimeType")
Symbol("customFunction1")
Symbol("customFunction2")

Article Tags :