Dart Enums and Symbols
An enum defines a set of named constant values, making code more readable.
This chapter introduces how to define Dart enums, enhanced enums (with methods and properties), and the Symbol and Rune types.
enum definition
An enum is a special kind of class used to represent a fixed number of constant values.
The most typical use case is representing a limited set of options such as status, direction, and color.
Example
// Define an enum
enum Status
{
pending
,
// Pending
approved
,
// Approved
rejected
,
// Rejected
cancelled
,
// Cancelled
}
void
main
(
)
{
// Use enum values
Status currentStatus
=
Status.
pending
;
(
'Current status: $currentStatus'
)
;
// Get the index via .index (starting from 0)
(
'Index value: ${currentStatus.index}'
)
;
// 0
// Get all enum values via .values
(
'All statuses: ${Status.values}'
)
;
// Iterate over all enum values
for
(
var
status
in
Status.
values
)
{
(
'RUNOOB status: $status, index: ${status.index}'
)
;
}
// Get an enum value from a string
Status parsed
=
Status.
values
.
byName
(
'approved'
)
;
(
'Parsed status: $parsed'
)
;
// Use enums in switch
switch
(
currentStatus
)
{
case
Status.
pending
:
(
'Order pending'
)
;
break
;
case
Status.
approved
:
(
'Order approved'
)
;
break
;
case
Status.
rejected
:
(
'Order rejected'
)
;
break
;
case
Status.
cancelled
:
(
'Order cancelled'
)
;
break
;
}
}
当前状态: Status.pending
索引值: 0
所有状态: [Status.pending, Status.approved, Status.rejected, Status.cancelled]
RUNOOB 状态: Status.pending, 索引: 0
RUNOOB 状态: Status.approved, 索引: 1
RUNOOB 状态: Status.rejected, 索引: 2
RUNOOB 状态: Status.cancelled, 索引: 3
解析出的状态: Status.approved
订单待处理
Enums and switch are a perfect match. When you handle all enum values in a switch, the Dart compiler checks whether you have covered every case, avoiding 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.
Example
// Enhanced enum: can have member variables, constructors, and methods
enum HttpStatus
{
// Enum values pass arguments via the constructor
ok
(
200
,
'Request succeeded'
)
,
created
(
201
,
'Resource created'
)
,
badRequest
(
400
,
'Bad request'
)
,
unauthorized
(
401
,
'Unauthorized'
)
,
notFound
(
404
,
'Resource not found'
)
,
serverError
(
500
,
'Internal server error'
)
;
// Member variables: every 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: look up an enum by status code
static
HttpStatus
?
fromCode
(
int
code
)
{
try
{
return
HttpStatus.
values
.
firstWhere
(
(
s
)
=>
s.
code
==
code
)
;
}
catch
(
_
)
{
return
null
;
}
}
}
void
main
(
)
{
var
status
=
HttpStatus.
notFound
;
(
'RUNOOB HTTP status: $status'
)
;
(
'Status code: ${status.code}'
)
;
(
'Message: ${status.message}'
)
;
(
'Is success: ${status.isSuccess}'
)
;
(
'Is client error: ${status.isClientError}'
)
;
// Use a static method to look up
var
found
=
HttpStatus.
fromCode
(
201
)
;
if
(
found
!=
null
)
{
(
'Found status: ${found.message}'
)
;
}
var
unknown
=
HttpStatus.
fromCode
(
999
)
;
(
'Unknown status code: $unknown'
)
;
}
RUNOOB HTTP 状态: HttpStatus.notFound
状态码: 404
消息: 资源未找到
是否成功: false
是否客户端错误: true
找到状态: 资源已创建
未知状态码: null
Enhanced enums upgrade enums from a set of named constants to a type with behavior, encapsulating logic related to the enum.
The constructor of an enhanced enum must be const and its member variables must be final, because enum values are themselves compile-time constants.
Symbol type
Symbol represents an identifier in a Dart program (variable name, function name, etc.).
It is rarely used in everyday development, mainly in reflection and code generation scenarios.
Example
void
main
(
)
{
// Create a Symbol using the # prefix
Symbol sym1
=
#runoob
;
Symbol sym2
=
#helloWorld
;
(
'Symbol 1: $sym1'
)
;
// Symbol("runoob")
(
'Symbol 2: $sym2'
)
;
// Symbol("helloWorld")
// Symbol comparison
Symbol sym3
=
#runoob
;
(
'sym1 == sym3: ${sym1 == sym3}'
)
;
// true
// Symbol can be used as a Map key
var
metadata
=
{
#author
:
'RUNOOB'
,
#version
:
'1.0.0'
,
#description
:
'Dart Tutorial'
,
}
;
(
'Author: ${metadata[#author]}'
)
;
}
Symbol 1: Symbol("runoob")
Symbol 2: Symbol("helloWorld")
sym1 == sym3: true
作者: RUNOOB
Symbols are usually minified after Dart compilation, so do not rely on the result of Symbol("runoob").toString() for logical decisions. The correct use of Symbol is reflection via the dart:mirrors library.
Rune and Unicode
Rune is the type in Dart that represents a Unicode code point.
In Dart, strings are UTF-16 encoded sequences.
For characters outside the Basic Multilingual Plane (BMP), such as emoji, you need to use Rune to handle them.
Example
void
main
(
)
{
// Get the Unicode code points of a string
String text
=
'RUNOOB'
;
(
'Character: $text'
)
;
(
'Code point list: ${text.runes.toList()}'
)
;
// Iterate over each character and its code point
for
(
var
char
in
text.
runes
)
{
(
'${String.fromCharCode(char)} -> U+${char.toRadixString(16).toUpperCase().padLeft(4, '
0
')}'
)
;
}
// Create a character from a code point
var
heart
=
String.
fromCharCode
(
0x2764
)
;
(
'Heart: $heart'
)
;
// Handle multi-code-point characters (such as some emoji)
var
smile
=
'\u{1F600}'
;
// Use \u{} syntax for characters beyond BMP
(
'Smiley: $smile'
)
;
// Get code points of multi-code-point characters
(
'Smiley code points: ${smile.runes.map((r) => '
U
$
{
r.
toRadixString
(
16
)
.
toUpperCase
(
)
}
').toList()}'
)
;
}
字符: RUNOOB
码点列表: [82, 85, 78, 79, 79, 66]
R -> U+0052
U -> U+0055
N -> U+004E
O -> U+004F
O -> U+004F
B -> U+0042
心形: ❤
笑脸: 😀
笑脸码点: [U+1F600]
In most everyday development you do not need to manipulate Rune directly; strings already handle Unicode well.
Rune is mainly used when precise manipulation of character code points is needed, such as low-level scenarios like text editors and font rendering.