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 when one or more of the cases are missing, so they ensure that all the possible values are handled.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175