kzrfaisal
kzrfaisal

Reputation: 1443

How can I restrict a string variable values to only some predefined values in dart?

I can do it in typescript like this:

let greet: 'Hey' | 'Hi' | 'Hello';
// Now greet will allow only above specified string values

greet = 'Hi'; // no Type Error here
greet = 'Welcome'; // throws a Type Error

How do I implement the equivalent in Dart?

Upvotes: 4

Views: 801

Answers (1)

Christopher Moore
Christopher Moore

Reputation: 17141

You can use an enumerated type and convert it to a String if necessary.

Declaring the enum:

enum Greet {
  Hey,
  Hi,
  Hello,
}

Providing a method of converting to string with an extension method:

extension ParseToString on Greet {
  String toShortString() {
    return this.toString().split('.').last;
  }
}

Example usage:

void main() {
  Greet greet = Greet.Hey;
  print(greet.toShortString());//Hey
}

enum Greet {
  Hey,
  Hi,
  Hello,
}

extension ParseToString on Greet {
  String toShortString() {
    return this.toString().split('.').last;
  }
}

If you just needed a type that had a few distinct values, you can ignore the String extension part.

Upvotes: 4

Related Questions