bool final#
The reserved words true and false denote objects that are the only two
instances of this class.
It is a compile-time error for a class to attempt to extend or implement bool.
Available Extensions
Constructors#
bool.fromEnvironment() factory const#
Boolean value for name in the compilation configuration environment.
The compilation configuration environment is provided by the
surrounding tools which are compiling or running the Dart program.
The environment is a mapping from a set of string keys to their associated
string value.
The string value, or lack of a value, associated with a name
must be consistent across all calls to String.fromEnvironment,
int.fromEnvironment,
bool.fromEnvironment and bool.hasEnvironment
in a single program.
The string values can be directly accessed using String.fromEnvironment.
This constructor parses the string value associated with name as
a boolean, as if by bool.tryParse,
meaning that it accepts only the strings "true" and "false".
If there is no value associated with name in the compilation
configuration environment, or if the associated string value is not one
of "true" or "false", the value of the constructor invocation
is the defaultValue boolean, which defaults to the boolean value
false.
The result is the same as that of:
(const String.fromEnvironment(name) == "true")
|| ((const String.fromEnvironment(name) != "false") && defaultValue)
Example:
const bool loggingEnabled = bool.fromEnvironment("logging");
In order to check whether a value is there at all, use bool.hasEnvironment. Example:
const bool? yesNoMaybe = bool.hasEnvironment("optionalFlag")
? bool.fromEnvironment("optionalFlag")
: null;
To accept other strings than "true" or "false", use the
String.fromEnvironment
constructor directly. Example:
const isLoggingOn = (const String.fromEnvironment("logging") == "on");
This constructor is only guaranteed to work when invoked as const.
It may work as a non-constant invocation on some platforms which
have access to compiler options at run-time, but most ahead-of-time
compiled platforms will not have this information.
Implementation
external const factory bool.fromEnvironment(
String name, {
bool defaultValue = false,
});
bool.hasEnvironment() factory const#
Whether name is declared in the compilation configuration environment.
The compilation configuration environment is provided by the
surrounding tools which are compiling or running the Dart program.
The environment is a mapping from a set of string keys to their associated
string value.
The string value, or lack of a value, associated with a name
must be consistent across all calls to String.fromEnvironment,
int.fromEnvironment,
bool.fromEnvironment and bool.hasEnvironment
in a single program.
This constructor evaluates to true if name has an associated value
in the compilation configuration environment, and to false if not.
If there is an associated value, then the value can be accessed using
const String.fromEnvironment(name). Otherwise,
String.fromEnvironment(name, defaultValue: someString)
is known to evaluate to the given defaultValue.
The String.fromEnvironment,
int.fromEnvironment
and
bool.fromEnvironment
constructors always produce a String,
int,
or bool, as required for a constructor.
In most cases, the absence of a configuration environment association
for a name simply means that the code should fall back on a default
behavior, and a default value of the same type typically represents that
perfectly.
In some cases, a value of different type, mostly null, may better
represent the absence of a choice. In that case, this constructor can
be used to first check whether there is a value, and only then use the
other fromEnvironment constructors.
Example:
const int? indentOverride = bool.hasEnvironment("indent-override")
? int.fromEnvironment("indent-override")
: null;
void indentLines(List<String> lines, int indentation) {
int actualIndentation = indentOverride ?? indentation;
// ... Do something to lines.
}
This pattern allows a compilation configuration to provide an override value to the program, but also to not do so, and the program can tell the difference between an explicitly provided value and the absence of one.
Another use case is to only do something extra when a needed value is available. Example:
const Logger? logger = bool.hasEnvironment("logging-id")
? Logger(id: String.fromEnvironment("logging-id"))
: null;
This constructor is only guaranteed to work when invoked as const.
It may work as a non-constant invocation on some platforms which
have access to compiler options at run-time, but most ahead-of-time
compiled platforms will not have this information.
Implementation
external const factory bool.hasEnvironment(String name);
Properties#
address extension no setter#
The memory address of the underlying data.
An expression of the form expression.address denoting this address can
only occurr as an entire argument expression in the invocation of a leaf
Native
external function.
Can only be used on fields of Struct subtypes, fields of Union subtypes, or Array elements. In other words, the boolean whose address is being accessed must itself be acccessed through a Struct, Union or Array.
Example:
@Native<Void Function(Pointer<Int8>)>(isLeaf: true)
external void myFunction(Pointer<Int8> pointer);
final class MyStruct extends Struct {
@Bool()
external bool x;
@Bool()
external bool y;
@Array(10)
external Array<Bool> array;
}
void main() {
final myStruct = Struct.create<MyStruct>();
myFunction(myStruct.y.address);
myFunction(myStruct.array[5].address);
}
The expression before .address is evaluated like the left-hand-side of
an assignment, to something that gives access to the storage behind the
expression, which can be used both for reading and writing. The .address
then gives a native pointer to that storage.
The .address is evaluated just before calling into native code when
invoking a leaf Native
external function. This ensures the Dart garbage
collector will not move the object that the address points in to.
Available on bool, provided by the BoolAddress extension
Implementation
external Pointer<Never> get address;
hashCode no setter override#
The hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Implementation
external int get hashCode;
runtimeType no setter inherited#
A representation of the runtime type of the object.
Inherited from Object.
Implementation
external Type get runtimeType;
toJS extension no setter#
Converts this bool to a JSBoolean.
Available on bool, provided by the BoolToJSBoolean extension
Implementation
external JSBoolean get toJS;
Methods#
noSuchMethod() inherited#
Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dynamic object = 1;
object.add(42); // Statically allowed, run-time error
This invalid code will invoke the noSuchMethod method
of the integer 1 with an Invocation
representing the
.add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}
This code has no compile-time warnings or errors even though
the MockList class has no concrete implementation of
any of the List interface methods.
Calls to List methods are forwarded to noSuchMethod,
so this code will log an invocation similar to
Invocation.method(#add, [42])
and then throw.
If a value is returned from noSuchMethod,
it becomes the result of the original invocation.
If the value is not of a type that can be returned by the original
invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
toString() override#
Returns either "true" for true and "false" for false.
Implementation
String toString() {
return this ? "true" : "false";
}
Operators#
operator &()#
The logical conjunction ("and") of this and other.
Returns true if both this and other are true, and false
otherwise.
Implementation
bool operator &(bool other) => other && this;
operator ==() inherited#
The equality operator.
The default behavior for all Objects is to return true if and
only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.-
Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false. -
Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
external bool operator ==(Object other);
operator ^()#
The logical exclusive disjunction ("exclusive or") of this and other.
Returns whether this and other are neither both true nor both false.
Implementation
bool operator ^(bool other) => !other == this;
operator |()#
The logical disjunction ("inclusive or") of this and other.
Returns true if either this or other is true, and false
otherwise.
Implementation
bool operator |(bool other) => other || this;
Static Methods#
parse()#
Parses source as an, optionally case-insensitive, boolean literal.
If caseSensitive is true, which is the default,
the only accepted inputs are the strings "true" and "false",
which returns the results true and false respectively.
If caseSensitive is false, any combination of upper and lower case
ASCII letters in the words "true" and "false" are accepted,
as if the input was first lower-cased.
Throws a FormatException
if the source string does not contain
a valid boolean literal.
Rather than throwing and immediately catching the FormatException, instead use tryParse to handle a potential parsing error.
Example:
print(bool.parse('true')); // true
print(bool.parse('false')); // false
print(bool.parse('TRUE')); // throws FormatException
print(bool.parse('TRUE', caseSensitive: false)); // true
print(bool.parse('FALSE', caseSensitive: false)); // false
print(bool.parse('NO')); // throws FormatException
print(bool.parse('YES')); // throws FormatException
print(bool.parse('0')); // throws FormatException
print(bool.parse('1')); // throws FormatException
Implementation
@Since("3.0")
external static bool parse(String source, {bool caseSensitive = true});
tryParse()#
Parses source as an, optionally case-insensitive, boolean literal.
If caseSensitive is true, which is the default,
the only accepted inputs are the strings "true" and "false",
which returns the results true and false respectively.
If caseSensitive is false, any combination of upper and lower case
ASCII letters in the words "true" and "false" are accepted,
as if the input was first lower-cased.
Returns null if the source string does not contain a valid
boolean literal.
If the input can be assumed to be valid, use bool.parse
to avoid
having to deal with a possible null result.
Example:
print(bool.tryParse('true')); // true
print(bool.tryParse('false')); // false
print(bool.tryParse('TRUE')); // null
print(bool.tryParse('TRUE', caseSensitive: false)); // true
print(bool.tryParse('FALSE', caseSensitive: false)); // false
print(bool.tryParse('NO')); // null
print(bool.tryParse('YES')); // null
print(bool.tryParse('0')); // null
print(bool.tryParse('1')); // null
Implementation
@Since("3.0")
external static bool? tryParse(String source, {bool caseSensitive = true});