asbool 1.0.5
asbool: ^1.0.5 copied to clipboard
Simple tool to convert whatever thing (dynamic) to a bool value.
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 withintvalues because is used for bit-wise negate operator, forintobjects use the extension or helper method
What values are converted to false:
null0And0.0double.nan"Not a Number" values""Empty Strings[]Empty iterable objects<any>.isEmpty == trueWhatever object with aisEmptyproperty that returnstrue(i.e, aMapor 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.