Search code examples
dartboolean-expression

Using variable as Boolean in conditional statement in Dart


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?


Solution

  • 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) ...