Skip to content

Offering my switchCase Extension #80

Open
@Skquark

Description

I just adapted a little utility I've been using to work as extension, and I think it'd fit in well with your library. It does the equivalent of switch(string) { case "txt1": etc, only cleaner and easier inside a widget structure, or wherever you'd use a standard switch case break default statement.. Here it is:

extension switchString on String {
  /// Performs a switch-case statement on String using a map for cases & conditions, optional default value 
  /// ```dart
  /// child: roomType.switchCase({
  ///   "public": Text("It's public"),
  ///   "private": Text("It's private"),
  ///   "custom": () { ... },
  /// }, Text("Default type")),
  /// ```
  TValue switchCase<String, TValue>(Map<String, TValue> cases, [TValue defaultValue]) {
    if (cases.containsKey(this)) return cases[this];
    return defaultValue;
  }
}

extension switchInt on int {
  /// Performs a switch-case statement on int using a map for cases & conditions, optional default value 
  /// ```dart
  /// child: typeNumber.switchCase({
  ///   1: Text("It's one"),
  ///   2: () { ... },
  ///   3: Text("It's three"),
  /// }, Text("Other number")),
  /// ```
  TValue switchCase<int, TValue>(Map<int, TValue> cases, [TValue defaultValue]) {
    if (cases.containsKey(this)) return cases[this];
    return defaultValue;
  }
}

Simple and fairly elegant code with the optional default: parameter, I could give you the original generic TOptionType version as well (I didn't write it), but it's nicer as extension on String and int and maybe another type too. Feel free to add it in, or if you prefer, I can add it in myself with a PR with doc updates. I'm just loving the flexibility of Dart now, so many new toys to play with...

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions