【问题标题】:Using variable as Boolean in conditional statement in Dart在 Dart 的条件语句中使用变量作为布尔值
【发布时间】:2022-10-08 05:00:37
【问题描述】:

我从 Python 开始学习 Dart,我想知道 Dart 最接近在条件语句中使用非布尔变量作为布尔值是什么。就像使用空字符串为false 而非空字符串为true 的字符串一样。

例如,在 Python 中:

name = 'Yes'

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

name2 = ''

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

Dart 是否有类似的东西而不必将变量转换为布尔语句?

【问题讨论】:

    标签: dart boolean-expression


    【解决方案1】:

    飞镖有在测试中使用非布尔值的启示。没有任何。做不到。

    测试位置中允许的唯一表达式是静态类型的表达式:

    • bool
    • dynamic(隐式向下转换为bool,好像后面跟着as bool,如果它实际上不是bool,则在运行时抛出。)
    • Never,总是在产生值之前抛出。

    bool 类型,在非空安全代码中可以评估为 null。如果发生这种情况,测试也会在运行时抛出。

    因此,对于任何测试,如果测试表达式的计算结果不是bool,它就会抛出。您只能在实际的 bool truefalse 上进行分支。

    如果您有一个值,您希望将 null 和空都视为 false,我会这样做:if (value?.isEmpty ?? false) ...

    【讨论】:

      【解决方案2】:

      我认为这样的代码甚至不会编译。 dart 中的类型检查往往非常严格,每当编译尝试评估非 bool 类型的条件时,它都会引发错误。 例如,以下内容不会编译:

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

      相反,dart 在许多内置类型(如字符串、不同容器等)上提供了isNonEmptyisEmpty 方法,因此您可以执行someString.isNotEmpty ? "good" : "bad"; 之类的操作。

      【讨论】:

        【解决方案3】:

        如果您需要处理特定值,例如“0”或“00000”,您可以在任何类型上编写扩展名。我非常喜欢它,因为它对任何解析都很方便,而且如果你把它命名好,它是可读的。

        extension BoolTest on String? {
          bool get toBool {
            if (this == null) {
              return false;
            } else {
              return true;
            }
          }
        }
        

        那么你只需像这样使用它:

        String? a = 'hello';
        String? b;
        print(a.toBool);      // true
        print(b.toBool);      // false
        print('hello'.toBool) // true
        

        看看:https://dart.dev/guides/language/extension-methods

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-30
          • 1970-01-01
          • 1970-01-01
          • 2018-06-16
          • 2020-08-20
          • 1970-01-01
          相关资源
          最近更新 更多