Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Enums and Symbols

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

;

  print

(

'Current status: $currentStatus'

)

;

 

// Get the index via .index (starting from 0)

  print

(

'Index value: ${currentStatus.index}'

)

;

 

// 0

 

// Get all enum values via .values

  print

(

'All statuses: ${Status.values}'

)

;

 

// Iterate over all enum values

 

for

(

var

status

in

Status.

values

)

{

    print

(

'RUNOOB status: $status, index: ${status.index}'

)

;

 

}

 

// Get an enum value from a string

  Status parsed

=

Status.

values

.

byName

(

'approved'

)

;

  print

(

'Parsed status: $parsed'

)

;

 

// Use enums in switch

 

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

;

 

}

}



当前状态: 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

;

  print

(

'RUNOOB HTTP status: $status'

)

;

  print

(

'Status code: ${status.code}'

)

;

  print

(

'Message: ${status.message}'

)

;

  print

(

'Is success: ${status.isSuccess}'

)

;

  print

(

'Is client error: ${status.isClientError}'

)

;

 

// Use a static method to look up

 

var

found

=

HttpStatus.

fromCode

(

201

)

;

 

if

(

found

!=

null

)

{

    print

(

'Found status: ${found.message}'

)

;

 

}

 

var

unknown

=

HttpStatus.

fromCode

(

999

)

;

  print

(

'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

;

  print

(

'Symbol 1: $sym1'

)

;

 

// Symbol("runoob")

  print

(

'Symbol 2: $sym2'

)

;

 

// Symbol("helloWorld")

 

// Symbol comparison

  Symbol sym3

=

#runoob

;

  print

(

'sym1 == sym3: ${sym1 == sym3}'

)

;

 

// true

 

// Symbol can be used as a Map key

 

var

metadata

=

{

    #author

:

'RUNOOB'

,

    #version

:

'1.0.0'

,

    #description

:

'Dart Tutorial'

,

 

}

;

  print

(

'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'

;

  print

(

'Character: $text'

)

;

  print

(

'Code point list: ${text.runes.toList()}'

)

;

 

// Iterate over each character and its code point

 

for

(

var

char

in

text.

runes

)

{

    print

(

'${String.fromCharCode(char)} -> U+${char.toRadixString(16).toUpperCase().padLeft(4, '

0

')}'

)

;

 

}

 

// Create a character from a code point

 

var

heart

=

String.

fromCharCode

(

0x2764

)

;

  print

(

'Heart: $heart'

)

;

 

// Handle multi-code-point characters (such as some emoji)

 

var

smile

=

'\u{1F600}'

;

 

// Use \u{} syntax for characters beyond BMP

  print

(

'Smiley: $smile'

)

;

 

// Get code points of multi-code-point characters

  print

(

'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.