Book Image

Learning Dart, Second Edition - Second Edition

By : Ivo Balbaert
Book Image

Learning Dart, Second Edition - Second Edition

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Learning Dart Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Using enums


Often, you encounter a situation where a variable can only take on a limited number of "named values," like the days in a week or the four compass directions. This concept is known as an enum and it was introduced in Dart in version 1.8. Here, is an example (see enums.dart):

enum Direction {North, South, East, West}

main() {
  Direction dir = Direction.South;
  if (dir == Direction.South) {
    print("Let's go on a trip");
  }
  switch (dir) {
    case Direction.North:
      print("Too cold up there!");
      break;
    case Direction.South:
          print("Let's go on a trip!");
          break;
    case Direction.West:
          print("Better stay home!");
          break;
    case Direction.East:
          print("Which eastern country do you want to visit?");
          break;
  }
}

This prints out:

Let's go on a trip
Let's go on a trip!

The nice thing about enums is that they not only clarify but shorten your code. When used in a switch statement, the Dart tools can warn you...