Enums in Dart
Our example demonstrates how to implement enumerated types (enums) with the target language and its existing idioms. Here’s the full source code and explanation.
// Define the ServerState enum
enum ServerState {
idle,
connected,
error,
retrying
}
// Create a mapping for the state names
const stateName = {
ServerState.idle: "idle",
ServerState.connected: "connected",
ServerState.error: "error",
ServerState.retrying: "retrying"
};
// Implement the transition function to emulate state transitions
ServerState transition(ServerState s) {
switch (s) {
case ServerState.idle:
return ServerState.connected;
case ServerState.connected:
case ServerState.retrying:
return ServerState.idle;
case ServerState.error:
return ServerState.error;
default:
throw Exception("unknown state: ${s}");
}
}
void main() {
var ns = transition(ServerState.idle);
print(stateName[ns]); // prints "connected"
var ns2 = transition(ns);
print(stateName[ns2]); // prints "idle"
}Our enum type ServerState has four possible values: idle, connected, error, and retrying.
enum ServerState {
idle,
connected,
error,
retrying
}The possible values for ServerState are defined using enum, which provides a way to define a collection of named constants.
By implementing a mapping using a constant Map, values of ServerState can be printed out or converted to strings.
const stateName = {
ServerState.idle: "idle",
ServerState.connected: "connected",
ServerState.error: "error",
ServerState.retrying: "retrying"
};The transition function emulates a state transition for a server; it takes the existing state and returns a new state.
ServerState transition(ServerState s) {
switch (s) {
case ServerState.idle:
return ServerState.connected;
case ServerState.connected:
case ServerState.retrying:
return ServerState.idle;
case ServerState.error:
return ServerState.error;
default:
throw Exception("unknown state: ${s}");
}
}In main, we have an example of how to use the transition function and print the state names.
void main() {
var ns = transition(ServerState.idle);
print(stateName[ns]); // prints "connected"
var ns2 = transition(ns);
print(stateName[ns2]); // prints "idle"
}In this example, the transition function takes a ServerState value and returns the next state. This provides some degree of compile-time type safety for enums, ensuring that only valid states are used.