Dart Enums And Symbols
\\
Enumerations (enum) are used to define a set of named constant values, making code more readable.\\
\\
This chapter introduces Dart enum definitions, enhanced enums (with methods and properties), and Symbol and Rune types.\\
\\
* * *\\
\\
## enum Definition\\
\\
An enumeration is a special class used to represent a fixed number of constant values.\\
\\
The most typical scenario is representing limited options like status, direction, color, etc.\\
\\
## Instance\\
\\
// Define enum\\
\\
enum Status {\\
\\
pending,// Pending\\
\\
approved,// Approved\\
\\
rejected,// Rejected\\
\\
cancelled,// Cancelled\\
\\
}\\
\\
void main(){\\
\\
// Useenum value\\
\\
Status currentStatus = Status.pending;\\
\\
print('current State: $currentStatus');\\
\\
// via .index get Index (starting from 0)\\
\\
print('IndexValue: ${currentStatus.index}');// 0\\
\\
// via .values get all enum values\\
\\
print('all States: ${Status.values}');\\
\\
// iterate through all enum values\\
\\
for(var status in Status.values){\\
\\
print('TUTORIAL State: $status, Index: ${status.index}');\\
\\
}\\
\\
// viaCharacterstring to get enum value\\
\\
Status parsed = Status.values.byName('approved');\\
\\
print('parsed State: $parsed');\\
\\
// in switch inUseEnum\\
\\
switch(currentStatus){\\
\\
case Status.pending:\\
\\
print('order Pending');\\
\\
break;\\
\\
case Status.approved:\\
\\
print('order Approved');\\
\\
break;\\
\\
case Status.rejected:\\
\\
print('Order Rejected');\\
\\
break;\\
\\
case Status.cancelled:\\
\\
print('order Cancelled');\\
\\
break;\\
\\
}\\
\\
}\\
\\
current State: Status.pending IndexValue: 0all States: [Status.pending, Status.approved, Status.rejected, Status.cancelled] TUTORIAL State: Status.pending, Index: 0 TUTORIAL State: Status.approved, Index: 1 TUTORIAL State: Status.rejected, Index: 2 TUTORIAL State: Status.cancelled, Index: 3parsed State: Status.approved order Pending\\
> Enums and switch are a perfect match. When you handle all enum values in a switch, the Dart compiler checks if you've covered all cases. This prevents bugs caused by missing branches.\\
\\
* * *\\
\\
## Enhanced Enums (with Methods and Properties)\\
\\
Dart 3.0 introduced Enhanced Enums, allowing enums to have fields, methods, and constructors.\\
\\
## Instance\\
\\
// EnhancedEnhancedEnum:canhavemember variables,constructorsandmethods\\
\\
enum HttpStatus {\\
\\
// enum value via constructor passing parameters\\
\\
ok(200,'Request successful'),\\
\\
created(201,'Resource created'),\\
\\
badRequest(400,'Request Error'),\\
\\
unauthorized(401,'Unauthorized'),\\
\\
notFound(404,'Resource not found'),\\
\\
serverError(500,'Server Internal Error');\\
\\
// member variables:each enum value has code and message\\
\\
final int code;\\
\\
final String message;\\
\\
// Constructor: must be const\\
\\
const HttpStatus(this.code,this.message);\\
\\
// Enum Method\\
\\
bool get isSuccess => code >=200&& code <300;\\
\\
bool get isClientError => code >=400&& code <500;\\
\\
bool get isServerError => code >=500;\\
\\
// static method: find enum by State code\\
\\
static HttpStatus? fromCode(int code){\\
\\
try{\\
\\
return HttpStatus.values.firstWhere((s)=> s.code== code);\\
\\
}catch(_){\\
\\
return null;\\
\\
}\\
\\
}\\
\\
}\\
\\
void main(){\\
\\
var status = HttpStatus.notFound;\\
\\
print('TUTORIAL HTTP State: $status');\\
\\
print('Statecode: ${status.code}');\\
\\
print('Message: ${status.message}');\\
\\
print('Is successful: ${status.isSuccess}');\\
\\
print('Is client error: ${status.isClientError}');\\
\\
// UseStatic Method Lookup\\
\\
var found = HttpStatus.fromCode(201);\\
\\
if(found !=null){\\
\\
print('find State: ${found.message}');\\
\\
}\\
\\
var unknown = HttpStatus.fromCode(999);\\
\\
print('unknown State code: $unknown');\\
\\
}\\
\\
TUTORIAL HTTP State: HttpStatus.notFound Statecode: 404Message: Resource not foundIs successful: falseIs client error: truefind State: Resource createdunknown State code: null\\
Enhanced enums upgrade enums from "named constant collections" to "types with behavior", allowing you to encapsulate logic related to that enum.\\
\\
> Enhanced enum constructors must be const, and member variables must be final. This is because enum values themselves are compile-time constants.\\
\\
* * *\\
\\
## Symbol Type\\
\\
Symbol represents identifiers (variable names, function names, etc.) in Dart programs.\\
\\
It is not commonly used in daily development, mainly in reflection and code generation scenarios.\\
\\
## Instance\\
\\
void main(){\\
\\
// Use # Prefix Creating Symbol\\
\\
Symbol sym1 = #tutorial;\\
\\
Symbol sym2 = #helloWorld;\\
\\
print('Symbol 1: $sym1');// Symbol("tutorial")\\
\\
print('Symbol 2: $sym2');// Symbol("helloWorld")\\
\\
// Symbol Comparison\\
\\
Symbol sym3 = #tutorial;\\
\\
print('sym1 == sym3: ${sym1 == sym3}');// true\\
\\
// Symbol Can Be Used as Map Key\\
\\
var metadata ={\\
\\
#author:'TUTORIAL',\\
\\
#version:'1.0.0',\\
\\
#description:'Dart Tutorial',\\
\\
};\\
\\
print('Author: ${metadata[#author]}');\\
\\
}\\
\\
Symbol 1: Symbol("tutorial")Symbol 2: Symbol("helloWorld") sym1 == sym3: trueAuthor: TUTORIAL\\
> Symbols are typically minified after Dart compilation, so don't rely on the result of Symbol("tutorial").toString() for logic judgment. The correct usage of Symbol is for reflection operations through the dart:mirrors library.\\
\\
* * *\\
\\
## Rune and Unicode\\
\\
Rune is the type used to represent Unicode code points in Dart.\\
\\
In Dart, strings are UTF-16 encoded sequences.\\
\\
For characters outside the Basic Multilingual Plane (BMP), such as emojis, you need to use Rune to handle them.\\
\\
## Instance\\
\\
void main(){\\
\\
// Get Unicode Code Points of Character String\\
\\
String text ='TUTORIAL';\\
\\
print('Character: $text');\\
\\
print('Code Point List: ${text.runes.toList()}');\\
\\
// iterate through each Character and its code point\\
\\
for(var char in text.runes){\\
\\
print('${String.fromCharCode(char)} -> U+${char.toRadixString(
YouTip