一个简单的工具(真的很简单,大约25行代码)可以将Dart对象(包括null)转换为bool(true|false),这与Javascript和Typescript中的双重非运算符(!!)的工作方式非常相似。
特点
您可以使用它作为运算符(~或两次~~),作为扩展(属性.asBool)或作为简单的帮助方法(asBool(value))。
警告 运算符
~不能与int值一起使用,因为它用于按位取反运算符,对于int对象,请使用扩展或帮助方法。
哪些值会被转换为false
空0和0.0double.nan“非数字”值""空字符串[]空的可迭代对象<any>.isEmpty == true任何具有isEmpty属性并返回true的对象(即,Map或实现isEmpty的任何自定义类)。
所有其他值都被视为true。
入门
将asbool包添加到您的项目中
dart pub add asbool
导入包
import 'package:asbool/asbool.dart'; // All included
用法
根据您的需要使用该工具
final foo = 'Hi';
final bar = [];
final m = {'a':'b'};
assert(~~foo == foo.asBool); // true == true
assert(asBool(foo) == ~~12); // true == true
assert(asBool(bar) == bar.asBool); // false == false
assert(asBool(0.0) == ~~double.nan); // false == false
assert(~~m == true); // true == true
assert(asBool({}) == false); // false == false
final things = [123, 'Hi', null, {}, {'a': 'b'}, double.nan, double.infinity, MyClass(), MyOtherClass(), 0, 0.0, ['ok']];
final trueThings = things.where(asBool).toList();
print(trueThings); // It will print: [123, 'Hi', {'a': 'b'}, double.infinity, MyClass(), ['ok']]
附加信息
如果您对该库有任何建议或问题,请打开一个Issue,我会尽力帮助您。