Dart

10. Dart Runes and enumeration

Runes and Enumeration

In Dart, runes and enumerations are both useful constructs, albeit quite different. Let’s explore each of them with examples:

  1. Runes
What are Runes?

Runes represent Unicode scalar values in Dart, which allow you to work with individual characters beyond the basic ASCII range.

Example:

Here’s how you can use runes in Dart:

void main() {
  // Define a rune for the heart symbol ❤ (Unicode: U+2764)
  var heartRune = '\u2764';

  // Output the rune and its code point
  print('Heart Rune: $heartRune');
  print('Heart Rune Code Unit: ${heartRune.runes.single}');
  
  // Accessing individual code units (runes) in a string
  var coffee = '☕';
  print('Coffee Rune: $coffee');
  print('Coffee Rune Code Units: ${coffee.runes.toList()}');
}
void main() {
  final c1 = '\u{1F9F6}';
  final c2 = '\u{1FA86}';
  final c3 = '\u26C4';
  final c4 = '\u{1F37A}';

  print(c1);
  print(c2);
  print(c3);
  print(c4);

  print(c3.codeUnits);
  print(c4.codeUnits);
}
    2. Enumerations (Enums)
What are Enums?

Enums (short for enumerations) in Dart are a way to define a collection of constants, often used to represent a fixed number of possible states or choices.

Example:

Here’s how you can define and use enums in Dart:

// Define an enum for different days of the week
enum Day {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}

void main() {
  // Using enums to declare variables
  Day today = Day.Wednesday;

  // Switch statement using enums
  switch (today) {
    case Day.Monday:
      print('It\'s Monday!');
      break;
    case Day.Wednesday:
      print('It\'s Wednesday!');
      break;
    case Day.Friday:
      print('It\'s Friday!');
      break;
    default:
      print('It\'s neither Monday, Wednesday, nor Friday.');
  }
}

 Enums are for defining a fixed set of related constants, whereas lists are for managing ordered collections of items.

Leave a Reply

Your email address will not be published. Required fields are marked *