asbool 1.0.3 copy "asbool: ^1.0.3" to clipboard
asbool: ^1.0.3 copied to clipboard

Simple tool to convert whatever thing (dynamic) to a bool value.

Pub Version codecov

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 twice 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 with int values because is used for bit-wise negate operator, for int objects use the extension or helper method

What values are converted to false:

  • null
  • 0 And 0.0
  • double.nan "Not a Number" values
  • "" Empty Strings
  • [] Empty iterable objects
  • <any>.isEmpty == true Whatever object with a isEmpty property that returns true (i.e, a Map or any custom class that implement isEmpty)

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.

3
likes
0
pub points
72%
popularity

Publisher

unverified uploader

Simple tool to convert whatever thing (dynamic) to a bool value.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

More

Packages that depend on asbool