Home > Software engineering >  Using variable as Boolean in conditional statement in Dart
Using variable as Boolean in conditional statement in Dart

Time:09-07

I'm learning Dart after coming from Python and I wanted to know what is the closest Dart has to using a non-Boolean variable as a Boolean in conditional statements. Like using a string where an empty string is false and a non-empty string is true.

For example, in Python:

name = 'Yes'

print('True' if name else 'False') // 'True'

name2 = ''

print('True' if name else 'False') // 'False'

Does Dart have something similar without having to convert the variable to a Boolean statement?

CodePudding user response:

I don't think such code will even compile. Type checking in dart tends to be very strict, and whenever the compile tries to evaluate a condition which is not of type bool it raises an error. For example, the following won't compile:

final String value = "truthyValue" ? "truth" : "dare";

Instead, dart offers the isNonEmpty and isEmpty methods on many built in types such as strings, different containers so on, so you could do something like someString.isNotEmpty ? "good" : "bad";.

CodePudding user response:

Dart has no affordance for using non-boolean values in tests. None, whatsoever. Can't be done.

The only expressions allowed in a test positions are those with static type:

  • bool
  • dynamic (which is implicitly downcast to bool as if followed by as bool, which throws at runtime if it's not actually a bool.)
  • Never, which always throws before producing a value.

The bool type, in non-null-safe code can evaluate to null. The test also throws at runtime if that happens.

So, for any test, if the test expression does not evaluate to a bool, it throws. You can only branch on an actual bool true or false.

If you have a value where you want to treat both null and empty as false, I'd do: if (value?.isEmpty ?? false) ...

  • Related