Skip to content

Instantly share code, notes, and snippets.

@cconstab
Last active September 15, 2022 00:02
Show Gist options
  • Save cconstab/ada622a5e4fd953f4d86af4c49145c63 to your computer and use it in GitHub Desktop.
Save cconstab/ada622a5e4fd953f4d86af4c49145c63 to your computer and use it in GitHub Desktop.
Dart Lang : Extend String to be able to parse "true" | "false" to boolean
void main() {
String trueString = "true";
String falseString = "false";
if (!falseString.parseBool()) { print("falseString is:false");}
if (trueString.parseBool()) { print("trueString is: true");}
}
extension BoolParsing on String {
bool parseBool() {
if (toLowerCase().trimLeft().trimRight() == 'true') {
return true;
} else if (toLowerCase().trimLeft().trimRight() == 'false') {
return false;
}
throw '"$this" can not be parsed to boolean.';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment