dart条件表达式


Dart编程语言支持两种条件表达式,其中一种格式如下:

条件? 表达式1: 表达式2

如果条件判断为true,则执行表达式1,并返回结果;反之则执行表达式2,并返回结果。 另一种格式如下:

表达式1 ?? 表达式2

如果表达式1的值不是null,则返回表达式1的结果;如果表达式1的值是null,则返回表达式2的结果。

示例如下:

//条件表达式
var conditionBool = true;
print(conditionBool? 'true': 'false');
conditionBool = null;
print(conditionBool ?? 'This message will show when conditionBool is null')

//运行结果
true
This message will show when conditionBool is null

上述事例很好的诠释了两种条件表达式的用法和区别。在某些条件和返回值足够简单的情况下,建议使用条件表达式来替代if-else语句。