A simple tool (really simple, about 25 lines of code) to convert a dart object, including null
, in a bool
(true|false
), quite similar to how the double NOT operator (!!
) works in Javascript and Typescript.
Features
You can use it as an operator (~
or twice ~~
), as an extension (property .asBool
) or as a simple helper method (asBool(value)
).
Warning The operator
~
doesn't work withint
values because is used for bit-wise negate operator, forint
objects use the extension or helper method
What values are converted to false
:
null
0
And0.0
double.nan
"Not a Number" values""
Empty Strings[]
Empty iterable objects<any>.isEmpty == true
Whatever object with aisEmpty
property that returnstrue
(i.e, aMap
or any custom class that implementisEmpty
)
All other values are considered as true
.
Getting started
Add the package asbool
to your project:
dart pub add asbool
Import the package, but if you prefer don't add the extension or the operator you can use different imports:
import 'package:asbool/asbool.dart'; // All included
All options are included: helper method, extension and operator.
import 'package:asbool/asbool_extension.dart'; // Only helper method and extension
Only 2 options are included: helper method and extension.
import 'package:asbool/asbool_helper.dart'; // Only helper method
Only helper method is imported.
Usage
Use the tool as you wish
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
Additional information
If you have any suggestion or problem with the lib, please open an issue and I'll try to help.
Libraries
- asbool
- A simple tool to convert a dart object, including
null
, in abool
(true|false
), quite similar to how works the double NOT operator!!
in Javascript and Typescript. - asbool_extension
- A simple tool to convert a dart object, including
null
, in abool
(true|false
), quite similar to how works the double NOT operator!!
in Javascript and Typescript. - asbool_helper
- A simple tool to convert a dart object, including
null
, in abool
(true|false
), quite similar to how works the double NOT operator!!
in Javascript and Typescript.