Symbols are special types to represent source names or identifiers at runtime.

It is used in API to identify by name.

Symbols are used in reflection functionality.

Symbols can be created in two ways. The first way, using new or without new with a parameter constructor

Syntax:

Symbol s=new Symbol("name")
Symbol s= Symbol("name")

the argument passed to the Symbol constructor contains the following

  • Library Name
  • Class Name
  • Function or method name
  • public instance member name
  • public constructor of a class
void main() {
  // using a new  operator
  Symbol symb1 = new Symbol('name1');
  // using without a new  operator
  Symbol symb2 = Symbol('name1');
  print(symb1);
  print(symb1.runtimeType);
  print(symb2);
  print(symb2.runtimeType);
}

Output:

Symbol("name1")
Symbol
Symbol("name1")
Symbol

The second way, using Symbol literal syntax. Any string can be made as a symbol by prefixing hash(#).

Syntax

Symbol s1=new Symbol(#name);

Here is an example

void main() {
  print(#name);
}

Output:

Symbol("name")

Symbol literals are compiled time constants.

How to Convert Symbol to String in Dart?

mirrors package provides MirrorSystem.getName(Symbol) method returns the symbol name.

Here is an example

import 'dart:mirrors';

void main() {
  // using new  operator
  Symbol symb1 = new Symbol('name1');
  // using without a new  operator
  String name = MirrorSystem.getName(symb1);
  print(name);
  print(name.runtimeType);
  print(symb1);
  print(symb1.runtimeType);
}

Output

name1
String
Symbol("name1")
Symbol