check-if-an-object-is-truthy-in-dart
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCheck if an Object is Truthy in Dart
在Dart中检查对象是否为Truthy值
If you are coming from language like JavaScript you may be used to checking if an object is truthy.
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)In Dart you need to explicitly check if an object is not null, true/false or determine if the value is true based on the type.
It is possible however to use Dart extensions to add the truthy capability.
extension on Object? {
bool get isTruthy => truthy(this);
}
bool truthy(Object? val) {
if (val == null) return false;
if (val is bool) return val;
if (val is num && val == 0) return false;
if (val is String && (val == 'false' || val == '')) return false;
if (val is Iterable && val.isEmpty) return false;
if (val is Map && val.isEmpty) return false;
return true;
}This will now make it possible for any object to be evaluated as a truthy value in if statements or value assignments.
Prints the following:
(null, false)
(, false)
(false, false)
(true, true)
(0, false)
(1, true)
(false, false)
(true, true)
([], false)
([1, 2, 3], true)
({}, false)
({1, 2, 3}, true)
({a: 1, b: 2}, true)如果你来自JavaScript这类语言,可能习惯了检查对象是否为truthy。
if (true)
if ({})
if ([])
if (42)
if ("0")
if ("false")
if (new Date())
if (-42)
if (12n)
if (3.14)
if (-3.14)
if (Infinity)
if (-Infinity)在Dart中,你需要显式检查对象是否不为null、是true/false,或者根据类型判断值是否为真。
不过,我们可以使用Dart扩展来添加truthy判断功能。
extension on Object? {
bool get isTruthy => truthy(this);
}
bool truthy(Object? val) {
if (val == null) return false;
if (val is bool) return val;
if (val is num && val == 0) return false;
if (val is String && (val == 'false' || val == '')) return false;
if (val is Iterable && val.isEmpty) return false;
if (val is Map && val.isEmpty) return false;
return true;
}现在,任何对象都可以在if语句或值赋值中被评估为truthy值。
输出如下:
(null, false)
(, false)
(false, false)
(true, true)
(0, false)
(1, true)
(false, false)
(true, true)
([], false)
([1, 2, 3], true)
({}, false)
({1, 2, 3}, true)
({a: 1, b: 2}, true)