Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StringId - a dynamic key lookup #6

Open
vishna opened this issue Jan 29, 2020 · 1 comment
Open

StringId - a dynamic key lookup #6

vishna opened this issue Jan 29, 2020 · 1 comment

Comments

@vishna
Copy link
Owner

vishna commented Jan 29, 2020

In some cases you might want to be able to use strings in more dynamic manner, e.g. backend driven a/b test.

Since dart on flutter offers no reflection we could generate extension method that could achieve that.

class StringKeys {
  StringKeys._();
  static const carrot = "carrot";
  static const apple = "apple";
}

extension StringKeysExtension on S {
  dynamic operator [](String key) {
    switch(key) {
      case StringKeys.carrot: return carrot;
      case StringKeys.apple: return apple;
      default: return null;
    }
  }
}

You could then use it in your code:

final apple1 = strings.apple;
final apple2 = strings["apple"];
final apple3 = strings[StringKeys.apple];

Beware the returned apple might not be a string value but a function in which case you need to know what arguments you want to use.

@vishna
Copy link
Owner Author

vishna commented Jan 29, 2020

...or a bit more rigid version

class StringId {
  const StringId(this.value);
  final String value;
  static const onboarding_sell_photos = StringId("onboarding_sell_photos");
  static const mission_winners = StringId("mission_winners");
}

extension StringKeysExtension on S {
  dynamic operator [](StringId id) {
    switch(id.value) {
      case "onboarding_sell_photos": return onboarding_sell_photos;
      case "mission_winners": return mission_winners;
      default: return null;
    }
  }
}

@vishna vishna changed the title dynamic key lookup StringId - a dynamic key lookup Jan 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant