RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Core libraries

Core types

Strings, numbers, BigInt, booleans, lists, maps, sets, iterables, dates and durations, URIs, regular expressions, errors and exceptions. Imported automatically.

import 'raya:core';

Imported automatically.

60 classes622 functions and methods673 of 755 documented503 runnable examples

Overview

Built-in types, collections, and other core functionality for every Raya program.

This library is automatically imported.

Some classes in this library, such as String and num, support Raya's built-in data types. Other classes, such as List and Map, provide data structures for managing collections of objects. And still other classes represent commonly used types of data such as URIs, dates and times, and errors.

Numbers and booleans

int and double provide support for Raya's built-in numerical data types: integers and double-precision floating point numbers, respectively. An object of type bool is either true or false. Variables of these types can be constructed from literals:

int meaningOfLife = 42;
double valueOfPi  = 3.141592;
bool visible      = true;

Strings and regular expressions

A String is immutable and represents a sequence of characters.

String shakespeareQuote = "All the world's a stage, ...";

StringBuffer provides a way to construct strings efficiently.

var moreShakespeare = StringBuffer();
moreShakespeare.write('And all the men and women ');
moreShakespeare.write('merely players; ...');

The String and StringBuffer classes implement string splitting, concatenation, and other string manipulation features.

bool isPalindrome(String text) => text == text.split('').reversed.join();

RegExp implements Raya regular expressions, which provide a grammar for matching patterns within text. For example, here's a regular expression that matches a substring containing one or more digits:

var numbers = RegExp(r'\d+');

Raya regular expressions have the same syntax and semantics as JavaScript regular expressions. See <http://ecma-international.org/ecma-262/5.1/#sec-15.10> for the specification of JavaScript regular expressions.

Collections

The raya:core library provides basic collections, such as List, Map, and Set.

A List is an ordered collection of objects, with a length. Lists are sometimes called arrays. Use a List when you need to access objects by index.

var superheroes = ['Batman', 'Superman', 'Harry Potter'];

A Set is an unordered collection of unique objects. You cannot get an item efficiently by index (position). Adding an element which is already in the set, has no effect.

var villains = {'Joker'};
print(villains.length); // 1
villains.addAll(['Joker', 'Lex Luthor', 'Voldemort']);
print(villains.length); // 3

A Map is an unordered collection of key-value pairs, where each key can only occur once. Maps are sometimes called associative arrays because maps associate a key to some value for easy retrieval. Use a Map when you need to access objects by a unique identifier.

var sidekicks = {'Batman': 'Robin',
                 'Superman': 'Lois Lane',
                 'Harry Potter': 'Ron and Hermione'};

In addition to these classes, raya:core contains Iterable, an interface that defines functionality common in collections of objects. Examples include the ability to run a function on each element in the collection, to apply a test to each element, to retrieve an object, and to determine the number of elements.

Iterable is implemented by List and Set, and used by Map for its keys and values.

For other kinds of collections, check out the raya:collection library.

Date and time

Use DateTime to represent a point in time and Duration to represent a span of time.

You can create DateTime objects with constructors or by parsing a correctly formatted string.

var now = DateTime.now();
var berlinWallFell = DateTime(1989, 11, 9);
var moonLanding = DateTime.parse("1969-07-20");

Create a Duration object by specifying the individual time units.

var timeRemaining = const Duration(hours: 56, minutes: 14);

In addition to DateTime and Duration, raya:core contains the Stopwatch class for measuring elapsed time.

Uri

A Uri object represents a uniform resource identifier, which identifies a resource, for example on the web.

var rayalang = Uri.parse('http://example.com/');

Errors

The Error class represents the occurrence of an error during runtime. Subclasses of this class represent specific kinds of errors.

Also exported here

Functions and constants

Functions

identicalfunction
external bool identical(Object? a, Object? b)

Check whether two object references are to the same object.

Raya values, what is stored in variables, are object references. There can be multiple references to the same object.

A Raya object has an identity, which separates it from other objects, even ones with otherwise identical state. The identical function exposes whether two object references refer to the same object.

If an identical call returns true, it is guaranteed that there is no way to distinguish the two arguments. If it returns false, the arguments are only known to not be the same object.

A non-constant invocation of a generative (non-factory) constructor, or evaluating a non-constant list, set or map literal, always creates a new object, which is not identical to any existing object.

Constant canonicalization ensures that the result of two compile-time constant expressions which create objects with the same state, also evaluate to references to the same, canonical, instance. Example:

print(identical(const <int>[1], const <int>[1])); // true

Integers and doubles are special, they do not allow creating new instances at all. If two integers are equal, they are also always identical. If two doubles have the same binary representation, they are identical (with caveats around double.nan and -0.0 on web platforms).

Record values do not have a persistent identity. This allows compilers to split a record into its parts and rebuild it later, without having to worry about creating an object with the same identity. A record may be identical to another record with the same shape, if all the corresponding fields are identical, or it may not, but it is never identical to anything else.

Example:

var o = new Object();
var isIdentical = identical(o, new Object()); // false, different objects.
isIdentical = identical(o, o); // true, same object.
isIdentical = identical(const Object(), const Object()); // true, const canonicalizes.
isIdentical = identical([1], [1]); // false, different new objects.
isIdentical = identical(const [1], const [1]); // true.
isIdentical = identical(const [1], const [2]); // false.
isIdentical = identical(2, 1 + 1); // true, integers canonicalize.

var pair = (1, "a"); // Create a record.
isIdentical = identical(pair, pair); // true or false, can be either.

var pair2 = (1, "a"); // Create another(?) record.
isIdentical = identical(pair, pair2); // true or false, can be either.

isIdentical = identical(pair, (2, "a")); // false, not identical values.
isIdentical = identical(pair, (1, "a", more: true)); // false, wrong shape.
Example
void main() {
  final a = [1, 2], b = [1, 2];
  print('a == b:          ${a == b}');
  print('identical(a, b): ${identical(a, b)}');
  print('identical(a, a): ${identical(a, a)}');
  const c = [1, 2], d = [1, 2];
  print('const lists identical: ${identical(c, d)}');
}
Output
a == b:          false
identical(a, b): false
identical(a, a): true
const lists identical: true
external int identityHashCode(Object? object)

The identity hash code of object.

Returns the value that the original Object.hashCode would return on this object, even if hashCode has been overridden.

This hash code is compatible with identical, which means that it's guaranteed to give the same result every time it's passed the same argument, throughout a single program execution, for any non-record object.

The identity hash code of a Record is undefined, because a record doesn't have a guranteed persistent identity. A record values identity and identity hash code can change at any time.

var identitySet = HashSet(equals: identical, hashCode: identityHashCode);
var dt1 = DateTime.now();
var dt2 = DateTime.fromMicrosecondsSinceEpoch(dt1.microsecondsSinceEpoch);
assert(dt1 == dt2);
identitySet.add(dt1);
print(identitySet.contains(dt1)); // true
print(identitySet.contains(dt2)); // false
Example
class Point {
  final int x, y;
  const Point(this.x, this.y);
  @override
  bool operator ==(Object o) => o is Point && o.x == x && o.y == y;
  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final a = Point(1, 2), b = Point(1, 2);
  print('a == b:                ${a == b}');
  print('equal hashCode:        ${a.hashCode == b.hashCode}');
  print('same identity hash:    ${identityHashCode(a) == identityHashCode(a)}');
  print('a, b identity differs: ${identical(a, b) ? 'no' : 'yes (distinct objects)'}');
}
Output
a == b:                true
equal hashCode:        true
same identity hash:    true
a, b identity differs: yes (distinct objects)
printfunction
void print(Object? object)

Prints an object to the console.

On the web, object is converted to a string and that string is output to the web console using console.log.

On native (non-Web) platforms, object is converted to a string and that string is terminated by a line feed ('\n', U+000A) and written to stdout. On Windows, the terminating line feed, and any line feeds in the string representation of object, are output using the Windows line terminator sequence of ('\r\n', U+000D + U+000A).

Calls to print can be intercepted by Zone.print.

Example
void main() {
  print('a string');
  print(42);
  print([1, 2, 3]);
  print({'k': 'v'});
  print(null);
}
Output
a string
42
[1, 2, 3]
{k: v}
null

Constants and variables

deprecatedconstant
const Deprecated deprecated = Deprecated("next release")

Marks a feature as Deprecated until the next release.

overrideconstant
const Object override = _Override()

Annotation on instance members which override an interface member.

Annotations have no effect on the meaning of a Raya program. This annotation is recognized by the Raya analyzer, and it allows the analyzer to provide hints or warnings for some potential problems of an otherwise valid program. As such, the meaning of this annotation is defined by the Raya analyzer.

The @override annotation expresses the intent that a declaration should override an interface method, something which is not visible from the declaration itself. This extra information allows the analyzer to provide a warning when that intent is not satisfied, where a member is intended to override a superclass member or implement an interface member, but fails to do so. Such a situation can arise if a member name is mistyped, or if the superclass renames the member.

The @override annotation applies to instance methods, instance getters, instance setters and instance variables (fields). When applied to an instance variable, it means that the variable's implicit getter and setter (if any) are marked as overriding. It has no effect on the variable itself.

Typedefs

Comparatortypedef
typedef Comparator<T> = int Function(T a, T b)

The signature of a generic comparison function.

A comparison function represents an ordering on a type of objects. A total ordering on a type means that for two values, either they are equal or one is greater than the other (and the latter must then be smaller than the former).

A Comparator function represents such a total ordering by returning

  • A negative integer if a is smaller than b,
  • Zero if a is equal to b, and
  • A positive integer if a is greater than b.

Classes

class Deprecated

The annotation @Deprecated('migration') marks a feature as deprecated.

The annotation deprecated is a shorthand for deprecating until an unspecified "next release" without migration instructions.

A feature can be any part of an API, from a full library to a single parameter.

The intent of the @Deprecated annotation is to inform authors who are currently using the feature, that they will soon need to stop using that feature in their code, even if the feature is currently still working correctly.

Deprecation is an early warning that the deprecated feature is scheduled to be removed at a later time, a time possibly specified in message. A deprecated feature should no longer be used, code using it will break at some point in the future. If existing code is using the feature, that code should be rewritten to no longer use the deprecated feature.

A deprecated feature should document how the same effect can be achieved in message, so the programmer knows how to rewrite the code.

The @Deprecated annotation applies to libraries, top-level declarations (variables, getters, setters, functions, classes, mixins, extension and typedefs), class-level declarations (variables, getters, setters, methods, operators or constructors, whether static or not), named optional parameters and trailing optional positional parameters.

Deprecation applies transitively to parts of a deprecated feature:

  • If a library is deprecated, so is every member of it.
  • If a class is deprecated, so is every member of it.
  • If a variable is deprecated, so are its implicit getter and setter.

If a feature is deprecated in a superclass, it is not automatically deprecated in a subclass as well. It is reasonable to remove a member from a superclass and retain it in a subclass, so it needs to be possible to deprecate the member only in the superclass.

A tool that processes Raya source code may report when:

  • The code imports a deprecated library.
  • The code exports a deprecated library, or any deprecated member of a non-deprecated library.
  • The code refers statically to a deprecated declaration.
  • The code uses a member of an object with a statically known type, where the member is deprecated on the interface of the static type.
  • The code calls a method with an argument where the corresponding optional parameter is deprecated on the object's static type.

If the deprecated use is inside a library, class or method which is itself deprecated, the tool should not bother the user about it. A deprecated feature is expected to use other deprecated features.

Constructors

Deprecatedconstructor
const Deprecated(this.message)

Creates a deprecation annotation which specifies the migration path and expiration of the annotated feature.

The message is displayed as part of the warning. The message should be aimed at the programmer using the annotated feature, and should recommend an alternative (if available), and say when this feature is expected to be removed if that is sooner or later than the next major version.

Example
@Deprecated('Use area() instead')
double size(double w, double h) => w * h;

double area(double w, double h) => w * h;

void main() {
  // The annotation is a plain const object: its message is readable.
  const note = Deprecated('Use area() instead');
  print('message:  ${note.message}');
  print('old call: ${size(3, 4)}'); // still works, analyzer warns
  print('new call: ${area(3, 4)}');
}
Output
message:  Use area() instead
old call: 12.0
new call: 12.0
const Deprecated.implement([this.message])

Creates an annotation which deprecates implementing a class or mixin.

The annotation can be used on class or mixin declarations whose interface can currently be implemented, so they are not marked final, sealed, or base, but where the ability to implement will be removed in a later release.

Any existing class, mixin or enum declaration which implements the interface will cause a warning that such use is deprecated. Does not affect classes which extend or mix in the annotated class or mixin (see Deprecated.extend, Deprecated.mixin, and Deprecated.subclass).

The annotation is not inherited by subclasses. If a public subclass will also become unimplementable, which it will if the annotated declaration becomes final or base, but not if it becomes sealed, then the subclass should deprecate implementation as well.

The message, if given, is displayed as part of the warning. The message should be aimed at the programmer who owns the implementing class, and should recommend an alternative (if available), and say when this functionality is expected to be removed if that is sooner or later than the next major version.

Example
// Warns anyone who implements Shape; extending it stays fine.
@Deprecated.implement('Extend Shape instead of implementing it')
abstract class Shape {
  double get area;
  String describe() => 'shape with area $area';
}

class Square extends Shape {
  final double side;
  Square(this.side);
  @override
  double get area => side * side;
}

void main() {
  const note = Deprecated.implement('Extend Shape instead of implementing it');
  print('message: ${note.message}');
  print('square:  ${Square(3).describe()}');
}
Output
message: Extend Shape instead of implementing it
square:  shape with area 9.0
const Deprecated.extend([this.message])

Creates an annotation which deprecates extending a class.

The annotation can be used on class declarations which can currently be extended, so they are not marked final, sealed, or interface, but where the ability to extend will be removed in a later release.

Any existing class declaration which extends the class will cause a warning that such use is deprecated. Does not affect classes which implement or mix in the annotated class (see Deprecated.implement, Deprecated.mixin, and Deprecated.subclass).

The annotation is not inherited by subclasses. If a public subclass will also become unextendable, which it will if the annotated declaration becomes final or interface, but not if it becomes sealed, then the subclass should deprecate extendability as well.

The message, if given, is displayed as part of the warning. The message should be aimed at the programmer who owns the extending class, and should recommend an alternative (if available), and say when this functionality is expected to be removed if that is sooner or later than the next major version.

Example
// Warns anyone who extends Logger; implementing or calling it is fine.
@Deprecated.extend('Logger will become final')
class Logger {
  final lines = <String>[];
  void log(String s) => lines.add(s);
}

void main() {
  const note = Deprecated.extend('Logger will become final');
  print('message: ${note.message}');
  final l = Logger()..log('a')..log('b');
  print('lines:   ${l.lines}');
}
Output
message: Logger will become final
lines:   [a, b]
const Deprecated.subclass([this.message])

Creates an annotation which deprecates subclassing (implementing or extending) a class.

The annotation can be used on class and mixin declarations which can currently be subclassed, so they are not marked final, or sealed, but where the ability to subclass will be removed in a later release.

Any existing class declaration which extends or implements the annotated class or mixin will cause a warning that such use is deprecated. Does not affect classes which mix in the annotated class (see Deprecated.extend, Deprecated.implement and Deprecated.mixin).

The annotation is not inherited by subclasses. If a public subclass will also become unsubclassable, which it will if the annotated declaration becomes final, but not if it becomes sealed, then the subclass should deprecate subclassability as well.

The message, if given, is displayed as part of the warning. The message should be aimed at the programmer who owns the subclassing class, and should recommend an alternative (if available), and say when this functionality is expected to be removed if that is sooner or later than the next major version.

Example
// Warns on both extends and implements of Animal.
@Deprecated.subclass('Animal will become sealed')
class Animal {
  String sound() => '...';
}

void main() {
  const note = Deprecated.subclass('Animal will become sealed');
  print('message: ${note.message}');
  print('sound:   ${Animal().sound()}');
}
Output
message: Animal will become sealed
sound:   ...
const Deprecated.instantiate([this.message])

Creates an annotation which deprecates instantiating a class.

The annotation can be used on class declarations which can currently be instantiated, so they are not marked abstract or sealed, but where the ability to instantiate will be removed in a later release.

Any existing code which instantiates the annotated class will cause a warning that such use is deprecated.

The message, if given, is displayed as part of the warning. The message should be aimed at the programmer who owns the instantiating code, and should recommend an alternative (if available), and say when this functionality is expected to be removed if that is sooner or later than the next major version.

Example
// Warns when someone calls a generative constructor of Config directly.
@Deprecated.instantiate('Use Config.defaults()')
class Config {
  final int retries;
  Config(this.retries);
  static Config defaults() => Config(3);
}

void main() {
  const note = Deprecated.instantiate('Use Config.defaults()');
  print('message: ${note.message}');
  print('retries: ${Config.defaults().retries}');
}
Output
message: Use Config.defaults()
retries: 3
Deprecated.mixinconstructor
const Deprecated.mixin([this.message])

Creates an annotation which deprecates mixing in a class.

The annotation can be used on class declarations which can currently be mixed in, so they are marked mixin, but where the ability to mix in will be removed in a later release.

Any existing class declaration which mixes in the annotated class will cause a warning that such use is deprecated. Does not affect classes which extend or implement the annotated class (see Deprecated.extend, Deprecated.implement and Deprecated.subclass).

The message, if given, is displayed as part of the warning. The message should be aimed at the programmer who owns the class which mixes in the annotated class, and should recommend an alternative (if available), and say when this functionality is expected to be removed if that is sooner or later than the next major version.

Example
// Warns when the class is used as a mixin.
@Deprecated.mixin('Use the Greeter base class instead')
mixin class Greeter {
  String greet(String name) => 'Hello, $name';
}

void main() {
  const note = Deprecated.mixin('Use the Greeter base class instead');
  print('message: ${note.message}');
  print('greet:   ${Greeter().greet('Ada')}');
}
Output
message: Use the Greeter base class instead
greet:   Hello, Ada
const Deprecated.optional([this.message])

Creates an annotation which deprecates omitting an argument for the annotated parameter.

The annotation can be used on optional parameters of methods, constructors, or top-level functions, indicating the parameter will be required in a later release.

Any call to a function which does not pass a value for the annotated parameter will cause a warning that such omission is deprecated.

The annotation is not inherited in method overrides.

The message, if given, is displayed as part of the warning. The message should be aimed at the programmer who is calling the function with the annotated parameter, and should recommend an alternative (if available), and say when this functionality is expected to be removed if that is sooner or later than the next major version.

Example
// Marks an optional parameter that will become required.
String label(String text, {@Deprecated.optional('pass width explicitly') int width = 10}) =>
    text.padRight(width, '.');

void main() {
  const note = Deprecated.optional('pass width explicitly');
  print('message: ${note.message}');
  print('default: [${label('ok')}]');
  print('width 5: [${label('ok', width: 5)}]');
}
Output
message: pass width explicitly
default: [ok........]
width 5: [ok...]

Properties

messagefield
final String? message

Message provided to the user when they use the deprecated feature.

The message should explain how to migrate away from the feature if an alternative is available, and when the deprecated feature is expected to be removed.

Methods

toStringmethod
String toString()
Example
void main() {
  const d = Deprecated('Use parseStrict');
  print('toString: ${d.toString()}');
  print('message:  ${d.message}');
  print('constant: ${identical(d, const Deprecated('Use parseStrict'))}');
}
Output
toString: Deprecated feature: Use parseStrict
message:  Use parseStrict
constant: true
class

pragma

final class pragma

A hint to tools.

Tools that work with Raya programs may accept hints to guide their behavior as pragma annotations on declarations. Each tool decides which hints it accepts, what they mean, and whether and how they apply to sub-parts of the annotated entity.

Tools that recognize pragma hints should pick a pragma prefix to identify the tool. They should recognize any hint with a name starting with their prefix followed by : as if it was intended for that tool. A hint with a prefix for another tool should be ignored (unless compatibility with that other tool is a goal).

A tool may recognize unprefixed names as well, if they would recognize that name with their own prefix in front.

If the hint can be parameterized, an extra options object can be added as well.

For example:

@pragma('Tool:pragma-name', [param1, param2, ...])
class Foo { }

@pragma('OtherTool:other-pragma')
void foo() { }

Here class Foo is annotated with a Tool specific pragma 'pragma-name' and function foo is annotated with a pragma 'other-pragma' specific to OtherTool.

Constructors

pragmafactory
const factory pragma(String name, [Object? options]) = pragma._

Creates a hint named name with optional options.

Example
// A pragma is a hint for the compiler; it does not change results.
@pragma('vm:prefer-inline')
int square(int x) => x * x;

void main() {
  const p = pragma('vm:prefer-inline');
  print('name:    ${p.name}');
  print('options: ${p.options}');
  const q = pragma('example:tag', {'level': 2});
  print('with options: ${q.name} ${q.options}');
  print('square(7) = ${square(7)}');
}
Output
name:    vm:prefer-inline
options: null
with options: example:tag {level: 2}
square(7) = 49

Properties

namefield
final String name

The name of the hint.

A string that is recognized by one or more tools, or such a string prefixed by a tool identifier and a colon, which is only recognized by that particular tool.

optionsfield
final Object? options

Optional extra data parameterizing the hint.

class

BigInt

abstract final class BigInt implements Comparable<BigInt>

An arbitrarily large integer value.

Big integers are signed and can have an arbitrary number of significant digits, only limited by memory.

To create a big integer from the provided number, use BigInt.from.

var bigInteger = BigInt.from(-1); // -1
bigInteger = BigInt.from(0.9999); // 0
bigInteger = BigInt.from(-10.99); // -10
bigInteger = BigInt.from(0x7FFFFFFFFFFFFFFF); // 9223372036854775807
bigInteger = BigInt.from(1e+30); // 1000000000000000019884624838656

To parse a large integer value from a string, use parse or tryParse.

var value = BigInt.parse('0x1ffffffffffffffff'); // 36893488147419103231
value = BigInt.parse('12345678901234567890'); // 12345678901234567890

To check whether a big integer can be represented as an int without losing precision, use isValidInt.

print(bigNumber.isValidInt); // false

To convert a big integer into an int, use toInt. To convert a big integer into an double, use toDouble.

var bigValue = BigInt.from(10).pow(3);
print(bigValue.isValidInt); // true
print(bigValue.toInt()); // 1000
print(bigValue.toDouble()); // 1000.0

See also:

  • int: An integer number.
  • double: A double-precision floating point number.
  • num: The super class for int and double.

Constructors

external factory BigInt.from(num value)

Creates a big integer from the provided value number.

Examples:

var bigInteger = BigInt.from(1); // 1
bigInteger = BigInt.from(0.9999); // 0
bigInteger = BigInt.from(-10.99); // -10
Example
void main() {
  BigInt fact(int n) {
    var r = BigInt.one;
    for (var i = 2; i <= n; i++) r *= BigInt.from(i);
    return r;
  }
  print('25! = ${fact(25)}');
  print('fits in int: ${fact(20).isValidInt}, ${fact(25).isValidInt}');
  print('20! as int: ${fact(20).toInt()}');
}
Output
25! = 15511210043330985984000000
fits in int: true, false
20! as int: 2432902008176640000

Static

zerostaticgetter
external static BigInt get zero

A big integer with the numerical value 0.

onestaticgetter
external static BigInt get one

A big integer with the numerical value 1.

twostaticgetter
external static BigInt get two

A big integer with the numerical value 2.

parsestaticmethod
external static BigInt parse(String source, {int? radix})

Parses source as a, possibly signed, integer literal and returns its value.

The source must be a non-empty sequence of base-radix digits, optionally prefixed with a minus or plus sign ('-' or '+').

The radix must be in the range 2..36. The digits used are first the decimal digits 0..9, and then the letters 'a'..'z' with values 10 through 35. Also accepts upper-case letters with the same values as the lower-case ones.

If no radix is given then it defaults to 10. In this case, the source digits may also start with 0x, in which case the number is interpreted as a hexadecimal literal, which effectively means that the 0x is ignored and the radix is instead set to 16.

For any int n and radix r, it is guaranteed that n == int.parse(n.toRadixString(r), radix: r).

Throws a FormatException if the source is not a valid integer literal, optionally prefixed by a sign. Examples:

print(BigInt.parse('-12345678901234567890')); // -12345678901234567890
print(BigInt.parse('0xFF')); // 255
print(BigInt.parse('0xffffffffffffffff')); // 18446744073709551615

// From binary (base 2) value.
print(BigInt.parse('1100', radix: 2)); // 12
print(BigInt.parse('00011111', radix: 2)); // 31
print(BigInt.parse('011111100101', radix: 2)); // 2021
// From octal (base 8) value.
print(BigInt.parse('14', radix: 8)); // 12
print(BigInt.parse('37', radix: 8)); // 31
print(BigInt.parse('3745', radix: 8)); // 2021
// From hexadecimal (base 16) value.
print(BigInt.parse('c', radix: 16)); // 12
print(BigInt.parse('1f', radix: 16)); // 31
print(BigInt.parse('7e5', radix: 16)); // 2021
// From base 35 value.
print(BigInt.parse('y1', radix: 35)); // 1191 == 34 * 35 + 1
print(BigInt.parse('z1', radix: 35)); // Throws.
// From base 36 value.
print(BigInt.parse('y1', radix: 36)); // 1225 == 34 * 36 + 1
print(BigInt.parse('z1', radix: 36)); // 1261 == 35 * 36 + 1
Example
void main() {
  final n = BigInt.parse('123456789012345678901234567890');
  print('n     = $n');
  print('n * n = ${n * n}');
  print('hex   = ${BigInt.parse('ff' * 10, radix: 16)}');
}
Output
n     = 123456789012345678901234567890
n * n = 15241578753238836750495351562536198787501905199875019052100
hex   = 1208925819614629174706175
tryParsestaticmethod
external static BigInt? tryParse(String source, {int? radix})

Parses source as a, possibly signed, integer literal and returns its value.

As parse except that this method returns null if the input is not valid

Examples:

print(BigInt.tryParse('-12345678901234567890')); // -12345678901234567890
print(BigInt.tryParse('0xFF')); // 255
print(BigInt.tryParse('0xffffffffffffffff')); // 18446744073709551615

// From binary (base 2) value.
print(BigInt.tryParse('1100', radix: 2)); // 12
print(BigInt.tryParse('00011111', radix: 2)); // 31
print(BigInt.tryParse('011111100101', radix: 2)); // 2021
// From octal (base 8) value.
print(BigInt.tryParse('14', radix: 8)); // 12
print(BigInt.tryParse('37', radix: 8)); // 31
print(BigInt.tryParse('3745', radix: 8)); // 2021
// From hexadecimal (base 16) value.
print(BigInt.tryParse('c', radix: 16)); // 12
print(BigInt.tryParse('1f', radix: 16)); // 31
print(BigInt.tryParse('7e5', radix: 16)); // 2021
// From base 35 value.
print(BigInt.tryParse('y1', radix: 35)); // 1191 == 34 * 35 + 1
print(BigInt.tryParse('z1', radix: 35)); // null
// From base 36 value.
print(BigInt.tryParse('y1', radix: 36)); // 1225 == 34 * 36 + 1
print(BigInt.tryParse('z1', radix: 36)); // 1261 == 35 * 36 + 1
Example
void main() {
  print('decimal: ${BigInt.tryParse('123456789012345678901234567890')}');
  print('hex:     ${BigInt.tryParse('ff', radix: 16)}');
  print('binary:  ${BigInt.tryParse('101010', radix: 2)}');
  print('bad:     ${BigInt.tryParse('12x')}');
  print('empty:   ${BigInt.tryParse('')}');
}
Output
decimal: 123456789012345678901234567890
hex:     255
binary:  42
bad:     null
empty:   null

Properties

bitLengthgetter
int get bitLength

Returns the minimum number of bits required to store this big integer.

The number of bits excludes the sign bit, which gives the natural length for non-negative (unsigned) values. Negative values are complemented to return the bit position of the first bit that differs from the sign bit.

To find the number of bits needed to store the value as a signed value, add one, i.e. use x.bitLength + 1.

x.bitLength == (-x-1).bitLength;

BigInt.from(3).bitLength == 2;   // 00000011
BigInt.from(2).bitLength == 2;   // 00000010
BigInt.from(1).bitLength == 1;   // 00000001
BigInt.from(0).bitLength == 0;   // 00000000
BigInt.from(-1).bitLength == 0;  // 11111111
BigInt.from(-2).bitLength == 1;  // 11111110
BigInt.from(-3).bitLength == 2;  // 11111101
BigInt.from(-4).bitLength == 2;  // 11111100
signgetter
int get sign

Returns the sign of this big integer.

Returns 0 for zero, -1 for values less than zero and +1 for values greater than zero.

isEvengetter
bool get isEven

Whether this big integer is even.

isOddgetter
bool get isOdd

Whether this big integer is odd.

bool get isNegative

Whether this number is negative.

bool get isValidInt

Whether this big integer can be represented as an int without losing precision.

Warning: this function may give a different result on the JavaScript compiler, dev compiler, and the VM, due to the differences in integer precision.

Example:

var bigNumber = BigInt.parse('100000000000000000000000');
print(bigNumber.isValidInt); // false

var value = BigInt.parse('0xFF'); // 255
print(value.isValidInt); // true

Methods

absmethod
BigInt abs()

Returns the absolute value of this integer.

For any integer x, the result is the same as x < 0 ? -x: x.

Example
void main() {
  final n = BigInt.parse('-98765432109876543210');
  print('n       = $n');
  print('n.abs() = ${n.abs()}');
  print('0.abs() = ${BigInt.zero.abs()}');
}
Output
n       = -98765432109876543210
n.abs() = 98765432109876543210
0.abs() = 0
remaindermethod
BigInt remainder(BigInt other)

Returns the remainder of the truncating division of this by other.

As a consequence the remainder r has the same sign as the divider this.

Example:

print(BigInt.from(5).remainder(BigInt.from(3))); // 2
print(BigInt.from(-5).remainder(BigInt.from(3))); // -2
print(BigInt.from(5).remainder(BigInt.from(-3))); // 2
print(BigInt.from(-5).remainder(BigInt.from(-3))); // -2
Example
void main() {
  final a = BigInt.from(-17), b = BigInt.from(5);
  print('(-17).remainder(5) = ${a.remainder(b)}  (sign of the dividend)');
  print('(-17) % 5          = ${a % b}  (always non-negative)');
  final big = BigInt.two.pow(100);
  print('2^100 remainder 7  = ${big.remainder(BigInt.from(7))}');
}
Output
(-17).remainder(5) = -2  (sign of the dividend)
(-17) % 5          = 3  (always non-negative)
2^100 remainder 7  = 2
compareTomethod
int compareTo(BigInt other)

Compares this to other.

Returns a negative number if this is less than other, zero if they are equal, and a positive number if this is greater than other.

Example:

print(BigInt.from(1).compareTo(BigInt.from(2))); // => -1
print(BigInt.from(2).compareTo(BigInt.from(1))); // => 1
print(BigInt.from(1).compareTo(BigInt.from(1))); // => 0
Example
void main() {
  final a = BigInt.parse('100000000000000000000');
  final b = BigInt.parse('99999999999999999999');
  print('a.compareTo(b) = ${a.compareTo(b)}');
  print('b.compareTo(a) = ${b.compareTo(a)}');
  print('a.compareTo(a) = ${a.compareTo(a)}');
  final xs = [BigInt.from(30), BigInt.from(-5), BigInt.from(12)]..sort();
  print('sorted: $xs');
}
Output
a.compareTo(b) = 1
b.compareTo(a) = -1
a.compareTo(a) = 0
sorted: [-5, 12, 30]
powmethod
BigInt pow(int exponent)

Returns this to the power of exponent.

Returns one if the exponent equals 0.

The exponent must otherwise be positive.

The result is always equal to the mathematical result of this to the power exponent, only limited by the available memory.

Example:

var value = BigInt.from(1000);
print(value.pow(0)); // 1
print(value.pow(1)); // 1000
print(value.pow(2)); // 1000000
print(value.pow(3)); // 1000000000
print(value.pow(4)); // 1000000000000
print(value.pow(5)); // 1000000000000000
print(value.pow(6)); // 1000000000000000000
print(value.pow(7)); // 1000000000000000000000
print(value.pow(8)); // 1000000000000000000000000
Example
void main() {
  final two = BigInt.two;
  print('2^100 = ${two.pow(100)}');
  print('digits: ${two.pow(1000).toString().length}');
}
Output
2^100 = 1267650600228229401496703205376
digits: 302
modPowmethod
BigInt modPow(BigInt exponent, BigInt modulus)

Returns this integer to the power of exponent modulo modulus.

The exponent must be non-negative and modulus must be positive.

Example
void main() {
  // A toy RSA round-trip with exact big integers.
  final p = BigInt.from(61), q = BigInt.from(53);
  final n = p * q;
  final phi = (p - BigInt.one) * (q - BigInt.one);
  final e = BigInt.from(17);
  final d = e.modInverse(phi);
  final msg = BigInt.from(65);
  final enc = msg.modPow(e, n);
  print('n = $n, d = $d');
  print('encrypted: $enc');
  print('decrypted: ${enc.modPow(d, n)}');
}
Output
n = 3233, d = 2753
encrypted: 2790
decrypted: 65
BigInt modInverse(BigInt modulus)

Returns the modular multiplicative inverse of this big integer modulo modulus.

The modulus must be positive.

It is an error if no modular inverse exists.

Example
void main() {
  final m = BigInt.from(97);
  final a = BigInt.from(35);
  final inv = a.modInverse(m);
  print('35^-1 mod 97 = $inv');
  print('check: 35 * $inv mod 97 = ${(a * inv) % m}');
  try {
    BigInt.from(6).modInverse(BigInt.from(9));
  } catch (e) {
    print('6 has no inverse mod 9: ${e.runtimeType}');
  }
}
Output
35^-1 mod 97 = 61
check: 35 * 61 mod 97 = 1
6 has no inverse mod 9: _Exception
gcdmethod
BigInt gcd(BigInt other)

Returns the greatest common divisor of this big integer and other.

If either number is non-zero, the result is the numerically greatest integer dividing both this and other.

The greatest common divisor is independent of the order, so x.gcd(y) is always the same as y.gcd(x).

For any integer x, x.gcd(x) is x.abs.

If both this and other is zero, the result is also zero.

Example:

print(BigInt.from(4).gcd(BigInt.from(2))); // 2
print(BigInt.from(8).gcd(BigInt.from(4))); // 4
print(BigInt.from(10).gcd(BigInt.from(12))); // 2
print(BigInt.from(10).gcd(BigInt.from(10))); // 10
print(BigInt.from(-2).gcd(BigInt.from(-3))); // 1
Example
void main() {
  final a = BigInt.parse('1071'), b = BigInt.parse('462');
  print('gcd(1071, 462) = ${a.gcd(b)}');
  final f = BigInt.from(2).pow(64) - BigInt.one;
  print('gcd(2^64 - 1, 2^32 + 1) = ${f.gcd(BigInt.from(2).pow(32) + BigInt.one)}');
}
Output
gcd(1071, 462) = 21
gcd(2^64 - 1, 2^32 + 1) = 4294967297
BigInt toUnsigned(int width)

Returns the least significant width bits of this big integer as a non-negative number (i.e. unsigned representation). The returned value has zeros in all bit positions higher than width.

BigInt.from(-1).toUnsigned(5) == 31   // 11111111  ->  00011111

This operation can be used to simulate arithmetic from low level languages. For example, to increment an 8 bit quantity:

q = (q + 1).toUnsigned(8);

q will count from 0 up to 255 and then wrap around to 0.

If the input fits in width bits without truncation, the result is the same as the input. The minimum width needed to avoid truncation of x is given by x.bitLength, i.e.

x == x.toUnsigned(x.bitLength);
Example
void main() {
  final n = BigInt.from(-1);
  print('-1 as 8-bit unsigned:  ${n.toUnsigned(8)}');
  print('-1 as 64-bit unsigned: ${n.toUnsigned(64)}');
  print('300 as 8-bit unsigned: ${BigInt.from(300).toUnsigned(8)}');
}
Output
-1 as 8-bit unsigned:  255
-1 as 64-bit unsigned: 18446744073709551615
300 as 8-bit unsigned: 44
toSignedmethod
BigInt toSigned(int width)

Returns the least significant width bits of this integer, extending the highest retained bit to the sign. This is the same as truncating the value to fit in width bits using an signed 2-s complement representation. The returned value has the same bit value in all positions higher than width.

var big15 = BigInt.from(15);
var big16 = BigInt.from(16);
var big239 = BigInt.from(239);
                               //     V--sign bit-V
big16.toSigned(5) == -big16;   //  00010000 -> 11110000
big239.toSigned(5) == big15;   //  11101111 -> 00001111
                               //     ^           ^

This operation can be used to simulate arithmetic from low level languages. For example, to increment an 8 bit signed quantity:

q = (q + 1).toSigned(8);

q will count from 0 up to 127, wrap to -128 and count back up to 127.

If the input value fits in width bits without truncation, the result is the same as the input. The minimum width needed to avoid truncation of x is x.bitLength + 1, i.e.

x == x.toSigned(x.bitLength + 1);
Example
void main() {
  print('255 as 8-bit signed:  ${BigInt.from(255).toSigned(8)}');
  print('127 as 8-bit signed:  ${BigInt.from(127).toSigned(8)}');
  final u64 = BigInt.parse('18446744073709551615');
  print('2^64-1 as 64-bit signed: ${u64.toSigned(64)}');
}
Output
255 as 8-bit signed:  -1
127 as 8-bit signed:  127
2^64-1 as 64-bit signed: -1
toIntmethod
int toInt()

Returns this BigInt as an int.

If the number does not fit, clamps to the max (or min) integer.

Warning: the clamping behaves differently between the web and native platforms due to the differences in integer precision.

Example:

var bigNumber = BigInt.parse('100000000000000000000000');
print(bigNumber.isValidInt); // false
print(bigNumber.toInt()); // 9223372036854775807
Example
void main() {
  print('small: ${BigInt.from(42).toInt()}');
  final big = BigInt.two.pow(70) + BigInt.from(5);
  print('isValidInt(2^70+5): ${big.isValidInt}');
  print('(2^70+5).toInt():   ${big.toInt()}  (clamped)');
}
Output
small: 42
isValidInt(2^70+5): false
(2^70+5).toInt():   9223372036854775807  (clamped)
toDoublemethod
double toDouble()

Returns this BigInt as a double.

If the number is not representable as a double, an approximation is returned. For numerically large integers, the approximation may be infinite.

Example:

var bigNumber = BigInt.parse('100000000000000000000000');
print(bigNumber.toDouble()); // 1e+23
Example
void main() {
  print('2^53     -> ${BigInt.two.pow(53).toDouble()}');
  print('2^53 + 1 -> ${(BigInt.two.pow(53) + BigInt.one).toDouble()}  (nearest double)');
  print('10^30    -> ${BigInt.from(10).pow(30).toDouble()}');
}
Output
2^53     -> 9007199254740992.0
2^53 + 1 -> 9007199254740992.0  (nearest double)
10^30    -> 1e+30
toStringmethod
String toString()

Returns a String-representation of this integer.

The returned string is parsable by parse. For any BigInt i, it is guaranteed that i == BigInt.parse(i.toString).

Example:

var bigNumber = BigInt.parse('100000000000000000000000');
print(bigNumber.toString()); // "100000000000000000000000"
Example
void main() {
  final n = BigInt.from(2).pow(80);
  print('toString(): ${n.toString()}');
  print('digits:     ${n.toString().length}');
  print('negative:   ${(-n).toString()}');
}
Output
toString(): 1208925819614629174706176
digits:     25
negative:   -1208925819614629174706176
String toRadixString(int radix)

Converts this BigInt to a string representation in the given radix.

In the string representation, lower-case letters are used for digits above '9', with 'a' being 10 an 'z' being 35.

The radix argument must be an integer in the range 2 to 36.

Example:

// Binary (base 2).
print(BigInt.from(12).toRadixString(2)); // 1100
print(BigInt.from(31).toRadixString(2)); // 11111
print(BigInt.from(2021).toRadixString(2)); // 11111100101
print(BigInt.from(-12).toRadixString(2)); // -1100
// Octal (base 8).
print(BigInt.from(12).toRadixString(8)); // 14
print(BigInt.from(31).toRadixString(8)); // 37
print(BigInt.from(2021).toRadixString(8)); // 3745
// Hexadecimal (base 16).
print(BigInt.from(12).toRadixString(16)); // c
print(BigInt.from(31).toRadixString(16)); // 1f
print(BigInt.from(2021).toRadixString(16)); // 7e5
// Base 36.
print(BigInt.from(35 * 36 + 1).toRadixString(36)); // z1
Example
void main() {
  final n = BigInt.from(2).pow(70);
  print('2^70 in hex:    ${n.toRadixString(16)}');
  print('2^70 in base 2 has ${n.toRadixString(2).length} digits');
  print('bitLength:      ${n.bitLength}');
}
Output
2^70 in hex:    400000000000000000
2^70 in base 2 has 71 digits
bitLength:      71

Operators

operator -operator
BigInt operator -()

Return the negative value of this integer.

The result of negating an integer always has the opposite sign, except for zero, which is its own negation.

Example
void main() {
  final n = BigInt.parse('12345678901234567890');
  print('-n      = ${-n}');
  print('-(-n)   = ${-(-n)}');
  print('-zero   = ${-BigInt.zero}');
}
Output
-n      = -12345678901234567890
-(-n)   = 12345678901234567890
-zero   = 0
operator +operator
BigInt operator +(BigInt other)

Adds other to this big integer.

The result is again a big integer.

Example
void main() {
  final a = BigInt.parse('9223372036854775807'); // largest 64-bit int
  print('a     = $a');
  print('a + 1 = ${a + BigInt.one}  (no overflow)');
  var fib = [BigInt.zero, BigInt.one];
  for (var i = 0; i < 99; i++) fib.add(fib[fib.length - 1] + fib[fib.length - 2]);
  print('fib(100) = ${fib[100]}');
}
Output
a     = 9223372036854775807
a + 1 = 9223372036854775808  (no overflow)
fib(100) = 354224848179261915075
operator -operator
BigInt operator -(BigInt other)

Subtracts other from this big integer.

The result is again a big integer.

Example
void main() {
  final a = BigInt.two.pow(100), b = BigInt.two.pow(99);
  print('2^100 - 2^99 = ${a - b}');
  print('equals 2^99:  ${a - b == b}');
  print('5 - 8        = ${BigInt.from(5) - BigInt.from(8)}');
}
Output
2^100 - 2^99 = 633825300114114700748351602688
equals 2^99:  true
5 - 8        = -3
operator *operator
BigInt operator *(BigInt other)

Multiplies other by this big integer.

The result is again a big integer.

Example
void main() {
  var f = BigInt.one;
  for (var i = 1; i <= 30; i++) f *= BigInt.from(i);
  print('30! = $f');
  print('(-3) * 4 = ${BigInt.from(-3) * BigInt.from(4)}');
}
Output
30! = 265252859812191058636308480000000
(-3) * 4 = -12
operator /operator
double operator /(BigInt other)

Double division operator.

Matching the similar operator on int, this operation first performs toDouble on both this big integer and other, then does [double.operator/] on those values and returns the result.

Note: The initial toDouble conversion may lose precision.

Example:

print(BigInt.from(1) / BigInt.from(2)); // 0.5
print(BigInt.from(1.99999) / BigInt.from(2)); // 0.5
Example
void main() {
  final a = BigInt.from(22), b = BigInt.from(7);
  print('22 / 7  = ${a / b}  (a double)');
  print('22 ~/ 7 = ${a ~/ b}  (a BigInt)');
  print('10^30 / 3 = ${BigInt.from(10).pow(30) / BigInt.from(3)}');
}
Output
22 / 7  = 3.142857142857143  (a double)
22 ~/ 7 = 3  (a BigInt)
10^30 / 3 = 3.333333333333333e+29
operator ~/operator
BigInt operator ~/(BigInt other)

Truncating integer division operator.

Performs a truncating integer division, where the remainder is discarded.

The remainder can be computed using the remainder method.

Examples:

var seven = BigInt.from(7);
var three = BigInt.from(3);
seven ~/ three;    // => 2
(-seven) ~/ three; // => -2
seven ~/ -three;   // => -2
seven.remainder(three);    // => 1
(-seven).remainder(three); // => -1
seven.remainder(-three);   // => 1
Example
void main() {
  final a = BigInt.parse('100000000000000000000');
  final b = BigInt.from(7);
  print('a ~/ 7 = ${a ~/ b}');
  print('a % 7  = ${a % b}');
  print('a / 7  = ${a / b} (a double)');
}
Output
a ~/ 7 = 14285714285714285714
a % 7  = 2
a / 7  = 14285714285714287000.0 (a double)
operator %operator
BigInt operator %(BigInt other)

Euclidean modulo operator.

Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs.

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

Example:

print(BigInt.from(5) % BigInt.from(3)); // 2
print(BigInt.from(-5) % BigInt.from(3)); // 1
print(BigInt.from(5) % BigInt.from(-3)); // 2
print(BigInt.from(-5) % BigInt.from(-3)); // 1
Example
void main() {
  final m = BigInt.from(7);
  print(' 17 % 7 = ${BigInt.from(17) % m}');
  print('-17 % 7 = ${BigInt.from(-17) % m}  (euclidean: never negative)');
  print('2^127 - 1 % 1000 = ${(BigInt.two.pow(127) - BigInt.one) % BigInt.from(1000)}');
}
Output
 17 % 7 = 3
-17 % 7 = 4  (euclidean: never negative)
2^127 - 1 % 1000 = 727
operator <<operator
BigInt operator <<(int shiftAmount)

Shift the bits of this integer to the left by shiftAmount.

Shifting to the left makes the number larger, effectively multiplying the number by pow(2, shiftIndex).

There is no limit on the size of the result. It may be relevant to limit intermediate values by using the "and" operator with a suitable mask.

It is an error if shiftAmount is negative.

Example
void main() {
  final one = BigInt.one;
  print('1 << 10  = ${one << 10}');
  print('1 << 100 = ${one << 100}');
  print('equals 2^100: ${(one << 100) == BigInt.two.pow(100)}');
}
Output
1 << 10  = 1024
1 << 100 = 1267650600228229401496703205376
equals 2^100: true
operator >>operator
BigInt operator >>(int shiftAmount)

Shift the bits of this integer to the right by shiftAmount.

Shifting to the right makes the number smaller and drops the least significant bits, effectively doing an integer division by pow(2, shiftIndex).

It is an error if shiftAmount is negative.

Example
void main() {
  final n = BigInt.two.pow(100);
  print('2^100 >> 90 = ${n >> 90}');
  print('-9 >> 1     = ${BigInt.from(-9) >> 1}  (rounds toward -infinity)');
}
Output
2^100 >> 90 = 1024
-9 >> 1     = -5  (rounds toward -infinity)
operator &operator
BigInt operator &(BigInt other)

Bit-wise and operator.

Treating both this and other as sufficiently large two's component integers, the result is a number with only the bits set that are set in both this and other

Of both operands are negative, the result is negative, otherwise the result is non-negative.

Example
void main() {
  final a = BigInt.parse('ff00ff00ff00ff00ff', radix: 16);
  final mask = BigInt.parse('ffff', radix: 16);
  print('low 16 bits: ${(a & mask).toRadixString(16)}');
  print('12 & 10 = ${BigInt.from(12) & BigInt.from(10)}');
}
Output
low 16 bits: ff
12 & 10 = 8
operator |operator
BigInt operator |(BigInt other)

Bit-wise or operator.

Treating both this and other as sufficiently large two's component integers, the result is a number with the bits set that are set in either of this and other

If both operands are non-negative, the result is non-negative, otherwise the result is negative.

Example
void main() {
  final hi = BigInt.one << 80;
  final lo = BigInt.from(5);
  print('(1<<80) | 5 = ${hi | lo}');
  print('hex: ${(hi | lo).toRadixString(16)}');
  print('12 | 10 = ${BigInt.from(12) | BigInt.from(10)}');
}
Output
(1<<80) | 5 = 1208925819614629174706181
hex: 100000000000000000005
12 | 10 = 14
operator ^operator
BigInt operator ^(BigInt other)

Bit-wise exclusive-or operator.

Treating both this and other as sufficiently large two's component integers, the result is a number with the bits set that are set in one, but not both, of this and other

If the operands have the same sign, the result is non-negative, otherwise the result is negative.

Example
void main() {
  final key = BigInt.parse('a5a5a5a5a5a5a5a5a5', radix: 16);
  final msg = BigInt.parse('123456789abcdef012', radix: 16);
  final enc = msg ^ key;
  print('encrypted: ${enc.toRadixString(16)}');
  print('decrypted: ${(enc ^ key).toRadixString(16)}');
}
Output
encrypted: b791f3dd3f197b55b7
decrypted: 123456789abcdef012
operator ~operator
BigInt operator ~()

The bit-wise negate operator.

Treating this as a sufficiently large two's component integer, the result is a number with the opposite bits set.

This maps any integer x to -x - 1.

Example
void main() {
  print('~0  = ${~BigInt.zero}');
  print('~5  = ${~BigInt.from(5)}  (equals -6)');
  print('~-1 = ${~BigInt.from(-1)}');
}
Output
~0  = -1
~5  = -6  (equals -6)
~-1 = 0
operator <operator
bool operator <(BigInt other)

Whether this big integer is numerically smaller than other.

Example
void main() {
  final a = BigInt.two.pow(64), b = BigInt.parse('18446744073709551616');
  final c = BigInt.from(-3);
  print('2^64 < 2^64 (parsed): ${a < b}');
  print('2^64 < -3:            ${a < c}');
  print('-3 < 2^64:            ${c < a}');
}
Output
2^64 < 2^64 (parsed): false
2^64 < -3:            false
-3 < 2^64:            true
operator <=operator
bool operator <=(BigInt other)

Whether other is numerically greater than this big integer.

Example
void main() {
  final a = BigInt.two.pow(64), b = BigInt.parse('18446744073709551616');
  final c = BigInt.from(-3);
  print('2^64 <= 2^64 (parsed): ${a <= b}');
  print('2^64 <= -3:            ${a <= c}');
  print('-3 <= 2^64:            ${c <= a}');
}
Output
2^64 <= 2^64 (parsed): true
2^64 <= -3:            false
-3 <= 2^64:            true
operator >operator
bool operator >(BigInt other)

Whether this big integer is numerically greater than other.

Example
void main() {
  final a = BigInt.two.pow(64), b = BigInt.parse('18446744073709551616');
  final c = BigInt.from(-3);
  print('2^64 > 2^64 (parsed): ${a > b}');
  print('2^64 > -3:            ${a > c}');
  print('-3 > 2^64:            ${c > a}');
}
Output
2^64 > 2^64 (parsed): false
2^64 > -3:            true
-3 > 2^64:            false
operator >=operator
bool operator >=(BigInt other)

Whether other is numerically smaller than this big integer.

Example
void main() {
  final a = BigInt.two.pow(64), b = BigInt.parse('18446744073709551616');
  final c = BigInt.from(-3);
  print('2^64 >= 2^64 (parsed): ${a >= b}');
  print('2^64 >= -3:            ${a >= c}');
  print('-3 >= 2^64:            ${c >= a}');
}
Output
2^64 >= 2^64 (parsed): true
2^64 >= -3:            true
-3 >= 2^64:            false
class

bool

final class bool

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.

Constructors

external const factory bool.fromEnvironment(String name, {bool defaultValue = false})

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 Raya 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.

Example
void main() {
  // Set with: raya run -DverboseLog=true main.ray
  const verbose = bool.fromEnvironment('verboseLog');
  const strict = bool.fromEnvironment('strictMode', defaultValue: true);
  print('verboseLog (default false): $verbose');
  print('strictMode (default true):  $strict');
}
Output
verboseLog (default false): false
strictMode (default true):  true
external const factory bool.hasEnvironment(String name)

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 Raya 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.

Example
void main() {
  const has = bool.hasEnvironment('releaseChannel');
  print('releaseChannel declared: $has');
  const channel = has ? String.fromEnvironment('releaseChannel') : 'dev';
  print('channel: $channel');
}
Output
releaseChannel declared: false
channel: dev

Static

parsestaticmethod
external static bool parse(String source, {bool caseSensitive = true})

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
Example
void main() {
  print(bool.parse('true'));
  print(bool.parse('FALSE', caseSensitive: false));
  print(bool.tryParse('yes'));
}
Output
true
false
null
tryParsestaticmethod
external static bool? tryParse(String source, {bool caseSensitive = true})

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
Example
void main() {
  print('"true"  -> ${bool.tryParse('true')}');
  print('"false" -> ${bool.tryParse('false')}');
  print('"TRUE"  -> ${bool.tryParse('TRUE')}');
  print('"TRUE" caseSensitive: false -> ${bool.tryParse('TRUE', caseSensitive: false)}');
  print('"yes"   -> ${bool.tryParse('yes')}');
}
Output
"true"  -> true
"false" -> false
"TRUE"  -> null
"TRUE" caseSensitive: false -> true
"yes"   -> null

Properties

hashCodegetter
external int get hashCode

Methods

toStringmethod
String toString()

Returns either "true" for true and "false" for false.

Example
void main() {
  print('true.toString():  ${true.toString()}');
  print('(3 > 2).toString(): ${(3 > 2).toString()}');
  print('in a string: ready=${1 == 2}');
}
Output
true.toString():  true
(3 > 2).toString(): true
in a string: ready=false

Operators

operator &operator
bool operator &(bool other)

The logical conjunction ("and") of this and other.

Returns true if both this and other are true, and false otherwise.

Example
void main() {
  const a = true, b = false;
  print('a & b = ${a & b}');
  print('a | b = ${a | b}');
  print('a ^ b = ${a ^ b}');
  print('a && b = ${a && b}, a || b = ${a || b}, !a = ${!a}');
}
Output
a & b = false
a | b = true
a ^ b = true
a && b = false, a || b = true, !a = false
operator |operator
bool operator |(bool other)

The logical disjunction ("inclusive or") of this and other.

Returns true if either this or other is true, and false otherwise.

Example
int calls = 0;
bool check(bool v) { calls++; return v; }

void main() {
  print('true | false = ${true | false}');
  calls = 0;
  final a = check(true) | check(false);
  print('|  evaluates both sides: $a, calls=$calls');
  calls = 0;
  final b = check(true) || check(false);
  print('|| short-circuits:       $b, calls=$calls');
}
Output
true | false = true
|  evaluates both sides: true, calls=2
|| short-circuits:       true, calls=1
operator ^operator
bool operator ^(bool other)

The logical exclusive disjunction ("exclusive or") of this and other.

Returns whether this and other are neither both true nor both false.

Example
void main() {
  for (final a in [false, true]) {
    for (final b in [false, true]) {
      print('$a ^ $b = ${a ^ b}');
    }
  }
}
Output
false ^ false = false
false ^ true = true
true ^ false = true
true ^ true = false
abstract interface class Comparable<T>

Interface used by types that have an intrinsic ordering.

The compareTo operation defines a total ordering of objects, which can be used for ordering and sorting.

The Comparable interface should be used for the natural ordering of a type. If a type can be ordered in more than one way, and none of them is the obvious natural ordering, then it might be better not to use the Comparable interface, and to provide separate Comparators instead.

It is recommended that the order of a Comparable agrees with its operator [operator ==] equality (a.compareTo(b) == 0 iff a == b), but this is not a requirement. For example, double and DateTime have compareTo methods that do not agree with operator [operator ==]. For doubles the compareTo method is more precise than the equality, and for DateTime it is less precise.

Examples:

(0.0).compareTo(-0.0);   // => 1
0.0 == -0.0;             // => true
var now = DateTime.now();
var utcNow = now.toUtc();
now == utcNow;           // => false
now.compareTo(utcNow);   // => 0

The Comparable interface does not imply the existence of the comparison operators <, <=, > and >=. These should only be defined if the ordering is a less-than/greater-than ordering, that is, an ordering where you would naturally use the words "less than" about the order of two elements.

If the equality operator and compareTo disagree, the comparison operators should follow the equality operator, and will likely also disagree with compareTo. Otherwise they should match the compareTo method, so that a < b iff a.compareTo(b) < 0.

The double class defines comparison operators that are compatible with equality. The operators differ from double.compareTo on -0.0 and NaN.

The DateTime class has no comparison operators, instead it has the more precisely named DateTime.isBefore and DateTime.isAfter, which both agree with DateTime.compareTo.

Example
// A type that sorts by implementing Comparable.
class Version implements Comparable<Version> {
  final int major, minor;
  Version(this.major, this.minor);
  @override
  int compareTo(Version o) => major != o.major ? major - o.major : minor - o.minor;
  @override
  String toString() => '$major.$minor';
}

void main() {
  final vs = [Version(1, 10), Version(0, 9), Version(1, 2)]..sort();
  print('sorted: $vs');
  print('newest: ${vs.last}');
}
Output
sorted: [0.9, 1.2, 1.10]
newest: 1.10

Static

comparestaticmethod
static int compare(Comparable a, Comparable b)

A Comparator that compares one comparable to another.

It returns the result of a.compareTo(b). The call may fail at run-time if a is not comparable to the type of b.

This utility function is used as the default comparator for ordering collections, for example in the List sort function.

Example
void main() {
  final xs = ['pear', 'apple', 'fig'];
  xs.sort(Comparable.compare);
  print(xs);
  print(Comparable.compare(2, 10));
}
Output
[apple, fig, pear]
-1

Methods

compareTomethod
int compareTo(T other)

Compares this object to another object.

Returns a value like a Comparator when comparing this to other. That is, it returns a negative integer if this is ordered before other, a positive integer if this is ordered after other, and zero if this and other are ordered together.

The other argument must be a value that is comparable to this object.

Example
class Version implements Comparable<Version> {
  final int major, minor;
  Version(this.major, this.minor);
  @override
  int compareTo(Version o) => major != o.major ? major - o.major : minor - o.minor;
  @override
  String toString() => '$major.$minor';
}

void main() {
  print("'apple'.compareTo('banana') = ${'apple'.compareTo('banana')}");
  print('3.compareTo(3) = ${3.compareTo(3)}');
  final vs = [Version(2, 1), Version(1, 9), Version(2, 0)]..sort();
  print('sorted versions: $vs');
}
Output
'apple'.compareTo('banana') = -1
3.compareTo(3) = 0
sorted versions: [1.9, 2.0, 2.1]
class DateTime implements Comparable<DateTime>

An instant in time, such as July 20, 1969, 8:18pm GMT.

DateTimes can represent time values that are at a distance of at most 100,000,000 days from epoch: -271821-04-20 to 275760-09-13.

Create a DateTime object by using one of the constructors or by parsing a correctly formatted string, which complies with a subset of ISO 8601. Note: hours are specified between 0 and 23, as in a 24-hour clock.

For example:

final now = DateTime.now();
final berlinWallFell = DateTime.utc(1989, 11, 9);
final moonLanding = DateTime.parse('1969-07-20 20:18:04Z'); // 8:18pm

A DateTime object is anchored either in the UTC time zone or in the local time zone of the current computer when the object is created.

Once created, neither the value nor the time zone of a DateTime object may be changed.

You can use properties to get the individual units of a DateTime object.

print(berlinWallFell.year); // 1989
print(berlinWallFell.month); // 11
print(berlinWallFell.day); // 9
print(moonLanding.hour); // 20
print(moonLanding.minute); // 18

For convenience and readability, the DateTime class provides a constant for each day and month name - for example, august and friday. You can use these constants to improve code readability:

final berlinWallFell = DateTime.utc(1989, DateTime.november, 9);
print(DateTime.november); // 11
assert(berlinWallFell.month == DateTime.november);
assert(berlinWallFell.weekday == DateTime.thursday);

Day and month values begin at 1, and the week starts on Monday. That is, the constants january and monday are both 1.

Working with UTC and local time

A DateTime object is in the local time zone unless explicitly created in the UTC time zone. Use isUtc to determine whether a DateTime object is based in UTC.

final dDay = DateTime.utc(1944, 6, 6);
print(dDay.isUtc); // true

final dDayLocal = DateTime(1944, 6, 6);
print(dDayLocal.isUtc); // false

Use the methods toLocal and toUtc to get the equivalent date/time value specified in the other time zone.

final localDay = dDay.toLocal(); // e.g. 1944-06-06 02:00:00.000
print(localDay.isUtc); // false

final utcFromLocal = localDay.toUtc(); // 1944-06-06 00:00:00.000Z
print(utcFromLocal.isUtc); // true

Use timeZoneName to get an abbreviated name of the time zone for the DateTime object.

print(dDay.timeZoneName); // UTC
print(localDay.timeZoneName); // e.g. EET

To find the difference between UTC and the time zone of a DateTime object call timeZoneOffset.

print(dDay.timeZoneOffset); // 0:00:00.000000
print(localDay.timeZoneOffset); // e.g. 2:00:00.000000
Comparing DateTime objects

The DateTime class contains methods for comparing DateTimes chronologically, such as isAfter, isBefore, and isAtSameMomentAs.

print(berlinWallFell.isAfter(moonLanding)); // true
print(berlinWallFell.isBefore(moonLanding)); // false
print(dDay.isAtSameMomentAs(localDay)); // true
Using DateTime with Duration

Use the add and subtract methods with a Duration object to create a DateTime object based on another. For example, to find the point in time that is 36 hours after now, you can write:

final now = DateTime.now();
final later = now.add(const Duration(hours: 36));

To find out how much time is between two DateTime objects use difference, which returns a Duration object:

final difference = berlinWallFell.difference(moonLanding);
print(difference.inDays); // 7416

The difference between two dates in different time zones is just the number of nanoseconds between the two points in time. It doesn't take calendar days into account. That means that the difference between two midnights in local time may be less than 24 hours times the number of days between them, if there is a daylight saving change in between. If the difference above is calculated using Australian local time, the difference is 7415 days and 23 hours, which is only 7415 whole days as reported by inDays.

Other resources
  • See Duration to represent a span of time.
  • See Stopwatch to measure timespans.
  • The DateTime class does not provide internationalization. To internationalize your code, use the intl package.

Constructors

DateTimeconstructor
DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])

Constructs a DateTime instance specified in the local time zone.

For example, to create a DateTime object representing the 7th of September 2017, 5:30pm

final dentistAppointment = DateTime(2017, 9, 7, 17, 30);
Example
void main() {
  final local = DateTime(2026, 3, 14, 15, 9, 26);
  print('year ${local.year}, month ${local.month}, day ${local.day}, ${local.hour}:${local.minute}:${local.second}');
  print('isUtc: ${local.isUtc}');
  // Out-of-range values roll over.
  final rolled = DateTime(2026, 13, 1);
  print('month 13 of 2026 -> ${rolled.year}-${rolled.month}-${rolled.day}');
  final feb = DateTime(2024, 2, 30);
  print('Feb 30, 2024 -> ${feb.month}/${feb.day}');
}
Output
year 2026, month 3, day 14, 15:9:26
isUtc: false
month 13 of 2026 -> 2027-1-1
Feb 30, 2024 -> 3/1
DateTime.utcconstructor
DateTime.utc(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])

Constructs a DateTime instance specified in the UTC time zone.

final moonLanding = DateTime.utc(1969, 7, 20, 20, 18, 04);

When dealing with dates or historic events, preferably use UTC DateTimes, since they are unaffected by daylight-saving changes and are unaffected by the local timezone.

Example
void main() {
  final launch = DateTime.utc(2026, 11, 29, 14, 30);
  print('iso:     ${launch.toIso8601String()}');
  print('year ${launch.year}, month ${launch.month}, day ${launch.day}');
  print('weekday: ${launch.weekday} (Sunday is ${DateTime.sunday})');
  print('isUtc:   ${launch.isUtc}');
}
Output
iso:     2026-11-29T14:30:00.000Z
year 2026, month 11, day 29
weekday: 7 (Sunday is 7)
isUtc:   true
DateTime.nowconstructor
DateTime.now()

Constructs a DateTime instance with current date and time in the local time zone.

final now = DateTime.now();
Example
void main() {
  final now = DateTime.now();
  print('isUtc: ${now.isUtc}');
  print('after 2020-01-01: ${now.isAfter(DateTime(2020))}');
  final later = DateTime.now();
  print('clock never goes back between calls: ${!later.isBefore(now)}');
}
Output
isUtc: false
after 2020-01-01: true
clock never goes back between calls: true
DateTime.timestamp()

Constructs a DateTime with the current UTC date and time.

final mark = DateTime.timestamp();
Example
void main() {
  final t = DateTime.timestamp();
  print('isUtc: ${t.isUtc}');
  print('timeZoneName: ${t.timeZoneName}');
  print('after 2020: ${t.isAfter(DateTime.utc(2020))}');
}
Output
isUtc: true
timeZoneName: UTC
after 2020: true
external DateTime.fromMillisecondsSinceEpoch(int millisecondsSinceEpoch, {bool isUtc = false})

Constructs a new DateTime instance with the given millisecondsSinceEpoch.

If isUtc is false then the date is in the local time zone.

The constructed DateTime represents 1970-01-01T00:00:00Z + millisecondsSinceEpoch ms in the given time zone (local or UTC).

final newYearsDay =
    DateTime.fromMillisecondsSinceEpoch(1641031200000, isUtc:true);
print(newYearsDay); // 2022-01-01 10:00:00.000Z
Example
void main() {
  final d = DateTime.fromMillisecondsSinceEpoch(1700000000000, isUtc: true);
  print('date:   $d');
  print('millis: ${d.millisecondsSinceEpoch}');
  print('epoch:  ${DateTime.fromMillisecondsSinceEpoch(0, isUtc: true)}');
}
Output
date:   2023-11-14 22:13:20.000Z
millis: 1700000000000
epoch:  1970-01-01 00:00:00.000Z
external DateTime.fromMicrosecondsSinceEpoch(int microsecondsSinceEpoch, {bool isUtc = false})

Constructs a new DateTime instance with the given microsecondsSinceEpoch.

If isUtc is false, then the date is in the local time zone.

The constructed DateTime represents 1970-01-01T00:00:00Z + microsecondsSinceEpoch us in the given time zone (local or UTC).

final newYearsEve =
    DateTime.fromMicrosecondsSinceEpoch(1640979000000000, isUtc:true);
print(newYearsEve); // 2021-12-31 19:30:00.000Z
Example
void main() {
  final t = DateTime.fromMicrosecondsSinceEpoch(1700000000123456, isUtc: true);
  print('iso:          ${t.toIso8601String()}');
  print('millisecond:  ${t.millisecond}, microsecond: ${t.microsecond}');
  print('round trip:   ${t.microsecondsSinceEpoch}');
  print('epoch:        ${DateTime.fromMicrosecondsSinceEpoch(0, isUtc: true)}');
}
Output
iso:          2023-11-14T22:13:20.123456Z
millisecond:  123, microsecond: 456
round trip:   1700000000123456
epoch:        1970-01-01 00:00:00.000Z

Static

mondayconstant
static const int monday = 1
tuesdayconstant
static const int tuesday = 2
wednesdayconstant
static const int wednesday = 3
thursdayconstant
static const int thursday = 4
fridayconstant
static const int friday = 5
saturdayconstant
static const int saturday = 6
sundayconstant
static const int sunday = 7
daysPerWeekconstant
static const int daysPerWeek = 7
januaryconstant
static const int january = 1
februaryconstant
static const int february = 2
marchconstant
static const int march = 3
aprilconstant
static const int april = 4
mayconstant
static const int may = 5
juneconstant
static const int june = 6
julyconstant
static const int july = 7
augustconstant
static const int august = 8
septemberconstant
static const int september = 9
octoberconstant
static const int october = 10
novemberconstant
static const int november = 11
decemberconstant
static const int december = 12
static const int monthsPerYear = 12
parsestaticmethod
static DateTime parse(String formattedString)

Constructs a new DateTime instance based on formattedString.

Throws a FormatException if the input string cannot be parsed.

The function parses a subset of ISO 8601, which includes the subset accepted by RFC 3339.

The accepted inputs are currently:

  • A date: A signed four-to-six digit year, two digit month and two digit day, optionally separated by - characters. Examples: "19700101", "-0004-12-24", "81030-04-01".
  • An optional time part, separated from the date by either T or a space. The time part is a two digit hour, then optionally a two digit minutes value, then optionally a two digit seconds value, and then optionally a '.' or ',' followed by at least a one digit second fraction. The minutes and seconds may be separated from the previous parts by a ':'. Examples: "12", "12:30:24.124", "12:30:24,124", "123010.50".
  • An optional time-zone offset part, possibly separated from the previous by a space. The time zone is either 'z' or 'Z', or it is a signed two digit hour part and an optional two digit minute part. The sign must be either "+" or "-", and cannot be omitted. The minutes may be separated from the hours by a ':'. Examples: "Z", "-10", "+01:30", "+1130".

This includes the output of both toString and toIso8601String, which will be parsed back into a DateTime object with the same time as the original.

The result is always in either local time or UTC. If a time zone offset other than UTC is specified, the time is converted to the equivalent UTC time.

Examples of accepted strings:

  • "2012-02-27"
  • "2012-02-27 13:27:00"
  • "2012-02-27 13:27:00.123456789z"
  • "2012-02-27 13:27:00,123456789z"
  • "20120227 13:27:00"
  • "20120227T132700"
  • "20120227"
  • "+20120227"
  • "2012-02-27T14Z"
  • "2012-02-27T14+00:00"
  • "-123450101 00:00:00 Z": in the year -12345.
  • "2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"

This method accepts out-of-range component values and interprets them as overflows into the next larger component. For example, "2020-01-42" will be parsed as 2020-02-11, because the last valid date in that month is 2020-01-31, so 42 days is interpreted as 31 days of that month plus 11 days into the next month.

To detect and reject invalid component values, use DateFormat.parseStrict from the intl package.

Example
void main() {
  final a = DateTime.parse('2026-02-28T23:00:00Z');
  final b = DateTime.parse('2026-03-01 08:15:00Z');
  print('a: $a');
  print('b: $b');
  print('hours between: ${b.difference(a).inHours}');
  print('tryParse("soon"): ${DateTime.tryParse('soon')}');
}
Output
a: 2026-02-28 23:00:00.000Z
b: 2026-03-01 08:15:00.000Z
hours between: 9
tryParse("soon"): null
tryParsestaticmethod
static DateTime? tryParse(String formattedString)

Constructs a new DateTime instance based on formattedString.

Works like parse except that this function returns null where parse would throw a FormatException.

Example
void main() {
  print('ISO date:     ${DateTime.tryParse('2026-11-29')}');
  print('with time Z:  ${DateTime.tryParse('2026-11-29T08:30:00Z')}');
  print('offset:       ${DateTime.tryParse('2026-11-29T08:30:00+02:00')}');
  print('garbage:      ${DateTime.tryParse('29 November')}');
}
Output
ISO date:     2026-11-29 00:00:00.000
with time Z:  2026-11-29 08:30:00.000Z
offset:       2026-11-29 06:30:00.000Z
garbage:      null

Properties

isUtcfield
final bool isUtc

True if this DateTime is set to UTC time.

final dDay = DateTime.utc(1944, 6, 6);
print(dDay.isUtc); // true

final local = DateTime(1944, 6, 6);
print(local.isUtc); // false
hashCodegetter
external int get hashCode
external int get millisecondsSinceEpoch

The number of milliseconds since the "Unix epoch" 1970-01-01T00:00:00Z (UTC).

This value is independent of the time zone.

This value is at most 8,640,000,000,000,000ms (100,000,000 days) from the Unix epoch. In other words: millisecondsSinceEpoch.abs <= 8640000000000000.

external int get microsecondsSinceEpoch

The number of microseconds since the "Unix epoch" 1970-01-01T00:00:00Z (UTC).

This value is independent of the time zone.

This value is at most 8,640,000,000,000,000,000us (100,000,000 days) from the Unix epoch. In other words: microsecondsSinceEpoch.abs <= 8640000000000000000.

Note that this value does not always fit into 53 bits (the size of a IEEE double). On the web JavaScript platforms, there may be a rounding error for DateTime values sufficiently far from the epoch. The year range close to the epoch to avoid rounding is approximately 1685..2254.

external String get timeZoneName

The time zone name.

This value is provided by the operating system and may be an abbreviation or a full name.

In the browser or on Unix-like systems commonly returns abbreviations, such as "CET" or "CEST". On Windows returns the full name, for example "Pacific Standard Time".

external Duration get timeZoneOffset

The time zone offset, which is the difference between local time and UTC.

The offset is positive for time zones east of UTC.

Note, that JavaScript, Python and C return the difference between UTC and local time. Java, C# and Ruby return the difference between local time and UTC.

For example, using local time in San Francisco, United States:

final dateUS = DateTime.parse('2021-11-01 20:18:04Z').toLocal();
print(dateUS); // 2021-11-01 13:18:04.000
print(dateUS.timeZoneName); // PDT ( Pacific Daylight Time )
print(dateUS.timeZoneOffset.inHours); // -7
print(dateUS.timeZoneOffset.inMinutes); // -420

For example, using local time in Canberra, Australia:

final dateAus = DateTime.parse('2021-11-01 20:18:04Z').toLocal();
print(dateAus); // 2021-11-02 07:18:04.000
print(dateAus.timeZoneName); // AEDT ( Australian Eastern Daylight Time )
print(dateAus.timeZoneOffset.inHours); // 11
print(dateAus.timeZoneOffset.inMinutes); // 660
yeargetter
external int get year

The year.

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.year); // 1969
monthgetter
external int get month

The month [1..12].

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.month); // 7
assert(moonLanding.month == DateTime.july);
daygetter
external int get day

The day of the month [1..31].

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.day); // 20
hourgetter
external int get hour

The hour of the day, expressed as in a 24-hour clock [0..23].

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.hour); // 20
minutegetter
external int get minute

The minute [0...59].

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.minute); // 18
secondgetter
external int get second

The second [0...59].

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.second); // 4
external int get millisecond

The millisecond [0...999].

final date = DateTime.parse('1970-01-01 05:01:01.234567Z');
print(date.millisecond); // 234
external int get microsecond

The microsecond [0...999].

final date = DateTime.parse('1970-01-01 05:01:01.234567Z');
print(date.microsecond); // 567
weekdaygetter
external int get weekday

The day of the week monday..sunday.

In accordance with ISO 8601 a week starts with Monday, which has the value 1.

final moonLanding = DateTime.parse('1969-07-20 20:18:04Z');
print(moonLanding.weekday); // 7
assert(moonLanding.weekday == DateTime.sunday);
Example
void main() {
  const names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  for (var day = 1; day <= 7; day++) {
    final d = DateTime.utc(2026, 11, day);
    print('2026-11-0$day is a ${names[d.weekday - 1]}');
  }
}
Output
2026-11-01 is a Sun
2026-11-02 is a Mon
2026-11-03 is a Tue
2026-11-04 is a Wed
2026-11-05 is a Thu
2026-11-06 is a Fri
2026-11-07 is a Sat

Methods

isBeforemethod
external bool isBefore(DateTime other)

Whether this DateTime occurs before other.

The comparison is independent of whether the time is in UTC or in the local time zone.

final now = DateTime.now();
final earlier = now.subtract(const Duration(seconds: 5));
print(earlier.isBefore(now)); // true
print(!now.isBefore(now)); // true

// This relation stays the same, even when changing timezones.
print(earlier.isBefore(now.toUtc())); // true
print(earlier.toUtc().isBefore(now)); // true

print(!now.toUtc().isBefore(now)); // true
print(!now.isBefore(now.toUtc())); // true
Example
void main() {
  final a = DateTime.utc(2026, 1, 1), b = DateTime.utc(2026, 6, 1);
  print('a.isBefore(b): ${a.isBefore(b)}');
  print('a.isAfter(b):  ${a.isAfter(b)}');
  print('same moment:   ${a.isAtSameMomentAs(DateTime.parse('2026-01-01T00:00:00Z'))}');
  final dates = [b, a, DateTime.utc(2025, 12, 25)]..sort();
  print('sorted: ${dates.map((d) => d.toIso8601String().substring(0, 10)).toList()}');
}
Output
a.isBefore(b): true
a.isAfter(b):  false
same moment:   true
sorted: [2025-12-25, 2026-01-01, 2026-06-01]
isAftermethod
external bool isAfter(DateTime other)

Whether this DateTime occurs after other.

The comparison is independent of whether the time is in UTC or in the local time zone.

final now = DateTime.now();
final later = now.add(const Duration(seconds: 5));
print(later.isAfter(now)); // true
print(!now.isBefore(now)); // true

// This relation stays the same, even when changing timezones.
print(later.isAfter(now.toUtc())); // true
print(later.toUtc().isAfter(now)); // true

print(!now.toUtc().isAfter(now)); // true
print(!now.isAfter(now.toUtc())); // true
Example
void main() {
  final a = DateTime.utc(2026, 1, 1);
  final b = DateTime.utc(2026, 6, 1);
  print('b.isAfter(a): ${b.isAfter(a)}');
  print('a.isAfter(b): ${a.isAfter(b)}');
  print('a.isAfter(a): ${a.isAfter(a)}');
}
Output
b.isAfter(a): true
a.isAfter(b): false
a.isAfter(a): false
external bool isAtSameMomentAs(DateTime other)

Whether this DateTime occurs at the same moment as other.

The comparison is independent of whether the time is in UTC or in the local time zone.

final now = DateTime.now();
final later = now.add(const Duration(seconds: 5));
print(!later.isAtSameMomentAs(now)); // true
print(now.isAtSameMomentAs(now)); // true

// This relation stays the same, even when changing timezones.
print(!later.isAtSameMomentAs(now.toUtc())); // true
print(!later.toUtc().isAtSameMomentAs(now)); // true

print(now.toUtc().isAtSameMomentAs(now)); // true
print(now.isAtSameMomentAs(now.toUtc())); // true
Example
void main() {
  final utc = DateTime.utc(2026, 11, 29, 12);
  final parsed = DateTime.parse('2026-11-29T14:00:00+02:00');
  print('utc:    $utc');
  print('parsed: $parsed');
  print('isAtSameMomentAs: ${utc.isAtSameMomentAs(parsed)}');
  print('== also true here (both UTC): ${utc == parsed}');
}
Output
utc:    2026-11-29 12:00:00.000Z
parsed: 2026-11-29 12:00:00.000Z
isAtSameMomentAs: true
== also true here (both UTC): true
compareTomethod
external int compareTo(DateTime other)

Compares this DateTime object to other, returning zero if the values are equal.

A compareTo function returns:

  • A negative value if this DateTime isBefore other.
  • 0 if this DateTime isAtSameMomentAs other, and
  • A positive value otherwise (when this DateTime isAfter other).
final now = DateTime.now();
final future = now.add(const Duration(days: 2));
final past = now.subtract(const Duration(days: 2));
final newDate = now.toUtc();

print(now.compareTo(future)); // -1
print(now.compareTo(past)); // 1
print(now.compareTo(newDate)); // 0
Example
void main() {
  final dates = [
    DateTime.utc(2026, 5, 1),
    DateTime.utc(2024, 12, 25),
    DateTime.utc(2026, 1, 15),
  ]..sort((a, b) => a.compareTo(b));
  for (final d in dates) print(d.toIso8601String().substring(0, 10));
  print('compareTo equal: ${dates[0].compareTo(DateTime.utc(2024, 12, 25))}');
}
Output
2024-12-25
2026-01-15
2026-05-01
compareTo equal: 0
toLocalmethod
DateTime toLocal()

Returns this DateTime value in the local time zone.

Returns this DateTime if it is already in the local time zone. Otherwise this method is equivalent to:

DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch,
                                    isUtc: false)
Example
void main() {
  final utc = DateTime.utc(2026, 7, 4, 12);
  final local = utc.toLocal();
  print('utc.isUtc:   ${utc.isUtc}');
  print('local.isUtc: ${local.isUtc}');
  print('same moment: ${local.isAtSameMomentAs(utc)}');
}
Output
utc.isUtc:   true
local.isUtc: false
same moment: true
toUtcmethod
DateTime toUtc()

Returns this DateTime value in the UTC time zone.

Returns this DateTime if it is already in UTC. Otherwise this method is equivalent to:

DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch,
                                    isUtc: true)
Example
void main() {
  final t = DateTime.parse('2026-11-29T09:00:00-05:00');
  final u = t.toUtc();
  print('parsed with -05:00 -> ${u.toIso8601String()}');
  print('hour in UTC: ${u.hour}');
  print('already UTC returns same: ${identical(u, u.toUtc())}');
}
Output
parsed with -05:00 -> 2026-11-29T14:00:00.000Z
hour in UTC: 14
already UTC returns same: true
toStringmethod
String toString()

Returns a human-readable string for this instance.

The returned string is constructed for the time zone of this instance. The toString method provides a simply formatted string. It does not support internationalized strings. Use the intl package at the pub shared packages repo.

The resulting string can be parsed back using parse.

Example
void main() {
  final t = DateTime.utc(2026, 11, 29, 8, 5, 3, 120);
  print('toString():         ${t.toString()}');
  print('toIso8601String():  ${t.toIso8601String()}');
  print('date only:          ${DateTime.utc(2026, 1, 2)}');
}
Output
toString():         2026-11-29 08:05:03.120Z
toIso8601String():  2026-11-29T08:05:03.120Z
date only:          2026-01-02 00:00:00.000Z
String toIso8601String()

Returns an ISO-8601 full-precision extended format representation.

The format is yyyy-MM-ddTHH:mm:ss.mmmuuuZ for UTC time, and yyyy-MM-ddTHH:mm:ss.mmmuuu (no trailing "Z") for local/non-UTC time, where:

  • yyyy is a, possibly negative, four digit representation of the year, if the year is in the range -9999 to 9999, otherwise it is a signed six digit representation of the year.
  • MM is the month in the range 01 to 12,
  • dd is the day of the month in the range 01 to 31,
  • HH are hours in the range 00 to 23,
  • mm are minutes in the range 00 to 59,
  • ss are seconds in the range 00 to 59 (no leap seconds),
  • mmm are milliseconds in the range 000 to 999, and
  • uuu are microseconds in the range 001 to 999. If microsecond equals 0, then this part is omitted.

The resulting string can be parsed back using parse.

final moonLanding = DateTime.utc(1969, 7, 20, 20, 18, 04);
final isoDate = moonLanding.toIso8601String();
print(isoDate); // 1969-07-20T20:18:04.000Z
Example
void main() {
  final d = DateTime.utc(2026, 7, 4, 9, 5, 3, 250);
  print('toIso8601String: ${d.toIso8601String()}');
  print('toString:        $d');
  print('date only:       ${d.toIso8601String().split('T').first}');
}
Output
toIso8601String: 2026-07-04T09:05:03.250Z
toString:        2026-07-04 09:05:03.250Z
date only:       2026-07-04
addmethod
external DateTime add(Duration duration)

Returns a new DateTime instance with duration added to this DateTime.

final today = DateTime.now();
final fiftyDaysFromNow = today.add(const Duration(days: 50));

Notice that the duration being added is actually 50 * 24 * 60 * 60 seconds. If the resulting DateTime has a different daylight saving offset than this, then the result won't have the same time-of-day as this, and may not even hit the calendar date 50 days later.

Be careful when working with dates in local time.

Example
void main() {
  final start = DateTime.utc(2026, 12, 30);
  print('+ 3 days:   ${start.add(const Duration(days: 3))}');
  print('- 12 hours: ${start.subtract(const Duration(hours: 12))}');
  // Months: build a new date (the day overflows into the next month).
  print('next month: ${DateTime.utc(start.year, start.month + 1, start.day)}');
}
Output
+ 3 days:   2027-01-02 00:00:00.000Z
- 12 hours: 2026-12-29 12:00:00.000Z
next month: 2027-01-30 00:00:00.000Z
subtractmethod
external DateTime subtract(Duration duration)

Returns a new DateTime instance with duration subtracted from this DateTime.

final today = DateTime.now();
final fiftyDaysAgo = today.subtract(const Duration(days: 50));

Notice that the duration being subtracted is actually 50 * 24 * 60 * 60 seconds. If the resulting DateTime has a different daylight saving offset than this, then the result won't have the same time-of-day as this, and may not even hit the calendar date 50 days earlier.

Be careful when working with dates in local time.

Example
void main() {
  final t = DateTime.utc(2026, 3, 1);
  print('minus 1 day:      ${t.subtract(const Duration(days: 1))}');
  print('minus 90 minutes: ${t.subtract(const Duration(minutes: 90))}');
  print('leap year 2024:   ${DateTime.utc(2024, 3, 1).subtract(const Duration(days: 1))}');
}
Output
minus 1 day:      2026-02-28 00:00:00.000Z
minus 90 minutes: 2026-02-28 22:30:00.000Z
leap year 2024:   2024-02-29 00:00:00.000Z
external Duration difference(DateTime other)

Returns a Duration with the difference when subtracting other from this DateTime.

The returned Duration will be negative if other occurs after this DateTime.

final berlinWallFell = DateTime.utc(1989, DateTime.november, 9);
final dDay = DateTime.utc(1944, DateTime.june, 6);

final difference = berlinWallFell.difference(dDay);
print(difference.inDays); // 16592

The difference is measured in seconds and fractions of seconds. The difference above counts the number of fractional seconds between midnight at the beginning of those dates. If the dates above had been in local time, not UTC, then the difference between two midnights may not be a multiple of 24 hours due to daylight saving differences.

For example, in Australia, similar code using local time instead of UTC:

final berlinWallFell = DateTime(1989, DateTime.november, 9);
final dDay = DateTime(1944, DateTime.june, 6);
final difference = berlinWallFell.difference(dDay);
print(difference.inDays); // 16591
assert(difference.inDays == 16592);

Will fail because the difference is actually 16591 days and 23 hours, and Duration.inDays only returns the number of whole days.

Example
void main() {
  final born = DateTime.utc(1815, 12, 10);
  final paper = DateTime.utc(1843, 9, 1);
  final d = paper.difference(born);
  print('days:  ${d.inDays}');
  print('years: ${(d.inDays / 365.2425).toStringAsFixed(1)}');
}
Output
days:  10127
years: 27.7

Operators

operator ==operator
external bool operator ==(Object other)

Whether other is a DateTime at the same moment and in the same time zone (UTC or local).

final dDayUtc = DateTime.utc(1944, 6, 6);
final dDayLocal = dDayUtc.toLocal();

// These two dates are at the same moment, but are in different zones.
assert(dDayUtc != dDayLocal);
print(dDayUtc != dDayLocal); // true

See isAtSameMomentAs for a comparison that compares moments in time independently of their zones.

Example
void main() {
  final a = DateTime.utc(2026, 1, 1);
  final b = DateTime.parse('2026-01-01T00:00:00Z');
  print('a == b: ${a == b}');
  final local = DateTime.fromMillisecondsSinceEpoch(a.millisecondsSinceEpoch);
  print('same moment, different zone kind: == ${a == local}, isAtSameMomentAs ${a.isAtSameMomentAs(local)}');
}
Output
a == b: true
same moment, different zone kind: == false, isAtSameMomentAs true
extension DateTimeCopyWith on DateTime

Adds copyWith method to DateTime objects.

Methods

copyWithmethod
DateTime copyWith({int? year, int? month, int? day, int? hour, int? minute, int? second, int? millisecond, int? microsecond, bool? isUtc})

Creates a new DateTime from this one by updating individual properties.

The copyWith method creates a new DateTime object with values for the properties DateTime.year, DateTime.hour, etc, provided by similarly named arguments, or using the existing value of the property if no argument, or null, is provided.

Example:

final now = DateTime.now();
final sameTimeOnMoonLandingDay =
    now.copyWith(year: 1969, month: 07, day: 20);

Like for the DateTime and DateTime.utc constructors, which this operation uses to create the new value, property values are allowed to overflow or underflow the range of the property (like a month outside the 1 to 12 range), which can affect the more significant properties (for example, a month of 13 will result in the month of January of the next year.)

Notice also that if the result is a local-time DateTime, seasonal time-zone adjustments (daylight saving) can cause some combinations of dates, hours and minutes to not exist, or to exist more than once. In the former case, a corresponding time in one of the two adjacent time zones is used instead. In the latter, one of the two options is chosen.

Example
void main() {
  final t = DateTime.utc(2026, 11, 29, 9, 30);
  print('original:       $t');
  print('year 2027:      ${t.copyWith(year: 2027)}');
  print('start of day:   ${t.copyWith(hour: 0, minute: 0)}');
  print('month 2, day 31 -> ${t.copyWith(month: 2, day: 31)}  (rolls over)');
}
Output
original:       2026-11-29 09:30:00.000Z
year 2027:      2027-11-29 09:30:00.000Z
start of day:   2026-11-29 00:00:00.000Z
month 2, day 31 -> 2026-03-03 09:30:00.000Z  (rolls over)
class

double

abstract final class double extends num

A double-precision floating point number.

Representation of Raya doubles containing double specific constants and operations and specializations of operations inherited from num. Raya doubles are 64-bit floating-point numbers as specified in the IEEE 754 standard.

The double type is contagious. Operations on doubles return double results.

It is a compile-time error for a class to attempt to extend or implement double.

See also:

Example
void main() {
  const x = 1.5;
  print('x * 2 = ${x * 2}');
  print('x ~/ 1 = ${x ~/ 1}');
  print('x % 1 = ${x % 1}');
  print('-x = ${-x}');
  print('sign of -0.5 = ${(-0.5).sign}');
}
Output
x * 2 = 3.0
x ~/ 1 = 1
x % 1 = 0.5
-x = -1.5
sign of -0.5 = -1.0

Static

nanconstant
static const double nan = 0.0 / 0.0
Example
void main() {
  print('nan:      ${double.nan}');
  print('infinity: ${double.infinity}');
  print('-inf:     ${double.negativeInfinity}');
  print('[1, nan].contains(nan): ${[1.0, double.nan].contains(double.nan)}');
}
Output
nan:      NaN
infinity: Infinity
-inf:     -Infinity
[1, nan].contains(nan): false
infinityconstant
static const double infinity = 1.0 / 0.0
static const double negativeInfinity = -infinity
minPositiveconstant
static const double minPositive = 5e-324
maxFiniteconstant
static const double maxFinite = 1.7976931348623157e+308
parsestaticmethod
external static double parse(String source)

Parse source as a double literal and return its value.

Accepts an optional sign (+ or -) followed by either the characters "Infinity", the characters "NaN" or a floating-point representation. A floating-point representation is composed of a mantissa and an optional exponent part. The mantissa is either a decimal point (.) followed by a sequence of (decimal) digits, or a sequence of digits optionally followed by a decimal point and optionally more digits. The (optional) exponent part consists of the character "e" or "E", an optional sign, and one or more digits. The source must not be null.

Leading and trailing whitespace is ignored.

Throws a FormatException if the source string is not a valid double literal.

Rather than throwing and immediately catching the FormatException, instead use tryParse to handle a potential parsing error.

Examples of accepted strings:

"3.14"
"  3.14 \xA0"
"0."
".0"
"-1.e3"
"1234E+7"
"+.12e-9"
"-NaN"
Example
void main() {
  print(double.parse('3.25'));
  print(double.parse('-1.5e-3'));
  print(double.parse('Infinity'));
  print(double.tryParse('3,25'));
}
Output
3.25
-0.0015
Infinity
null
tryParsestaticmethod
external static double? tryParse(String source)

Parse source as a double literal and return its value.

Like parse, except that this function returns null for invalid inputs instead of throwing.

Example:

var value = double.tryParse('3.14'); // 3.14
value = double.tryParse('  3.14 \xA0'); // 3.14
value = double.tryParse('0.'); // 0.0
value = double.tryParse('.0'); // 0.0
value = double.tryParse('-1.e3'); // -1000.0
value = double.tryParse('1234E+7'); // 12340000000.0
value = double.tryParse('+.12e-9'); // 1.2e-10
value = double.tryParse('-NaN'); // NaN
value = double.tryParse('0xFF'); // null
value = double.tryParse(double.infinity.toString()); // Infinity
Example
void main() {
  for (final s in ['3.14', '1e-3', '-0.5', 'Infinity', 'NaN', '1,5', '']) {
    print('${"'$s'".padRight(10)} -> ${double.tryParse(s)}');
  }
}
Output
'3.14'     -> 3.14
'1e-3'     -> 0.001
'-0.5'     -> -0.5
'Infinity' -> Infinity
'NaN'      -> NaN
'1,5'      -> null
''         -> null

Properties

signgetter
double get sign

The sign of the double's numerical value.

Returns -1.0 if the value is less than zero, +1.0 if the value is greater than zero, and the value itself if it is -0.0, 0.0 or NaN.

Methods

remaindermethod
double remainder(num other)
Example
void main() {
  print('7.5.remainder(2)  = ${7.5.remainder(2)}');
  print('-7.5.remainder(2) = ${(-7.5).remainder(2)}');
  print('-7.5 % 2          = ${-7.5 % 2}');
}
Output
7.5.remainder(2)  = 1.5
-7.5.remainder(2) = -1.5
-7.5 % 2          = 0.5
absmethod
double abs()
Example
void main() {
  print('(-2.5).abs() = ${(-2.5).abs()}');
  print('(-0.0).abs() = ${(-0.0).abs()}');
  print('distance |3.2 - 7.9| = ${(3.2 - 7.9).abs().toStringAsFixed(1)}');
}
Output
(-2.5).abs() = 2.5
(-0.0).abs() = 0.0
distance |3.2 - 7.9| = 4.7
roundmethod
int round()

Returns the integer closest to this number.

Rounds away from zero when there is no closest integer: (3.5).round == 4 and (-3.5).round == -4.

Throws an UnsupportedError if this number is not finite (NaN or an infinity).

print(3.0.round()); // 3
print(3.25.round()); // 3
print(3.5.round()); // 4
print(3.75.round()); // 4
print((-3.5).round()); // -4
Example
void main() {
  // Halves round away from zero.
  for (final x in [2.5, 3.5, -2.5, 2.49]) print('$x.round() = ${x.round()}');
  try {
    double.infinity.round();
  } on UnsupportedError catch (e) {
    print('infinity.round(): ${e.runtimeType}');
  }
}
Output
2.5.round() = 3
3.5.round() = 4
-2.5.round() = -3
2.49.round() = 2
infinity.round(): UnsupportedError
floormethod
int floor()

Returns the greatest integer no greater than this number.

Rounds the number towards negative infinity.

Throws an UnsupportedError if this number is not finite (NaN or infinity).

print(1.99999.floor()); // 1
print(2.0.floor()); // 2
print(2.99999.floor()); // 2
print((-1.99999).floor()); // -2
print((-2.0).floor()); // -2
print((-2.00001).floor()); // -3
Example
void main() {
  for (final x in [2.9, -2.1, 5.0]) print('$x.floor() = ${x.floor()}');
}
Output
2.9.floor() = 2
-2.1.floor() = -3
5.0.floor() = 5
ceilmethod
int ceil()

Returns the least integer that is not smaller than this number.

Rounds the number towards infinity.

Throws an UnsupportedError if this number is not finite (NaN or an infinity).

print(1.99999.ceil()); // 2
print(2.0.ceil()); // 2
print(2.00001.ceil()); // 3
print((-1.99999).ceil()); // -1
print((-2.0).ceil()); // -2
print((-2.00001).ceil()); // -2
Example
void main() {
  for (final x in [2.1, -2.9, 5.0]) print('$x.ceil() = ${x.ceil()}');
}
Output
2.1.ceil() = 3
-2.9.ceil() = -2
5.0.ceil() = 5
truncatemethod
int truncate()

Returns the integer obtained by discarding any fractional part of this number.

Rounds the number towards zero.

Throws an UnsupportedError if this number is not finite (NaN or an infinity).

print(2.00001.truncate()); // 2
print(1.99999.truncate()); // 1
print(0.5.truncate()); // 0
print((-0.5).truncate()); // 0
print((-1.5).truncate()); // -1
print((-2.5).truncate()); // -2
Example
void main() {
  for (final x in [2.9, -2.9, 1e10 + 0.5]) print('$x.truncate() = ${x.truncate()}');
}
Output
2.9.truncate() = 2
-2.9.truncate() = -2
10000000000.5.truncate() = 10000000000
double roundToDouble()

Returns the integer double value closest to this.

Rounds away from zero when there is no closest integer: (3.5).roundToDouble == 4 and (-3.5).roundToDouble == -4.

If this is already an integer valued double, including -0.0, or it is not a finite value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0, and -0.0 is therefore considered closer to negative numbers than 0.0. This means that for a value d in the range -0.5 < d < 0.0, the result is -0.0.

print(3.0.roundToDouble()); // 3.0
print(3.25.roundToDouble()); // 3.0
print(3.5.roundToDouble()); // 4.0
print(3.75.roundToDouble()); // 4.0
print((-3.5).roundToDouble()); // -4.0
Example
void main() {
  print('2.5.roundToDouble() = ${2.5.roundToDouble()}');
  print('2.7.floorToDouble() = ${2.7.floorToDouble()}');
  print('2.1.ceilToDouble()  = ${2.1.ceilToDouble()}');
  // Round to 2 decimal places, keeping a double.
  print('3.14159 to 2 places  = ${(3.14159 * 100).roundToDouble() / 100}');
}
Output
2.5.roundToDouble() = 3.0
2.7.floorToDouble() = 2.0
2.1.ceilToDouble()  = 3.0
3.14159 to 2 places  = 3.14
double floorToDouble()

Returns the greatest integer double value no greater than this.

If this is already an integer valued double, including -0.0, or it is not a finite value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0. A number d in the range 0.0 < d < 1.0 will return 0.0.

print(1.99999.floorToDouble()); // 1.0
print(2.0.floorToDouble()); // 2.0
print(2.99999.floorToDouble()); // 2.0
print((-1.99999).floorToDouble()); // -2.0
print((-2.0).floorToDouble()); // -2.0
print((-2.00001).floorToDouble()); // -3.0
Example
void main() {
  for (final x in [2.9, -2.1, -0.5]) print('$x.floorToDouble() = ${x.floorToDouble()}');
}
Output
2.9.floorToDouble() = 2.0
-2.1.floorToDouble() = -3.0
-0.5.floorToDouble() = -1.0
double ceilToDouble()

Returns the least integer double value no smaller than this.

If this is already an integer valued double, including -0.0, or it is not a finite value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0. A number d in the range -1.0 < d < 0.0 will return -0.0.

print(1.99999.ceilToDouble()); // 2.0
print(2.0.ceilToDouble()); // 2.0
print(2.00001.ceilToDouble()); // 3.0
print((-1.99999).ceilToDouble()); // -1.0
print((-2.0).ceilToDouble()); // -2.0
print((-2.00001).ceilToDouble()); // -2.0
Example
void main() {
  for (final x in [2.1, -2.9, -0.5]) print('$x.ceilToDouble() = ${x.ceilToDouble()}');
  print('note: -0.5 rounds up to negative zero');
}
Output
2.1.ceilToDouble() = 3.0
-2.9.ceilToDouble() = -2.0
-0.5.ceilToDouble() = -0.0
note: -0.5 rounds up to negative zero
double truncateToDouble()

Returns the integer double value obtained by discarding any fractional digits from this.

If this is already an integer valued double, including -0.0, or it is not a finite value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0. A number d in the range -1.0 < d < 0.0 will return -0.0, and in the range 0.0 < d < 1.0 it will return 0.0.

print(2.5.truncateToDouble()); // 2.0
print(2.00001.truncateToDouble()); // 2.0
print(1.99999.truncateToDouble()); // 1.0
print(0.5.truncateToDouble()); // 0.0
print((-0.5).truncateToDouble()); // -0.0
print((-1.5).truncateToDouble()); // -1.0
print((-2.5).truncateToDouble()); // -2.0
Example
void main() {
  for (final x in [2.9, -2.9, double.infinity]) print('$x.truncateToDouble() = ${x.truncateToDouble()}');
}
Output
2.9.truncateToDouble() = 2.0
-2.9.truncateToDouble() = -2.0
Infinity.truncateToDouble() = Infinity
toStringmethod
String toString()

Provide a representation of this double value.

The representation is a number literal such that the closest double value to the representation's mathematical value is this double.

Returns "NaN" for the Not-a-Number value. Returns "Infinity" and "-Infinity" for positive and negative Infinity. Returns "-0.0" for negative zero.

For all doubles, d, converting to a string and parsing the string back gives the same value again: d == double.parse(d.toString) (except when d is NaN).

Example
void main() {
  print(0.1 + 0.2);
  print(1e21);
  print(100.0);
  print(1 / 3);
  print(double.maxFinite);
  print(double.minPositive);
}
Output
0.30000000000000004
1e+21
100.0
0.3333333333333333
1.7976931348623157e+308
5e-324

Operators

operator +operator
double operator +(num other)
Example
void main() {
  print('0.1 + 0.2 = ${0.1 + 0.2}');
  print('1.5 + 2   = ${1.5 + 2}');
  print('inf + 1   = ${double.infinity + 1}');
}
Output
0.1 + 0.2 = 0.30000000000000004
1.5 + 2   = 3.5
inf + 1   = Infinity
operator -operator
double operator -(num other)
Example
void main() {
  print('5.5 - 2   = ${5.5 - 2}');
  print('1.0 - 0.9 = ${1.0 - 0.9}');
  print('inf - inf = ${double.infinity - double.infinity}');
}
Output
5.5 - 2   = 3.5
1.0 - 0.9 = 0.09999999999999998
inf - inf = NaN
operator *operator
double operator *(num other)
Example
void main() {
  print('2.5 * 4   = ${2.5 * 4}');
  print('0.1 * 3   = ${0.1 * 3}');
  print('1e308 * 10 = ${1e308 * 10}');
}
Output
2.5 * 4   = 10.0
0.1 * 3   = 0.30000000000000004
1e308 * 10 = Infinity
operator %operator
double operator %(num other)
Example
void main() {
  print('5.5 % 2   = ${5.5 % 2}');
  print('-5.5 % 2  = ${-5.5 % 2}  (never negative)');
  // Wrap an angle into [0, 360).
  print('-30 deg -> ${-30.0 % 360}');
}
Output
5.5 % 2   = 1.5
-5.5 % 2  = 0.5  (never negative)
-30 deg -> 330.0
operator /operator
double operator /(num other)
Example
void main() {
  print('7.0 / 2  = ${7.0 / 2}');
  print('1.0 / 0  = ${1.0 / 0}');
  print('-1.0 / 0 = ${-1.0 / 0}');
  print('0.0 / 0  = ${0.0 / 0}');
}
Output
7.0 / 2  = 3.5
1.0 / 0  = Infinity
-1.0 / 0 = -Infinity
0.0 / 0  = NaN
operator ~/operator
int operator ~/(num other)
Example
void main() {
  print('7.5 ~/ 2  = ${7.5 ~/ 2}');
  print('-7.5 ~/ 2 = ${-7.5 ~/ 2}');
  try {
    1.0 ~/ 0;
  } on UnsupportedError catch (e) {
    print('1.0 ~/ 0 throws ${e.runtimeType}');
  }
}
Output
7.5 ~/ 2  = 3
-7.5 ~/ 2 = -3
1.0 ~/ 0 throws UnsupportedError
operator -operator
double operator -()
Example
void main() {
  const x = 2.5;
  print('-x = ${-x}');
  print('-0.0 = ${-0.0}, isNegative ${(-0.0).isNegative}');
  print('-nan is nan: ${(-double.nan).isNaN}');
}
Output
-x = -2.5
-0.0 = -0.0, isNegative true
-nan is nan: true
class Duration implements Comparable<Duration>

A difference between points in time.

A Duration is a signed number of microseconds, which represents an offset from a point in time to another. You can add a Duration to a DateTime, which gives the point in time that is offset by that duration from the original.

Most durations are positive and represent an offset to a later time. A positive duration is useful for representing a delay, a point in the future relative to now (as used by Future.delayed), or as a measure of time that has passed from an earlier time until now (as reported by Stopwatch.elapsed).

A negative duration is the difference from a later time to an earlier, and adding it to a time gives an earlier time. You cannot wait for a negative amount of time using Future.delayed.

Durations are independent of calendars. For example, a duration of 2 days is always 48 hours, even when it is added to a DateTime just when the time zone is about to make a daylight-savings switch. (See DateTime.add).

A duration is a (positive or negative) number of microseconds. Durations are ordered by this number of microseconds when compared using [operator <] or compareTo.

Despite the same name, a Duration object does not implement "Durations" as specified by ISO 8601. In particular, a duration object does not keep track of the individually provided members (such as "days" or "hours"), but only uses these arguments to compute the length of the corresponding time interval.

To create a new Duration object, use this class's single constructor giving the appropriate arguments:

const fastestMarathon = Duration(hours: 2, minutes: 3, seconds: 2);

The created Duration is defined by the number of microseconds that is the sum of all the individual arguments to the constructor.

Properties can access that single number in different ways. The inMicroseconds is the entire value, and, for example, inMinutes gives the number of whole minutes in the total duration, which includes any minutes that were provided as "hours" to the constructor or provided as "seconds" with a value of 60 or above.

const fastestMarathon = Duration(hours: 2, minutes: 0, seconds: 35);
print(fastestMarathon.inDays); // 0
print(fastestMarathon.inHours); // 2
print(fastestMarathon.inMinutes); // 120
print(fastestMarathon.inSeconds); // 7235
print(fastestMarathon.inMilliseconds); // 7235000

If a duration is negative, all the properties derived from the duration are non-positive (negative unless they are zero).

const overDayAgo = Duration(days: -1, hours: -10);
print(overDayAgo.inDays); // -1
print(overDayAgo.inHours); // -34
print(overDayAgo.inMinutes); // -2040

Use one of the properties, such as inDays, to retrieve the integer value of the Duration in the specified time unit. Note that the returned value is rounded towards zero. For example,

const aLongWeekend = Duration(hours: 88);
print(aLongWeekend.inDays); // 3
const aLongWeekendAgo = Duration(hours: -88);
print(aLongWeekendAgo.inDays); // -3

A duration also provides arithmetic and comparison operators, all based on the microsecond offset of the duration. And the class provides a set of constants useful for converting between time units.

const firstHalf = Duration(minutes: 45); // 00:45:00.000000
const secondHalf = Duration(minutes: 45); // 00:45:00.000000
const overTime = Duration(minutes: 30); // 00:30:00.000000
final maxGameTime = firstHalf + secondHalf + overTime;
print(maxGameTime.inMinutes); // 120

// The duration of the firstHalf and secondHalf is the same, returns 0.
var result = firstHalf.compareTo(secondHalf);
print(result); // 0

// Duration of overTime is shorter than firstHalf, returns < 0.
result = overTime.compareTo(firstHalf);
print(result); // < 0

// Duration of secondHalf is longer than overTime, returns > 0.
result = secondHalf.compareTo(overTime);
print(result); // > 0

See also:

Example
void main() {
  const d = Duration(hours: 1, minutes: 30, seconds: 15);
  print('toString:  $d');
  print('inMinutes: ${d.inMinutes}');
  print('inSeconds: ${d.inSeconds}');
  print('doubled:   ${d * 2}');
  print('sum:       ${d + const Duration(minutes: 45)}');
}
Output
toString:  1:30:15.000000
inMinutes: 90
inSeconds: 5415
doubled:   3:00:30.000000
sum:       2:15:15.000000

Constructors

Durationconstructor
const Duration({int days = 0, int hours = 0, int minutes = 0, int seconds = 0, int milliseconds = 0, int microseconds = 0})

Creates a new Duration object whose value is the sum of all individual parts.

Individual parts can be larger than the number of those parts in the next larger unit. For example, hours can be greater than 23. If this happens, the value overflows into the next larger unit, so 26 hours is the same as 2 hours and one more days. Likewise, values can be negative, in which case they underflow and subtract from the next larger unit.

If the total number of microseconds cannot be represented as an integer value, the number of microseconds might overflow and be truncated to a smaller number of bits, or it might lose precision.

All arguments are 0 by default.

const duration = Duration(days: 1, hours: 8, minutes: 56, seconds: 59,
  milliseconds: 30, microseconds: 10);
print(duration); // 32:56:59.030010
Example
void main() {
  const d = Duration(days: 1, hours: 2, minutes: 30, seconds: 15);
  print('d:              $d');
  print('inMinutes:      ${d.inMinutes}');
  print('inSeconds:      ${d.inSeconds}');
  const overflow = Duration(minutes: 125);
  print('125 minutes:    $overflow');
  print('negative parts: ${const Duration(hours: 1, minutes: -15)}');
}
Output
d:              26:30:15.000000
inMinutes:      1590
inSeconds:      95415
125 minutes:    2:05:00.000000
negative parts: 0:45:00.000000

Static

static const int microsecondsPerMillisecond = 1000

The number of microseconds per millisecond.

static const int millisecondsPerSecond = 1000

The number of milliseconds per second.

static const int secondsPerMinute = 60

The number of seconds per minute.

Notice that some minutes of official clock time might differ in length because of leap seconds. The Duration and DateTime classes ignore leap seconds and consider all minutes to have 60 seconds.

static const int minutesPerHour = 60

The number of minutes per hour.

hoursPerDayconstant
static const int hoursPerDay = 24

The number of hours per day.

Notice that some calendar days may differ in length because of time zone changes due to daylight saving. The Duration class is calendar and time zone agnostic and considers all days to have 24 hours.

static const int microsecondsPerSecond = microsecondsPerMillisecond * millisecondsPerSecond

The number of microseconds per second.

static const int microsecondsPerMinute = microsecondsPerSecond * secondsPerMinute

The number of microseconds per minute.

static const int microsecondsPerHour = microsecondsPerMinute * minutesPerHour

The number of microseconds per hour.

static const int microsecondsPerDay = microsecondsPerHour * hoursPerDay

The number of microseconds per day.

static const int millisecondsPerMinute = millisecondsPerSecond * secondsPerMinute

The number of milliseconds per minute.

static const int millisecondsPerHour = millisecondsPerMinute * minutesPerHour

The number of milliseconds per hour.

static const int millisecondsPerDay = millisecondsPerHour * hoursPerDay

The number of milliseconds per day.

static const int secondsPerHour = secondsPerMinute * minutesPerHour

The number of seconds per hour.

static const int secondsPerDay = secondsPerHour * hoursPerDay

The number of seconds per day.

static const int minutesPerDay = minutesPerHour * hoursPerDay

The number of minutes per day.

zeroconstant
static const Duration zero = Duration(seconds: 0)

An empty duration, representing zero time.

Properties

final int inMicroseconds

The time offset of this duration in microseconds.

The value can be greater than 999999. For example, a duration of nine seconds, 123 milliseconds and 678 microseconds has 9123678 microseconds.

const duration = Duration(seconds: 9, milliseconds: 123,
    microseconds: 567);
print(duration.inMicroseconds); // 9123678
inDaysgetter
int get inDays

The number of entire days spanned by this Duration.

For example, a duration of four days and three hours has four entire days.

const duration = Duration(days: 4, hours: 3);
print(duration.inDays); // 4

A negative duration has a negative number of whole days, so that (-duration).inDays = -(duration.inDays).

Example
void main() {
  const d = Duration(milliseconds: 98765432);
  print('days ${d.inDays}, hours ${d.inHours}, minutes ${d.inMinutes}');
  final h = d.inHours, m = d.inMinutes % 60, s = d.inSeconds % 60;
  print('h:mm:ss = $h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}');
}
Output
days 1, hours 27, minutes 1646
h:mm:ss = 27:26:05
inHoursgetter
int get inHours

The number of entire hours spanned by this Duration.

The returned value can be greater than 23. For example, a duration of four days and three hours has 99 entire hours.

const duration = Duration(days: 4, hours: 3);
print(duration.inHours); // 99 = 4 * 24 + 3

A negative duration has a negative number of whole hours, so that (-duration).inHours = -(duration.inHours).

inMinutesgetter
int get inMinutes

The number of whole minutes spanned by this Duration.

The returned value can be greater than 59. For example, a duration of three hours and 12 minutes has 192 minutes.

const duration = Duration(hours: 3, minutes: 12);
print(duration.inMinutes); // 192 = 3 * 60 + 12

A negative duration has a negative number of whole minutes, so that (-duration).inMinutes = -(duration.inMinutes).

inSecondsgetter
int get inSeconds

The number of whole seconds spanned by this Duration.

The returned value can be greater than 59. For example, a duration of three minutes and 12 seconds has 192 seconds.

const duration = Duration(minutes: 3, seconds: 12);
print(duration.inSeconds); // 192 = 3 * 60 + 12

A negative duration has a negative number of whole seconds, so that (-duration).inSeconds = -(duration.inSeconds).

int get inMilliseconds

The number of whole milliseconds spanned by this Duration.

The returned value can be greater than 999. For example, a duration of nine seconds and 123 milliseconds has 9125 milliseconds.

const duration = Duration(seconds: 9, milliseconds: 123);
print(duration.inMilliseconds); // 9123 = 9 * 1000 + 123
hashCodegetter
int get hashCode

The hash code of a duration is the hash code of its inMicroseconds.

bool get isNegative

Whether this Duration is negative.

A negative Duration represents the difference from a later time to an earlier time.

Methods

compareTomethod
int compareTo(Duration other)

Compares this Duration to other.

Returns a negative integer if this Duration's offset is smaller than that of other, a positive integer if this duration's offset is greater than that of other, and 0 if they are equivalent.

A longer positive duration ends after a shorter positive duration, a positive duration ends after a negative duration, and a shorter negative duration ends after a longer negative duration. Equivalent to comparing the inMicroseconds of the duration).

It is always the case that duration1.compareTo(duration2) < 0 if and only if (someDate + duration1).compareTo(someDate + duration2) < 0.

Example
void main() {
  const a = Duration(minutes: 90), b = Duration(hours: 1);
  print('a > b: ${a > b}');
  print('a.compareTo(b): ${a.compareTo(b)}');
  print('b - a: ${b - a}, isNegative ${(b - a).isNegative}, abs ${(b - a).abs()}');
}
Output
a > b: true
a.compareTo(b): 1
b - a: -0:30:00.000000, isNegative true, abs 0:30:00.000000
toStringmethod
String toString()

A string representation of this Duration.

A string with hours, minutes, seconds, and microseconds, in the following format: H:MM:SS.mmmmmm. For example,

var d = const Duration(days: 1, hours: 1, minutes: 33, microseconds: 500);
print(d.toString()); // 25:33:00.000500

d = const Duration(hours: 1, minutes: 10, microseconds: 500);
print(d.toString()); // 1:10:00.000500
Example
void main() {
  print(const Duration(hours: 2, minutes: 5, seconds: 7).toString());
  print(const Duration(milliseconds: 1500).toString());
  print(const Duration(days: 3).toString());
  print(const Duration(microseconds: -42).toString());
}
Output
2:05:07.000000
0:00:01.500000
72:00:00.000000
-0:00:00.000042
absmethod
Duration abs()

A positive Duration with the same absolute length as this Duration.

The returned Duration has the same length as this one, but is always positive where possible.

Example
void main() {
  final a = DateTime.utc(2026, 1, 10), b = DateTime.utc(2026, 1, 3);
  final d = b.difference(a);
  print('b - a:       $d');
  print('abs():       ${d.abs()}');
  print('days apart:  ${d.abs().inDays}');
}
Output
b - a:       -168:00:00.000000
abs():       168:00:00.000000
days apart:  7

Operators

operator +operator
Duration operator +(Duration other)

Adds this Duration and other and returns the sum as a new Duration object.

Example
void main() {
  const laps = [Duration(minutes: 4, seconds: 12), Duration(minutes: 3, seconds: 58), Duration(minutes: 4, seconds: 5)];
  var total = Duration.zero;
  for (final l in laps) total += l;
  print('total: $total');
  print('in seconds: ${total.inSeconds}');
}
Output
total: 0:12:15.000000
in seconds: 735
operator -operator
Duration operator -(Duration other)

The offset of this duration minus the offset of other.

Example
void main() {
  const budget = Duration(hours: 1);
  const used = Duration(minutes: 72);
  final left = budget - used;
  print('left: $left');
  print('over budget: ${left.isNegative}');
}
Output
left: -0:12:00.000000
over budget: true
operator *operator
Duration operator *(num factor)

This Duration scaled by factor.

Note that when factor is a double, and the duration is greater than 53 bits, precision is lost because of double-precision arithmetic.

Example
void main() {
  const lap = Duration(seconds: 90);
  print('lap * 4:   ${lap * 4}');
  print('lap * 1.5: ${lap * 1.5}');
  print('lap * 0.001: ${lap * 0.001}');
}
Output
lap * 4:   0:06:00.000000
lap * 1.5: 0:02:15.000000
lap * 0.001: 0:00:00.090000
operator ~/operator
Duration operator ~/(int quotient)

One-quotientth of this duration.

Divides the offset in microseconds of this duration by quotient rounding towards zero, and provides a new Duration with that as its inMicroseconds.

The quotient must not be 0. If it is negative, the result is equivalent to dividing by the absolute value and then negating.

Example
void main() {
  const total = Duration(minutes: 10);
  print('10 min ~/ 3:  ${total ~/ 3}');
  print('10 min ~/ 7:  ${total ~/ 7}  (microseconds truncated)');
}
Output
10 min ~/ 3:  0:03:20.000000
10 min ~/ 7:  0:01:25.714285  (microseconds truncated)
operator <operator
bool operator <(Duration other)

Whether this duration's offset is smaller than that of other.

A negative duration's offset is always smaller than a positive one's. Equivalent to comparing inMicroseconds

Example
void main() {
  const a = Duration(minutes: 90), b = Duration(hours: 1, minutes: 30), c = Duration(hours: 2);
  print('90min < 1h30: ${a < b}');
  print('90min < 2h:   ${a < c}');
  print('2h < 90min:   ${c < a}');
}
Output
90min < 1h30: false
90min < 2h:   true
2h < 90min:   false
operator >operator
bool operator >(Duration other)

Whether this duration's offset is greater than that of other.

A negative duration's offset is always smaller than a positive one's. Equivalent to comparing inMicroseconds

Example
void main() {
  const a = Duration(minutes: 90), b = Duration(hours: 1, minutes: 30), c = Duration(hours: 2);
  print('90min > 1h30: ${a > b}');
  print('90min > 2h:   ${a > c}');
  print('2h > 90min:   ${c > a}');
}
Output
90min > 1h30: false
90min > 2h:   false
2h > 90min:   true
operator <=operator
bool operator <=(Duration other)

Whether this duration's offset is not greater than that of other.

A negative duration's offset is always smaller than a positive one's. Equivalent to comparing inMicroseconds

Example
void main() {
  const a = Duration(minutes: 90), b = Duration(hours: 1, minutes: 30), c = Duration(hours: 2);
  print('90min <= 1h30: ${a <= b}');
  print('90min <= 2h:   ${a <= c}');
  print('2h <= 90min:   ${c <= a}');
}
Output
90min <= 1h30: true
90min <= 2h:   true
2h <= 90min:   false
operator >=operator
bool operator >=(Duration other)

Whether this duration's offset is not smaller than that of other.

A negative duration's offset is always smaller than a positive one's. Equivalent to comparing inMicroseconds

Example
void main() {
  const a = Duration(minutes: 90), b = Duration(hours: 1, minutes: 30), c = Duration(hours: 2);
  print('90min >= 1h30: ${a >= b}');
  print('90min >= 2h:   ${a >= c}');
  print('2h >= 90min:   ${c >= a}');
}
Output
90min >= 1h30: true
90min >= 2h:   false
2h >= 90min:   true
operator ==operator
bool operator ==(Object other)

Whether this Duration is equivalent to other.

Durations are equivalent if they have the same number of microseconds, as reported by inMicroseconds.

Example
void main() {
  const a = Duration(minutes: 60), b = Duration(hours: 1), c = Duration(seconds: 3601);
  print('60 min == 1 h:     ${a == b}');
  print('60 min == 3601 s:  ${a == c}');
  print('in a set: ${{a, b, c}.length} distinct');
}
Output
60 min == 1 h:     true
60 min == 3601 s:  false
in a set: 2 distinct
operator -operator
Duration operator -()

Creates a new Duration with the opposite sign of this Duration.

The returned Duration has the absolute length as this one, but has the opposite sign (as reported by isNegative) where possible.

Example
void main() {
  const d = Duration(minutes: 5);
  print('-d:          ${-d}');
  print('-(-d):       ${-(-d)}');
  print('isNegative:  ${(-d).isNegative}');
}
Output
-d:          -0:05:00.000000
-(-d):       0:05:00.000000
isNegative:  true
class

Enum

abstract interface class Enum

An enumerated value.

This class is implemented by all types and values introduced using an enum declaration. Non-platform classes cannot extend or mix in this class. Concrete classes cannot implement the interface.

The identifier used to name an enum value is available as a String, via the EnumName.name extension property on the enum value.

Example
enum Planet { mercury, venus, earth }

void main() {
  for (final p in Planet.values) {
    print('${p.index}: ${p.name}');
  }
  print(Planet.values.byName('venus'));
  print(Enum.compareByIndex(Planet.earth, Planet.mercury) > 0);
}
Output
0: mercury
1: venus
2: earth
Planet.venus
true

Static

compareByIndexstaticmethod
static int compareByIndex<T extends Enum>(T value1, T value2)

Compares two enum values by their index.

A generic Comparator function for enum types which orders enum values by their index value, which corresponds to the source order of the enum element declarations in the enum declaration.

Example:

enum Season { spring, summer, autumn, winter }

void main() {
  var relationByIndex =
      Enum.compareByIndex(Season.spring, Season.summer); // < 0
  relationByIndex =
      Enum.compareByIndex(Season.summer, Season.spring); // > 0
  relationByIndex =
      Enum.compareByIndex(Season.spring, Season.winter); // < 0
  relationByIndex =
      Enum.compareByIndex(Season.winter, Season.spring); // > 0
}
Example
enum Size { small, medium, large }

void main() {
  final picks = [Size.large, Size.small, Size.medium, Size.small];
  picks.sort(Enum.compareByIndex);
  print('by declaration order: $picks');
  print('compare(small, large) = ${Enum.compareByIndex(Size.small, Size.large)}');
  print('compare(large, large) = ${Enum.compareByIndex(Size.large, Size.large)}');
}
Output
by declaration order: [Size.small, Size.small, Size.medium, Size.large]
compare(small, large) = -2
compare(large, large) = 0
compareByNamestaticmethod
static int compareByName<T extends Enum>(T value1, T value2)

Compares enum values by name.

The EnumName.name of an enum value is a string representing the source name used to declare that enum value.

This Comparator compares two enum values by comparing their names, and can be used to sort enum values by their names. The comparison uses String.compareTo, and is therefore case sensitive.

Example:

enum Season { spring, summer, autumn, winter }

void main() {
  var seasons = [...Season.values]..sort(Enum.compareByName);
  print(seasons);
  // [Season.autumn, Season.spring, Season.summer, Season.winter]
}
Example
enum Fruit { pear, apple, mango, banana }

void main() {
  final all = [...Fruit.values]..sort(Enum.compareByName);
  print('alphabetical: ${all.map((f) => f.name).toList()}');
  print('compare(pear, apple) = ${Enum.compareByName(Fruit.pear, Fruit.apple).sign}');
}
Output
alphabetical: [apple, banana, mango, pear]
compare(pear, apple) = 1

Properties

indexgetter
int get index

A numeric identifier for the enumerated value.

The values of a single enumeration are numbered consecutively from zero to one less than the number of values. This is also the index of the value in the enumerated type's static values list.

extension

EnumName

extension EnumName on Enum

Access to the name of an enum value.

This method is declared as an extension method instead of an instance method in order to allow enum values to have the name name.

Properties

namegetter
String get name

The name of the enum value.

The name is a string containing the source identifier used to declare the enum value.

For example, given a declaration like:

enum MyEnum {
  value1,
  value2
}

The result of MyEnum.value1.name is the string "value1".

extension

EnumByName

extension EnumByName<T extends Enum> on Iterable<T>

Access enum values by name.

Extensions on a collection of enum values, intended for use on the values list of an enum type, which allows looking up a value by its name.

Since enum classes are expected to be relatively small, lookup of byName is performed by linearly iterating through the values and comparing their name to the provided name. If a more efficient lookup is needed, perhaps because the lookup operation happens very often, consider building a map instead using asNameMap:

static myEnumNameMap = MyEnum.values.asNameMap();

And then use that for lookups.

Methods

byNamemethod
T byName(String name)

Finds the enum value in this list with name name.

Goes through this collection looking for an enum with name name, as reported by EnumName.name. Returns the first value with the given name. Such a value must be found.

Example
enum Color { red, green, blue }

void main() {
  print('byName(green): ${Color.values.byName('green')}');
  final input = ['blue', 'red'];
  print('parsed: ${input.map(Color.values.byName).toList()}');
  try {
    Color.values.byName('purple');
  } on ArgumentError catch (e) {
    print('unknown name -> ArgumentError: ${e.message}');
  }
}
Output
byName(green): Color.green
parsed: [Color.blue, Color.red]
unknown name -> ArgumentError: No enum value with that name
asNameMapmethod
Map<String, T> asNameMap()

Creates a map from the names of enum values to the values.

The collection that this method is called on is expected to have enums with distinct names, like the values list of an enum class. Only one value for each name can occur in the created map, so if two or more enum values have the same name (either being the same value, or being values of different enum type), at most one of them will be represented in the returned map.

Example
enum Planet { mercury, venus, earth }

void main() {
  final byName = Planet.values.asNameMap();
  print('map:   $byName');
  print('earth: ${byName['earth']}');
  print('pluto: ${byName['pluto']}'); // null instead of throwing
}
Output
map:   {mercury: Planet.mercury, venus: Planet.venus, earth: Planet.earth}
earth: Planet.earth
pluto: null
class

Error

class Error

Error objects thrown in the case of a program failure.

An Error object represents a program failure that the programmer should have avoided.

Examples include calling a function with invalid arguments, or even with the wrong number of arguments, or calling it at a time when it is not allowed.

These are not errors that a caller should expect or catch &mdash; if they occur, the program is erroneous, and terminating the program may be the safest response.

When deciding that a function should throw an error, the conditions where it happens should be clearly described, and they should be detectable and predictable, so the programmer using the function can avoid triggering the error.

Such descriptions often uses words like "must" or "must not" to describe the condition, and if you see words like that in a function's documentation, then not satisfying the requirement is very likely to cause an error to be thrown.

Example (from String.contains):

`startIndex` must not be negative or greater than `length`.

In this case, an error will be thrown if startIndex is negative or too large.

If the conditions are not detectable before calling a function, the called function should not throw an Error. It may still throw, but the caller will have to catch the thrown value, effectively making it an alternative result rather than an error. If so, we consider the thrown object an exception rather than an error. The thrown object can choose to implement Exception to document that it represents an exceptional, but not erroneous, occurrence, but being an Exception has no other effect than documentation.

All non-null values can be thrown in Raya. Objects extending the Error class are handled specially: The first time they are thrown, the stack trace at the throw point is recorded and stored in the error object. It can be retrieved using the stackTrace getter. An error object that merely implements Error, and doesn't extend it, will not store the stack trace automatically.

Error objects are also used for system wide failures like stack overflow or an out-of-memory situation, which the user is also not expected to catch or handle.

Since errors are not created to be caught, there is no need for subclasses to distinguish the errors. Instead subclasses have been created in order to make groups of related errors easy to create with consistent error messages. For example, the String.contains method will use a RangeError if its startIndex isn't in the range 0..length, which is easily created by RangeError.range(startIndex, 0, length). Catching specific subclasses of Error is not intended, and shouldn't happen outside of testing your own code.

Constructors

Errorconstructor
Error()
Example
// Subclass Error for programming mistakes callers should not catch.
class NegativeSizeError extends Error {
  final int size;
  NegativeSizeError(this.size);
  @override
  String toString() => 'NegativeSizeError: size $size < 0';
}

List<int> zeros(int n) => n < 0 ? throw NegativeSizeError(n) : List.filled(n, 0);

void main() {
  print('zeros(3): ${zeros(3)}');
  try {
    zeros(-2);
  } on Error catch (e) {
    print('caught: $e');
    print('is Error: ${e is Error}');
  }
}
Output
zeros(3): [0, 0, 0]
caught: NegativeSizeError: size -2 < 0
is Error: true

Static

safeToStringstaticmethod
static String safeToString(Object? object)

Safely convert a value to a String description.

The conversion is guaranteed to not throw, so it won't use the object's toString method except for specific known and trusted types.

Example
void main() {
  print('number: ${Error.safeToString(42)}');
  print('string: ${Error.safeToString('hi "there"')}');
  print('null:   ${Error.safeToString(null)}');
  print('bool:   ${Error.safeToString(true)}');
}
Output
number: 42
string: "hi \"there\""
null:   null
bool:   true
static Never throwWithStackTrace(Object error, StackTrace stackTrace)

Throws error with associated stack trace stackTrace.

Behaves like throw error would if the StackTrace.current was stackTrace at the time of the throw.

Like for a throw, if error extends Error, and it has not been thrown before, its Error.stackTrace property will be set to the stackTrace.

This function does not guarantee to preserve the identity of stackTrace. The StackTrace object that is caught by a try/catch of this error, or which is set as the Error.stackTrace of an error, may not be the same stackTrace object provided as argument, but it will have the same contents according to StackTrace.toString.

Example
void main() {
  // Rethrow an error later, attaching a chosen stack trace.
  final saved = StackTrace.fromString('#0 parseConfig (config.ray:12)');
  try {
    Error.throwWithStackTrace(StateError('config missing'), saved);
  } catch (e, st) {
    print('error: $e');
    print('trace: $st');
  }
}
Output
error: Bad state: config missing
trace: #0 parseConfig (config.ray:12)

Properties

external StackTrace? get stackTrace

The stack trace at the point where this error was first thrown.

Classes which extend Error will automatically have a stack trace filled in the first time they are thrown by a throw expression.

class AssertionError extends Error

Error thrown by the runtime system when an assert statement fails.

Constructors

AssertionErrorconstructor
AssertionError([this.message])

Creates an assertion error with the provided message.

Example
void main() {
  final e = AssertionError('balance must be positive');
  print('message:  ${e.message}');
  print('toString: $e');
  try {
    throw AssertionError('index out of order');
  } on AssertionError catch (e) {
    print('caught:   ${e.message}');
  }
}
Output
message:  balance must be positive
toString: Assertion failed: "balance must be positive"
caught:   index out of order

Properties

messagefield
final Object? message

Message describing the assertion error.

Methods

toStringmethod
String toString()
Example
void main() {
  print('with message:    ${AssertionError('x > 0')}');
  print('without message: ${AssertionError()}');
}
Output
with message:    Assertion failed: "x > 0"
without message: Assertion failed
class TypeError extends Error

Error thrown by the runtime system when a dynamic type error happens.

class ArgumentError extends Error

Error thrown when a function is passed an unacceptable argument.

The method should document restrictions on the arguments it accepts, for example if an integer argument must be non-nullable, a string argument must be non-empty, or a dynamic-typed argument must actually have one of a few accepted types.

The user should be able to predict which arguments will cause an error to be throw, and avoid calling with those.

It's almost always a good idea to provide the unacceptable value as part of the error, to help the user figure out what went wrong, so the ArgumentError.value constructor is the preferred constructor. Use ArgumentError.new only when the value cannot be provided for some reason.

Example
int safeSqrtFloor(int n) {
  if (n < 0) throw ArgumentError.value(n, 'n', 'must not be negative');
  var r = 0;
  while ((r + 1) * (r + 1) <= n) r++;
  return r;
}

void main() {
  print('floor sqrt of 50: ${safeSqrtFloor(50)}');
  try {
    safeSqrtFloor(-4);
  } on ArgumentError catch (e) {
    print('caught: $e');
  }
}
Output
floor sqrt of 50: 7
caught: Invalid argument (n): must not be negative: -4

Constructors

ArgumentErrorconstructor
ArgumentError([this.message, @Since("2.14") this.name])

Creates an error with message describing the problem with an argument.

Existing code may be using message to hold the invalid value. If the message is not a String, it is assumed to be a value instead of a message.

If name is provided, it should be the name of the parameter which received an invalid argument.

Prefer using ArgumentError.value instead to retain and document the invalid value as well.

Example
double sqrtOf(double x) {
  if (x < 0) throw ArgumentError('must be non-negative', 'x');
  return x;
}

void main() {
  try {
    sqrtOf(-1);
  } on ArgumentError catch (e) {
    print('name:    ${e.name}');
    print('message: ${e.message}');
    print('text:    $e');
  }
}
Output
name:    x
message: must be non-negative
text:    Invalid argument(s) (x): must be non-negative
ArgumentError.value(value, [this.name, this.message])

Creates error containing the invalid value.

A message is built by suffixing the message argument with the name argument (if provided) and the value. Example:

Invalid argument (foo): null

The name should match the argument name of the function, but if the function is a method implementing an interface, and its argument names differ from the interface, it might be more useful to use the interface method's argument name (or just rename arguments to match).

Example
void main() {
  final e = ArgumentError.value(-5, 'count', 'must be positive');
  print('invalidValue: ${e.invalidValue}');
  print('name:         ${e.name}');
  print('text:         $e');
}
Output
invalidValue: -5
name:         count
text:         Invalid argument (count): must be positive: -5
ArgumentError.notNull([this.name])

Creates an argument error for a null argument that must not be null.

Example
void main() {
  final e = ArgumentError.notNull('userId');
  print('name:    ${e.name}');
  print('message: ${e.message}');
  print('text:    $e');
}
Output
name:    userId
message: Must not be null
text:    Invalid argument(s) (userId): Must not be null

Static

checkNotNullstaticmethod
static T checkNotNull<T>(T? argument, [String? name])

Throws if argument is null.

If name is supplied, it is used as the parameter name in the error message.

Returns the argument if it is not null.

Example
String greet(String? name) {
  final n = ArgumentError.checkNotNull(name, 'name'); // returns the non-null value
  return 'Hello, $n';
}

void main() {
  print(greet('Ada'));
  try {
    greet(null);
  } on ArgumentError catch (e) {
    print('null -> $e');
  }
}
Output
Hello, Ada
null -> Invalid argument(s) (name): Must not be null

Properties

final dynamic invalidValue

The invalid value.

namefield
final String? name

Name of the invalid argument, if available.

messagefield
final dynamic message

Message describing the problem.

Methods

toStringmethod
String toString()
Example
void main() {
  print(ArgumentError('bad input'));
  print(ArgumentError.value(3, 'mode'));
  print(ArgumentError.value('x', 'unit', 'unknown unit'));
}
Output
Invalid argument(s): bad input
Invalid argument (mode): 3
Invalid argument (unit): unknown unit: "x"
class RangeError extends ArgumentError

Error thrown due to an argument value being outside an accepted range.

Example
void main() {
  final xs = [1, 2, 3];
  try {
    print(xs[5]);
  } on RangeError catch (e) {
    print('caught a RangeError for index ${e.invalidValue}');
  }
  print('checkValueInInterval(2, 0, 3) = ${RangeError.checkValueInInterval(2, 0, 3)}');
  try {
    RangeError.checkValueInInterval(7, 0, 3, 'n');
  } on RangeError catch (e) {
    print('7 is outside 0..3: start ${e.start}, end ${e.end}');
  }
}
Output
caught a RangeError for index 5
checkValueInInterval(2, 0, 3) = 2
7 is outside 0..3: start 0, end 3

Constructors

RangeErrorconstructor
RangeError(message)

Create a new RangeError with the given message.

Example
void main() {
  final e = RangeError('step must be between 1 and 10');
  print('message: ${e.message}');
  print('text:    $e');
  print('is ArgumentError: ${e is ArgumentError}');
}
Output
message: step must be between 1 and 10
text:    RangeError: step must be between 1 and 10
is ArgumentError: true
RangeError.valueconstructor
RangeError.value(num value, [String? name, String? message])

Create a new RangeError with a message for the given value.

An optional name can specify the argument name that has the invalid value, and the message can override the default error description.

Example
void main() {
  final e = RangeError.value(42, 'percent', 'too large');
  print('invalidValue: ${e.invalidValue}');
  print('text:         $e');
}
Output
invalidValue: 42
text:         RangeError (percent): too large: 42
RangeError.rangeconstructor
RangeError.range(num invalidValue, int? minValue, int? maxValue, [String? name, String? message])

Create a new RangeError for a value being outside the valid range.

The allowed range is from minValue to maxValue, inclusive. If minValue or maxValue are null, the range is infinite in that direction.

For a range from 0 to the length of something, end exclusive, use RangeError.index.

An optional name can specify the argument name that has the invalid value, and the message can override the default error description.

Example
int month(int m) {
  if (m < 1 || m > 12) throw RangeError.range(m, 1, 12, 'm');
  return m;
}

void main() {
  print('month(5) = ${month(5)}');
  try {
    month(13);
  } on RangeError catch (e) {
    print('start ${e.start}, end ${e.end}, value ${e.invalidValue}');
    print('text: $e');
  }
}
Output
month(5) = 5
start 1, end 12, value 13
text: RangeError (m): Invalid value: Not in inclusive range 1..12: 13
factory RangeError.index(int index, dynamic indexable, [String? name, String? message, int? length]) = IndexError

Creates a new RangeError stating that index is not a valid index into indexable.

An optional name can specify the argument name that has the invalid value, and the message can override the default error description.

The length is the length of indexable at the time of the error. If length is omitted, it defaults to indexable.length.

Example
void main() {
  final items = ['a', 'b', 'c'];
  final e = RangeError.index(5, items, 'i');
  print('type: ${e is IndexError ? 'IndexError' : 'RangeError'}');
  print('text: $e');
}
Output
type: IndexError
text: RangeError (i): Index out of range: index should be less than 3: 5

Static

static int checkValueInInterval(int value, int minValue, int maxValue, [String? name, String? message])

Check that an integer value lies in a specific interval.

Throws if value is not in the interval. The interval is from minValue to maxValue, both inclusive.

If name or message are provided, they are used as the parameter name and message text of the thrown error.

Returns value if it is in the interval.

Example
void main() {
  print('7 in [0, 10]: ${RangeError.checkValueInInterval(7, 0, 10, 'level')}');
  try {
    RangeError.checkValueInInterval(11, 0, 10, 'level');
  } on RangeError catch (e) {
    print('11 -> $e');
  }
}
Output
7 in [0, 10]: 7
11 -> RangeError (level): Invalid value: Not in inclusive range 0..10: 11
checkValidIndexstaticmethod
static int checkValidIndex(int index, dynamic indexable, [String? name, int? length, String? message])

Check that index is a valid index into an indexable object.

Throws if index is not a valid index into indexable.

An indexable object is one that has a length and an index-operator [] that accepts an index if 0 <= index < length.

If name or message are provided, they are used as the parameter name and message text of the thrown error. If name is omitted, it defaults to "index".

If length is provided, it is used as the length of the indexable object, otherwise the length is found as indexable.length.

Returns index if it is a valid index.

Example
void main() {
  final xs = [10, 20, 30];
  print('index 2 ok: ${RangeError.checkValidIndex(2, xs)}');
  try {
    RangeError.checkValidIndex(3, xs, 'i');
  } on RangeError catch (e) {
    print('index 3 -> $e');
  }
}
Output
index 2 ok: 2
index 3 -> RangeError (i): Index out of range: index should be less than 3: 3
checkValidRangestaticmethod
static int checkValidRange(int start, int? end, int length, [String? startName, String? endName, String? message])

Check that a range represents a slice of an indexable object.

Throws if the range is not valid for an indexable object with the given length. A range is valid for an indexable object with a given length

If 0 <= [start] <= [end] <= [length]. An end of null is considered equivalent to length.

The startName and endName defaults to "start" and "end", respectively.

Returns the actual end value, which is length if end is null, and end otherwise.

Example
void main() {
  // Returns the effective end; a null end means "to the length".
  print('range 1..3 of 5: end ${RangeError.checkValidRange(1, 3, 5)}');
  print('range 2..null of 5: end ${RangeError.checkValidRange(2, null, 5)}');
  try {
    RangeError.checkValidRange(4, 2, 5);
  } on RangeError catch (e) {
    print('4..2 -> $e');
  }
}
Output
range 1..3 of 5: end 3
range 2..null of 5: end 5
4..2 -> RangeError (end): Invalid value: Not in inclusive range 4..5: 2
checkNotNegativestaticmethod
static int checkNotNegative(int value, [String? name, String? message])

Check that an integer value is non-negative.

Throws if the value is negative.

If name or message are provided, they are used as the parameter name and message text of the thrown error. If name is omitted, it defaults to index.

Returns value if it is not negative.

Example
void main() {
  print('count 3: ${RangeError.checkNotNegative(3, 'count')}');
  print('count 0: ${RangeError.checkNotNegative(0, 'count')}');
  try {
    RangeError.checkNotNegative(-1, 'count');
  } on RangeError catch (e) {
    print('count -1 -> $e');
  }
}
Output
count 3: 3
count 0: 0
count -1 -> RangeError (count): Invalid value: Not greater than or equal to 0: -1

Properties

startfield
final num? start

The minimum value that value is allowed to assume.

endfield
final num? end

The maximum value that value is allowed to assume.

num? get invalidValue
class IndexError extends ArgumentError implements RangeError

A specialized RangeError used when an index is not in the range 0..indexable.length-1.

Also contains the indexable object, its length at the time of the error, and the invalid index itself.

Constructors

IndexErrorconstructordeprecated
IndexError(int invalidValue, dynamic indexable, [String? name, String? message, int? length])

Creates a new IndexError stating that invalidValue is not a valid index into indexable.

The length is the length of indexable at the time of the error. If length is omitted, it defaults to indexable.length.

The message is used as part of the string representation of the error.

Example
void main() {
  final letters = ['x', 'y'];
  final e = IndexError(4, letters, 'pos');
  print('index:  ${e.invalidValue}');
  print('length: ${e.length}');
  print('text:   $e');
}
Output
index:  4
length: 2
text:   RangeError (pos): Index out of range: index should be less than 2: 4
IndexError.withLength(int invalidValue, this.length, {this.indexable, String? name, String? message})

Creates a new IndexError stating that invalidValue is not a valid index into indexable.

The length is the length of indexable at the time of the error.

The message is used as part of the string representation of the error.

Example
void main() {
  // Use when you know the length but have no list object at hand.
  final e = IndexError.withLength(9, 4, name: 'slot');
  print('index ${e.invalidValue}, length ${e.length}');
  print('valid range: ${e.start}..${e.end}');
  print('text: $e');
}
Output
index 9, length 4
valid range: 0..3
text: RangeError (slot): Index out of range: index should be less than 4: 9

Static

checkstaticmethod
static int check(int index, int length, {Object? indexable, String? name, String? message})

Check that index is a valid index into an indexable object.

Throws if index is not a valid index.

An indexable object is one that has a length and an index-operator [] that accepts an index if 0 <= index < length.

The length is the length of the indexable object.

The indexable, if provided, is the indexable object.

The name is the parameter name of the index value. Defaults to "index", and can be set to null to omit a name from the error string, if the invalid index was not a parameter.

The message, if provided, is included in the error string.

Returns index if it is a valid index.

Example
void main() {
  print('check(1, 3) = ${IndexError.check(1, 3)}');
  try {
    IndexError.check(3, 3, name: 'row');
  } on IndexError catch (e) {
    print('check(3, 3) -> $e');
  }
}
Output
check(1, 3) = 1
check(3, 3) -> RangeError (row): Index out of range: index should be less than 3: 3

Properties

final Object? indexable

The indexable object that invalidValue was not a valid index into.

Can be, for example, a List or String, which both have index based operations.

lengthfield
final int length

The length of indexable at the time of the error.

int get invalidValue
startgetter
int get start
endgetter
int get end
class NoSuchMethodError extends Error

Error thrown on an invalid function or method invocation.

Thrown when a dynamic function or method call provides an invalid type argument or argument list to the function being called. For non-dynamic invocations, static type checking prevents such invalid arguments.

Also thrown by the default implementation of Object.noSuchMethod.

Constructors

external factory NoSuchMethodError.withInvocation(Object? receiver, Invocation invocation)

Creates a NoSuchMethodError corresponding to a failed method call.

The receiver is the receiver of the method call. That is, the object on which the method was attempted called.

The invocation represents the method call that failed. It should not be null.

Example
void main() {
  final call = Invocation.method(#fly, [10]);
  final e = NoSuchMethodError.withInvocation('penguin', call);
  print('is Error: ${e is Error}');
  print('mentions fly: ${e.toString().contains('fly')}');
}
Output
is Error: true
mentions fly: true

Methods

toStringmethod
external String toString()
Example
void main() {
  dynamic n = 5;
  try {
    n.quack();
  } on NoSuchMethodError catch (e) {
    final text = e.toString();
    print('mentions quack: ${text.contains('quack')}');
    print('first line: ${text.split('\n').first.startsWith('NoSuchMethodError')}');
  }
}
Output
mentions quack: true
first line: true
class UnsupportedError extends Error

The operation was not allowed by the object.

This Error is thrown when an instance cannot implement one of the methods in its signature. For example, it's used by unmodifiable versions of collections, when someone calls a modifying method.

Constructors

UnsupportedErrorconstructor
UnsupportedError(String this.message)
Example
void main() {
  final fixed = List.unmodifiable([1, 2, 3]);
  try {
    fixed.add(4);
  } on UnsupportedError catch (e) {
    print('add to unmodifiable -> UnsupportedError');
  }
  final mine = UnsupportedError('PNG export is not available');
  print('message: ${mine.message}');
}
Output
add to unmodifiable -> UnsupportedError
message: PNG export is not available

Properties

messagefield
final String? message

Methods

toStringmethod
String toString()
Example
void main() {
  print(UnsupportedError('read-only view'));
}
Output
Unsupported operation: read-only view
class UnimplementedError extends Error implements UnsupportedError

Thrown by operations that have not been implemented yet.

This Error is thrown by unfinished code that hasn't yet implemented all the features it needs.

If the class does not intend to implement the feature, it should throw an UnsupportedError instead. This error is only intended for use during development.

Constructors

UnimplementedError([this.message])
Example
abstract class Codec {
  String encode(String s);
  String decode(String s) => throw UnimplementedError('decode is not written yet');
}

class Upper extends Codec {
  @override
  String encode(String s) => s.toUpperCase();
}

void main() {
  final c = Upper();
  print('encode: ${c.encode('raya')}');
  try {
    c.decode('RAYA');
  } on UnimplementedError catch (e) {
    print('decode: ${e.message}');
  }
}
Output
encode: RAYA
decode: decode is not written yet

Properties

messagefield
final String? message

Methods

toStringmethod
String toString()
Example
void main() {
  print(UnimplementedError('todo: caching'));
  print(UnimplementedError());
}
Output
UnimplementedError: todo: caching
UnimplementedError
class StateError extends Error

The operation was not allowed by the current state of the object.

Should be used when this particular object is currently in a state which doesn't support the requested operation, but other similar objects might, or the object itself can later change its state to one which supports the operation.

Example: Asking for list.first on a currently empty list. If the operation is never supported by this object or class, consider using UnsupportedError instead.

This is a generic error used for a variety of different erroneous actions. The message should be descriptive.

Example
void main() {
  try {
    <int>[].first;
  } on StateError catch (e) {
    print('StateError: ${e.message}');
  }
}
Output
StateError: No element

Constructors

StateErrorconstructor
StateError(this.message)
Example
class Door {
  bool open = false;
  void close() {
    if (!open) throw StateError('door is already closed');
    open = false;
  }
}

void main() {
  try {
    Door().close();
  } on StateError catch (e) {
    print('message: ${e.message}');
  }
  try {
    <int>[].first;
  } on StateError catch (e) {
    print('empty list first: ${e.message}');
  }
}
Output
message: door is already closed
empty list first: No element

Properties

messagefield
final String message

Methods

toStringmethod
String toString()
Example
void main() {
  print(StateError('not connected'));
}
Output
Bad state: not connected
class ConcurrentModificationError extends Error

Error occurring when a collection is modified during iteration.

Some modifications may be allowed for some collections, so each collection (Iterable or similar collection of values) should declare which operations are allowed during an iteration.

Constructors

ConcurrentModificationError([this.modifiedObject])
Example
void main() {
  final xs = [1, 2, 3];
  try {
    for (final x in xs) {
      if (x == 2) xs.add(99); // changing a list while iterating it
    }
  } on ConcurrentModificationError catch (e) {
    print('caught ConcurrentModificationError');
    print('modified object: ${e.modifiedObject}');
  }
  print('custom: ${ConcurrentModificationError(xs).modifiedObject}');
}
Output
caught ConcurrentModificationError
modified object: [1, 2, 3, 99]
custom: [1, 2, 3, 99]

Properties

final Object? modifiedObject

The object that was modified in an incompatible way.

Methods

toStringmethod
String toString()
Example
void main() {
  // The text names the modified object (strings and numbers print as values).
  print(ConcurrentModificationError('playlist'));
  print(ConcurrentModificationError());
}
Output
Concurrent modification during iteration: "playlist".
Concurrent modification during iteration.
final class OutOfMemoryError implements Error

Error that the platform can use in case of memory shortage.

Constructors

OutOfMemoryErrorconstructor
const OutOfMemoryError()
Example
void main() {
  // Normally thrown by the runtime; constructing one is only for tests.
  const e = OutOfMemoryError();
  print('is Error: ${e is Error}');
  print('stackTrace: ${e.stackTrace}');
}
Output
is Error: true
stackTrace: null

Properties

StackTrace? get stackTrace

Methods

toStringmethod
String toString()
Example
void main() {
  print(const OutOfMemoryError());
}
Output
Out of Memory
final class StackOverflowError implements Error

Error that the platform can use in case of stack overflow.

Constructors

const StackOverflowError()
Example
void main() {
  // Normally thrown by the runtime on runaway recursion.
  const e = StackOverflowError();
  print('is Error: ${e is Error}');
  print('stackTrace: ${e.stackTrace}');
}
Output
is Error: true
stackTrace: null

Properties

StackTrace? get stackTrace

Methods

toStringmethod
String toString()
Example
void main() {
  print(const StackOverflowError());
}
Output
Stack Overflow
abstract interface class Exception

A marker interface implemented by all core library exceptions.

An Exception is intended to convey information to the user about a failure, so that the error can be addressed programmatically. It is intended to be caught, and it should contain useful data fields.

Creating instances of Exception directly with Exception("message") is discouraged in library code since it doesn't give users a precise type they can catch. It may be reasonable to use instances of this class in tests or during development.

For failures that are not intended to be caught, use Error and its subclasses.

Constructors

Exceptionfactory
factory Exception([message])
Example
int parsePort(String s) {
  final p = int.tryParse(s);
  if (p == null || p < 1 || p > 65535) throw Exception('bad port: $s');
  return p;
}

void main() {
  print('port: ${parsePort('8080')}');
  try {
    parsePort('99999');
  } on Exception catch (e) {
    print('caught: $e');
  }
}
Output
port: 8080
caught: Exception: bad port: 99999
class FormatException implements Exception

Exception thrown when a string or some other data does not have an expected format and cannot be parsed or processed.

Example
void main() {
  for (final s in ['42', 'forty-two']) {
    try {
      print('parsed ${int.parse(s)}');
    } on FormatException catch (e) {
      print('FormatException: ${e.message} (source "${e.source}")');
    }
  }
}
Output
parsed 42
FormatException: Invalid radix-10 number (source "forty-two")

Constructors

FormatExceptionconstructor
const FormatException([this.message = "", this.source, this.offset])

Creates a new FormatException with an optional error message.

Optionally also supply the actual source with the incorrect format, and the offset in the format where a problem was detected.

Example
void main() {
  const src = '12;3x;7';
  final e = FormatException('not a digit', src, 4);
  print('message: ${e.message}');
  print('source:  ${e.source}');
  print('offset:  ${e.offset}');
}
Output
message: not a digit
source:  12;3x;7
offset:  4

Properties

messagefield
final String message

A message describing the format error.

sourcefield
final dynamic source

The actual source input which caused the error.

This is usually a String, but can be other types too. If it is a string, parts of it may be included in the toString message.

The source is null if omitted or unknown.

offsetfield
final int? offset

The offset in source where the error was detected.

A zero-based offset into the source that marks the format error causing this exception to be created. If source is a string, this should be a string index in the range 0 <= offset <= source.length.

If input is a string, the toString method may represent this offset as a line and character position. The offset should be inside the string, or at the end of the string.

May be omitted. If present, source should also be present if possible.

Methods

toStringmethod
String toString()

Returns a description of the format exception.

The description always contains the message.

If source is present and is a string, the description will contain (at least a part of) the source. If offset is also provided, the part of the source included will contain that offset, and the offset will be marked.

If the source is a string and it contains a line break before offset, only the line containing offset will be included, and its line number will also be part of the description. Line and character offsets are 1-based.

Example
void main() {
  // With a source and offset the text points at the bad character.
  print(FormatException('unexpected character', 'a + * b', 4));
  print('---');
  print(const FormatException('empty input'));
}
Output
FormatException: unexpected character (at character 5)
a + * b
    ^

---
FormatException: empty input
class IntegerDivisionByZeroException implements Exception, UnsupportedError

Constructors

const IntegerDivisionByZeroException()
Example
void main() {
  try {
    print(7 ~/ 0);
  } catch (e) {
    print('7 ~/ 0 throws instead of returning a number');
  }
  const e = IntegerDivisionByZeroException();
  print('is Exception: ${e is Exception}');
}
Output
7 ~/ 0 throws instead of returning a number
is Exception: true

Properties

messagegetter
String? get message
StackTrace? get stackTrace

Methods

toStringmethod
String toString()
Example
void main() {
  print(const IntegerDivisionByZeroException());
}
Output
IntegerDivisionByZeroException
abstract final class Function

A function value.

The Function class is a supertype of all function types, and contains no values itself. All objects that implement Function have a function type as their runtime type.

The Function type does not carry information about the parameter signatures or return type of a function. To express a more precise function type, use the function type syntax, which is the Function keyword followed by a parameter list, or a type argument list and a parameter list, and which can also have an optional return type.

The function type syntax mirrors the definition of a function, with the function name replaced by the word "Function".

Example:

String numberToString(int n) => "$n";
String Function(int n) fun = numberToString; // Type annotation
assert(fun is String Function(int)); // Type check.
List<String Function(int)> functions = [fun]; // Type argument.

The type String Function(int) is the type of a function that takes one positional int argument and returns a String.

Example with generic function type:

T id<T>(T value) => value;
X Function<X>(X) anotherId = id; // Parameter name may be omitted.
int Function(int) intId = id<int>;

A function type can be used anywhere a type is allowed, and is often used for functions taking other functions, "callbacks", as arguments.

void doSomething(String Function(int) callback) {
  print(callback(1));
}

A function type has all the members declared by Object, since function types are subtypes of Object.

A function type also has a call method with a signature that has the same function type as the function type itself. Calling the call method behaves just as calling the function. This is mainly used to conditionally call a nullable function value.

String Function(int) fun = (n) => "$n";
String Function(int) fun2 = fun.call; // Valid.
print(fun2.call(1)); // Prints "1".

String Function(int)? maybeFun = Random().nextBool() ? fun : null;
print(maybeFun?.call(1)); // Prints "1" or "null".

The Function type has a number of special features which are not visible in this class declaration.

The Function type itself allows any function to be assigned to it, since it is a supertype of any function type, but does not say how the function can be called.

However, a value with the static type Function can still be called like a function.

Function f = (int x) => "$x";
print(f(1)); // Prints "1".

f("not", "one", "int"); // Throws! No static warning.

Such an invocation is a dynamic invocation, precisely as if the function value had been statically typed as dynamic, and is precisely as unsafe as any other dynamic invocation. Checks will be performed at run-time to ensure that the argument list matches the function's parameters, and if not the call will fail with an Error. There is no static type checking for such a call, any argument list is accepted and checked at runtime.

Like every function type has a call method with its own function type, the Function type has a special call member which acts as if it is a method with a function type of Function (which is not a method signature which can be expressed in normal Raya code).

Function fun = (int x) => "$x";

var fun2 = fun.call; // Inferred type of `fun2` is `Function`.

print(fun2.call(1)); // Prints "1";

Function? maybeFun = Random().nextBool() ? fun : null;
print(maybeFun?.call(1)); // Prints "1" or "null".

Static

applystaticmethod
external static apply(Function function, List<dynamic>? positionalArguments, [Map<Symbol, dynamic>? namedArguments])

Dynamically call function with the specified arguments.

Acts the same as dynamically calling function with positional arguments corresponding to the elements of positionalArguments and named arguments corresponding to the elements of namedArguments.

This includes giving the same errors if function expects different parameters.

Example:

void printWineDetails(int vintage, {String? country, String? name}) {
  print('Name: $name, Country: $country, Vintage: $vintage');
}

void main() {
  Function.apply(
      printWineDetails, [2018], {#country: 'USA', #name: 'Dominus Estate'});
}

// Output of the example is:
// Name: Dominus Estate, Country: USA, Vintage: 2018

If positionalArguments is null, it's considered an empty list. If namedArguments is omitted or null, it is considered an empty map.

void helloWorld() {
  print('Hello world!');
}

void main() {
  Function.apply(helloWorld, null);
}
// Output of the example is:
// Hello world!
Example
int add3(int a, int b, int c) => a + b + c;
String greet(String name, {String greeting = 'Hello'}) => '$greeting, $name';

void main() {
  print(Function.apply(add3, [1, 2, 3]));
  print(Function.apply(greet, ['Ada'], {#greeting: 'Hi'}));
}
Output
6
Hi, Ada

Properties

hashCodegetter
int get hashCode

A hash code value that is compatible with operator==.

Operators

operator ==operator
bool operator ==(Object other)

Test whether another object is equal to this function.

Function objects are only equal to other function objects (an object satisfying object is Function), and never to non-function objects.

Some function objects are considered equal by == because they are recognized as representing the "same function":

  • It is the same object. Static and top-level functions are compile time constants when used as values, so referring to the same function twice always yields the same object, as does referring to a local function declaration twice in the same scope where it was declared.
void main() {
  assert(identical(print, print));
  int add(int x, int y) => x + y;
  assert(identical(add, add));
}
  • The functions are same member method extracted from the same object. Repeatedly extracting ("tearing off") the same instance method of the same object to a function value gives equal, but not necessarily identical, function values.
var o = Object();
assert(o.toString == o.toString);
  • Instantiations of equal generic functions with the same types yields equal results.
T id<T>(T value) => value;
assert(id<int> == id<int>);

(If the function is a constant and the type arguments are known at compile-time, the results may also be identical.)

Different evaluations of function literals are not guaranteed or required to give rise to identical or equal function objects. For example:

var functions = <Function>[];
for (var i = 0; i < 2; i++) {
  functions.add((x) => x);
}
print(identical(functions[0], functions[1])); // 'true' or 'false'
print(functions[0] == functions[1]); // 'true' or 'false'

If the distinct values are identical, they are always equal.

If the function values are equal, they are guaranteed to behave indistinguishably for all arguments.

If two functions values behave differently, they are never equal or identical.

The reason to not require a specific equality or identity of the values of a function expression is to allow compiler optimizations. If a function expression does not depend on surrounding variables, an implementation can safely be shared between multiple evaluations. For example:

List<int> ints = [6, 2, 5, 1, 4, 3];
ints.sort((x, y) => x - y);
print(ints);

A compiler can convert the closure (x, y) => x - y into a top-level function.

Example
int twice(int x) => 2 * x;

class Counter {
  int n = 0;
  void bump() => n++;
}

void main() {
  print('same top-level function: ${twice == twice}');
  final c = Counter();
  // Tear-offs of the same method on the same object are equal.
  print('c.bump == c.bump:        ${c.bump == c.bump}');
  print('different objects:       ${c.bump == Counter().bump}');
  int add(int x) => x + 1;
  print('closure equals itself:   ${add == add}');
}
Output
same top-level function: true
c.bump == c.bump:        true
different objects:       false
closure equals itself:   true
class

int

abstract final class int extends num

An integer number.

The default implementation of int is 64-bit two's complement integers with operations that wrap to that range on overflow.

Note: When compiling to JavaScript, integers are restricted to values that can be represented exactly by double-precision floating point values. The available integer values include all integers between -2^53 and 2^53, and some integers with larger magnitude. That includes some integers larger than 2^63. The behavior of the operators and methods in the int class therefore sometimes differs between the Raya VM and Raya code compiled to JavaScript. For example, the bitwise operators truncate their operands to 32-bit integers when compiled to JavaScript.

Classes cannot extend, implement, or mix in int.

See also:

Example
void main() {
  const big = 9007199254740993; // 2^53 + 1 is exact as a 64-bit int
  print('2^53 + 1 = $big');
  print('max 64-bit = ${0x7FFFFFFFFFFFFFFF}');
  print('7 ~/ 2 = ${7 ~/ 2}, 7 % 2 = ${7 % 2}, 7 / 2 = ${7 / 2}');
  print('-7 ~/ 2 = ${-7 ~/ 2}, -7 % 2 = ${-7 % 2}');
}
Output
2^53 + 1 = 9007199254740993
max 64-bit = 9223372036854775807
7 ~/ 2 = 3, 7 % 2 = 1, 7 / 2 = 3.5
-7 ~/ 2 = -3, -7 % 2 = 1

Constructors

external const factory int.fromEnvironment(String name, {int defaultValue = 0})

Integer value for name in the compilation configuration environment.

The compilation configuration environment is provided by the surrounding tools which are compiling or running the Raya 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 looks up the string value for name, then attempts to parse it as an integer, using the same syntax rules as int.parse/int.tryParse. That is, it accepts decimal numerals and hexadecimal numerals with a 0x prefix, and it accepts a leading minus sign. If there is no value associated with name in the compilation configuration environment, or if the associated string value cannot be parsed as an integer, the value of the constructor invocation is the defaultValue integer, which defaults to the integer zero.

The result is effectively the same as that of:

int.tryParse(const String.fromEnvironment(name, defaultValue: ""))
    ?? defaultValue

Except that the constructor invocation can be a constant value.

Example:

const defaultPort = int.fromEnvironment("defaultPort", defaultValue: 80);

In order to check whether a value is there at all, use bool.hasEnvironment. Example:

const int? maybeDeclared = bool.hasEnvironment("defaultPort")
    ? int.fromEnvironment("defaultPort")
    : null;

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 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.

Example
void main() {
  // Set with: raya run -DworkerCount=8 main.ray
  const workers = int.fromEnvironment('workerCount', defaultValue: 4);
  const retries = int.fromEnvironment('retries');
  print('workerCount (default 4): $workers');
  print('retries (default 0):     $retries');
}
Output
workerCount (default 4): 4
retries (default 0):     0

Static

parsestaticmethod
external static int parse(String source, {int? radix})

Parse source as a, possibly signed, integer literal and return its value.

The source must be a non-empty sequence of base-radix digits, optionally prefixed with a minus or plus sign ('-' or '+').

The radix must be in the range 2..36. The digits used are first the decimal digits 0..9, and then the letters 'a'..'z' with values 10 through 35. Also accepts upper-case letters with the same values as the lower-case ones.

If no radix is given then it defaults to 10. In this case, the source digits may also start with 0x, in which case the number is interpreted as a hexadecimal integer literal, When int is implemented by 64-bit signed integers, hexadecimal integer literals may represent values larger than 2<sup>63</sup>, in which case the value is parsed as if it is an unsigned number, and the resulting value is the corresponding signed integer value.

For any int n and valid radix r, it is guaranteed that n == int.parse(n.toRadixString(r), radix: r).

If the source string does not contain a valid integer literal, optionally prefixed by a sign, a FormatException is thrown.

Rather than throwing and immediately catching the FormatException, instead use tryParse to handle a potential parsing error.

Example:

var value = int.tryParse(text);
if (value == null) {
  // handle the problem
  // ...
}
Example
void main() {
  print('decimal: ${int.parse('42')}');
  print('hex:     ${int.parse('ff', radix: 16)}');
  print('binary:  ${int.parse('101010', radix: 2)}');
  print('signed:  ${int.parse('-17')}');
  try {
    int.parse('4.2');
  } on FormatException catch (e) {
    print('error:   ${e.message}');
  }
}
Output
decimal: 42
hex:     255
binary:  42
signed:  -17
error:   Invalid radix-10 number
tryParsestaticmethod
external static int? tryParse(String source, {int? radix})

Parse source as a, possibly signed, integer literal.

Like parse except that this function returns null where a similar call to parse would throw a FormatException.

Example:

print(int.tryParse('2021')); // 2021
print(int.tryParse('1f')); // null
// From binary (base 2) value.
print(int.tryParse('1100', radix: 2)); // 12
print(int.tryParse('00011111', radix: 2)); // 31
print(int.tryParse('011111100101', radix: 2)); // 2021
// From octal (base 8) value.
print(int.tryParse('14', radix: 8)); // 12
print(int.tryParse('37', radix: 8)); // 31
print(int.tryParse('3745', radix: 8)); // 2021
// From hexadecimal (base 16) value.
print(int.tryParse('c', radix: 16)); // 12
print(int.tryParse('1f', radix: 16)); // 31
print(int.tryParse('7e5', radix: 16)); // 2021
// From base 35 value.
print(int.tryParse('y1', radix: 35)); // 1191 == 34 * 35 + 1
print(int.tryParse('z1', radix: 35)); // null
// From base 36 value.
print(int.tryParse('y1', radix: 36)); // 1225 == 34 * 36 + 1
print(int.tryParse('z1', radix: 36)); // 1261 == 35 * 36 + 1
Example
void main() {
  for (final s in ['12', ' 7 ', 'x9', '0x1F', '']) {
    print('"$s" -> ${int.tryParse(s)}');
  }
  final n = int.tryParse('abc') ?? 0;
  print('with a default: $n');
}
Output
"12" -> 12
" 7 " -> 7
"x9" -> null
"0x1F" -> 31
"" -> null
with a default: 0

Properties

isEvengetter
bool get isEven

Returns true if and only if this integer is even.

Example
void main() {
  final nums = [1, 2, 3, 4, 5, 6];
  print('even: ${nums.where((n) => n.isEven).toList()}');
  print('odd:  ${nums.where((n) => n.isOdd).toList()}');
}
Output
even: [2, 4, 6]
odd:  [1, 3, 5]
isOddgetter
bool get isOdd

Returns true if and only if this integer is odd.

bitLengthgetter
int get bitLength

Returns the minimum number of bits required to store this integer.

The number of bits excludes the sign bit, which gives the natural length for non-negative (unsigned) values. Negative values are complemented to return the bit position of the first bit that differs from the sign bit.

To find the number of bits needed to store the value as a signed value, add one, i.e. use x.bitLength + 1.

x.bitLength == (-x-1).bitLength;

3.bitLength == 2;     // 00000011
2.bitLength == 2;     // 00000010
1.bitLength == 1;     // 00000001
0.bitLength == 0;     // 00000000
(-1).bitLength == 0;  // 11111111
(-2).bitLength == 1;  // 11111110
(-3).bitLength == 2;  // 11111101
(-4).bitLength == 2;  // 11111100
Example
void main() {
  for (final n in [0, 1, 255, 256, 1 << 40, -1, -256]) {
    print('$n: bitLength ${n.bitLength}');
  }
}
Output
0: bitLength 0
1: bitLength 1
255: bitLength 8
256: bitLength 9
1099511627776: bitLength 41
-1: bitLength 0
-256: bitLength 8
int get trailingZeroBitCount

The number of trailing (least significant) zero bits in the binary representation of this integer.

On JavaScript platforms, only the least significant 32 bits are used. On native platforms, the 64-bit signed integer is used directly.

The trailing zero-bit count is the position of the least significant 1-bit in the binary representation of the integer. If the integer is zero, the value is the size of integer that the platform uses for bit operations (64-bit on native, 32-bit on the web).

1.trailingZeroBitCount;  // 0
2.trailingZeroBitCount;  // 1
8.trailingZeroBitCount;  // 3
0.trailingZeroBitCount;  // 64 on native, 32 on the web
int get oneBitCount

The number of 1 bits in the binary representation of this integer.

On JavaScript platforms, only the least significant 32 bits are used. On native platforms, the 64-bit signed integer is used directly.

The one-bit count is the number of 1 digits in the binary representation of that integer. A negative integer has one-digits up to the size of integer that the platform uses for bit operations (64-bit on native, 32-bit on the web). The value of n.oneBitCount + (~n).oneBitCount is always the size the platform uses for bit operations (on the web, at least if the value starts out as a 32-bit integer).

0.oneBitCount;    // 0
1.oneBitCount;    // 1
7.oneBitCount;    // 3
(-1).oneBitCount; // 64 on native, 32 on the web
Example
void main() {
  for (final n in [0, 7, 255, 1024]) {
    print('$n: ones ${n.oneBitCount}, trailing zeros ${n.trailingZeroBitCount}');
  }
}
Output
0: ones 0, trailing zeros 64
7: ones 3, trailing zeros 0
255: ones 8, trailing zeros 0
1024: ones 1, trailing zeros 10
signgetter
int get sign

Returns the sign of this integer.

Returns 0 for zero, -1 for values less than zero and +1 for values greater than zero.

Methods

modPowmethod
int modPow(int exponent, int modulus)

Returns this integer to the power of exponent modulo modulus.

The exponent must be non-negative and modulus must be positive.

Example
void main() {
  print('3^200 mod 13 = ${3.modPow(200, 13)}');
  print('2^10 mod 1000 = ${2.modPow(10, 1000)}');
  // Fermat check: a^(p-1) = 1 (mod p) for a prime p.
  const p = 101;
  print('5^(p-1) mod p = ${5.modPow(p - 1, p)}');
}
Output
3^200 mod 13 = 9
2^10 mod 1000 = 24
5^(p-1) mod p = 1
int modInverse(int modulus)

Returns the modular multiplicative inverse of this integer modulo modulus.

The modulus must be positive.

It is an error if no modular inverse exists.

Example
void main() {
  final inv = 3.modInverse(11);
  print('3^-1 mod 11 = $inv');
  print('check: 3 * $inv mod 11 = ${3 * inv % 11}');
}
Output
3^-1 mod 11 = 4
check: 3 * 4 mod 11 = 1
gcdmethod
int gcd(int other)

Returns the greatest common divisor of this integer and other.

If either number is non-zero, the result is the numerically greatest integer dividing both this and other.

The greatest common divisor is independent of the order, so x.gcd(y) is always the same as y.gcd(x).

For any integer x, x.gcd(x) is x.abs.

If both this and other is zero, the result is also zero.

Example:

print(4.gcd(2)); // 2
print(8.gcd(4)); // 4
print(10.gcd(12)); // 2
print(10.gcd(0)); // 10
print((-2).gcd(-3)); // 1
Example
void main() {
  print('gcd(12, 18) = ${12.gcd(18)}');
  print('gcd(17, 5)  = ${17.gcd(5)}');
  print('gcd(-8, 12) = ${(-8).gcd(12)}');
  // Least common multiple from the gcd.
  const a = 4, b = 6;
  print('lcm(4, 6)   = ${a * b ~/ a.gcd(b)}');
}
Output
gcd(12, 18) = 6
gcd(17, 5)  = 1
gcd(-8, 12) = 4
lcm(4, 6)   = 12
int toUnsigned(int width)

Returns the least significant width bits of this integer as a non-negative number (i.e. unsigned representation). The returned value has zeros in all bit positions higher than width.

(-1).toUnsigned(5) == 31   // 11111111  ->  00011111

This operation can be used to simulate arithmetic from low level languages. For example, to increment an 8 bit quantity:

q = (q + 1).toUnsigned(8);

q will count from 0 up to 255 and then wrap around to 0.

If the input fits in width bits without truncation, the result is the same as the input. The minimum width needed to avoid truncation of x is given by x.bitLength, i.e.

x == x.toUnsigned(x.bitLength);
Example
void main() {
  print('-1.toUnsigned(8)  = ${(-1).toUnsigned(8)}');
  print('300.toUnsigned(8) = ${300.toUnsigned(8)}');
  print('-2.toUnsigned(16) = ${(-2).toUnsigned(16)}');
}
Output
-1.toUnsigned(8)  = 255
300.toUnsigned(8) = 44
-2.toUnsigned(16) = 65534
toSignedmethod
int toSigned(int width)

Returns the least significant width bits of this integer, extending the highest retained bit to the sign. This is the same as truncating the value to fit in width bits using an signed 2-s complement representation. The returned value has the same bit value in all positions higher than width.

                         //     V--sign bit-V
16.toSigned(5) == -16;   //  00010000 -> 11110000
239.toSigned(5) == 15;   //  11101111 -> 00001111
                         //     ^           ^

This operation can be used to simulate arithmetic from low level languages. For example, to increment an 8 bit signed quantity:

q = (q + 1).toSigned(8);

q will count from 0 up to 127, wrap to -128 and count back up to 127.

If the input value fits in width bits without truncation, the result is the same as the input. The minimum width needed to avoid truncation of x is x.bitLength + 1, i.e.

x == x.toSigned(x.bitLength + 1);
Example
void main() {
  print('200 as signed 8-bit:   ${200.toSigned(8)}');
  print('-1 as unsigned 8-bit:  ${(-1).toUnsigned(8)}');
  print('300 as unsigned 8-bit: ${300.toUnsigned(8)}');
}
Output
200 as signed 8-bit:   -56
-1 as unsigned 8-bit:  255
300 as unsigned 8-bit: 44
absmethod
int abs()

Returns the absolute value of this integer.

For any integer value, the result is the same as value < 0 ? -value: value.

Integer overflow may cause the result of -value to stay negative.

Example
void main() {
  print('(-7).abs() = ${(-7).abs()}');
  print('(-7).sign  = ${(-7).sign}');
  print('0.sign     = ${0.sign}');
}
Output
(-7).abs() = 7
(-7).sign  = -1
0.sign     = 0
roundmethod
int round()

Returns this.

Example
void main() {
  // On an int, round() returns the same value: it is already whole.
  print('7.round()  = ${7.round()}');
  print('-3.round() = ${(-3).round()}');
  print('as double: 7.0.round() = ${7.0.round()}');
}
Output
7.round()  = 7
-3.round() = -3
as double: 7.0.round() = 7
floormethod
int floor()

Returns this.

Example
void main() {
  // On an int, floor() returns the same value: it is already whole.
  print('7.floor()  = ${7.floor()}');
  print('-3.floor() = ${(-3).floor()}');
  print('as double: 7.0.floor() = ${7.0.floor()}');
}
Output
7.floor()  = 7
-3.floor() = -3
as double: 7.0.floor() = 7
ceilmethod
int ceil()

Returns this.

Example
void main() {
  // On an int, ceil() returns the same value: it is already whole.
  print('7.ceil()  = ${7.ceil()}');
  print('-3.ceil() = ${(-3).ceil()}');
  print('as double: 7.0.ceil() = ${7.0.ceil()}');
}
Output
7.ceil()  = 7
-3.ceil() = -3
as double: 7.0.ceil() = 7
truncatemethod
int truncate()

Returns this.

Example
void main() {
  // On an int, truncate() returns the same value: it is already whole.
  print('7.truncate()  = ${7.truncate()}');
  print('-3.truncate() = ${(-3).truncate()}');
  print('as double: 7.0.truncate() = ${7.0.truncate()}');
}
Output
7.truncate()  = 7
-3.truncate() = -3
as double: 7.0.truncate() = 7
double roundToDouble()

Returns this.toDouble.

Example
void main() {
  final d = 7.roundToDouble();
  print('7.roundToDouble() = $d (${d.runtimeType})');
  print('-3.roundToDouble() = ${(-3).roundToDouble()}');
}
Output
7.roundToDouble() = 7.0 (double)
-3.roundToDouble() = -3.0
double floorToDouble()

Returns this.toDouble.

Example
void main() {
  final d = 7.floorToDouble();
  print('7.floorToDouble() = $d (${d.runtimeType})');
  print('-3.floorToDouble() = ${(-3).floorToDouble()}');
}
Output
7.floorToDouble() = 7.0 (double)
-3.floorToDouble() = -3.0
double ceilToDouble()

Returns this.toDouble.

Example
void main() {
  final d = 7.ceilToDouble();
  print('7.ceilToDouble() = $d (${d.runtimeType})');
  print('-3.ceilToDouble() = ${(-3).ceilToDouble()}');
}
Output
7.ceilToDouble() = 7.0 (double)
-3.ceilToDouble() = -3.0
double truncateToDouble()

Returns this.toDouble.

Example
void main() {
  final d = 7.truncateToDouble();
  print('7.truncateToDouble() = $d (${d.runtimeType})');
  print('-3.truncateToDouble() = ${(-3).truncateToDouble()}');
}
Output
7.truncateToDouble() = 7.0 (double)
-3.truncateToDouble() = -3.0
toStringmethod
String toString()

Returns a string representation of this integer.

The returned string is parsable by parse. For any int i, it is guaranteed that i == int.parse(i.toString).

Example
void main() {
  print('42.toString()     = ${42.toString()}');
  print('-7.toString()     = ${(-7).toString()}');
  print('padded:           ${7.toString().padLeft(3, '0')}');
  print('length of 2^62:   ${(1 << 62).toString().length} digits');
}
Output
42.toString()     = 42
-7.toString()     = -7
padded:           007
length of 2^62:   19 digits
String toRadixString(int radix)

Converts this int to a string representation in the given radix.

In the string representation, lower-case letters are used for digits above '9', with 'a' being 10 and 'z' being 35.

The radix argument must be an integer in the range 2 to 36.

Example:

// Binary (base 2).
print(12.toRadixString(2)); // 1100
print(31.toRadixString(2)); // 11111
print(2021.toRadixString(2)); // 11111100101
print((-12).toRadixString(2)); // -1100
// Octal (base 8).
print(12.toRadixString(8)); // 14
print(31.toRadixString(8)); // 37
print(2021.toRadixString(8)); // 3745
// Hexadecimal (base 16).
print(12.toRadixString(16)); // c
print(31.toRadixString(16)); // 1f
print(2021.toRadixString(16)); // 7e5
// Base 36.
print((35 * 36 + 1).toRadixString(36)); // z1
Example
void main() {
  const n = 255;
  print('binary:  ${n.toRadixString(2)}');
  print('octal:   ${n.toRadixString(8)}');
  print('hex:     ${n.toRadixString(16)}');
  print('base 36: ${123456789.toRadixString(36)}');
  print('padded byte: ${10.toRadixString(2).padLeft(8, '0')}');
}
Output
binary:  11111111
octal:   377
hex:     ff
base 36: 21i3v9
padded byte: 00001010

Operators

operator &operator
int operator &(int other)

Bit-wise and operator.

Treating both this and other as sufficiently large two's component integers, the result is a number with only the bits set that are set in both this and other

If both operands are negative, the result is negative, otherwise the result is non-negative.

print((2 & 1).toRadixString(2)); // 0010 & 0001 -> 0000
print((3 & 1).toRadixString(2)); // 0011 & 0001 -> 0001
print((10 & 2).toRadixString(2)); // 1010 & 0010 -> 0010
Example
void main() {
  const flags = 0x0F;
  print('0x0F & 0x3C = ${(flags & 0x3C).toRadixString(2)}');
  print('0x0F | 0x30 = ${(flags | 0x30).toRadixString(2)}');
  print('0x0F ^ 0xFF = ${(flags ^ 0xFF).toRadixString(2)}');
  print('~0          = ${~0}');
}
Output
0x0F & 0x3C = 1100
0x0F | 0x30 = 111111
0x0F ^ 0xFF = 11110000
~0          = -1
operator |operator
int operator |(int other)

Bit-wise or operator.

Treating both this and other as sufficiently large two's component integers, the result is a number with the bits set that are set in either of this and other

If both operands are non-negative, the result is non-negative, otherwise the result is negative.

Example:

print((2 | 1).toRadixString(2)); // 0010 | 0001 -> 0011
print((3 | 1).toRadixString(2)); // 0011 | 0001 -> 0011
print((10 | 2).toRadixString(2)); // 1010 | 0010 -> 1010
Example
void main() {
  const read = 4, write = 2, exec = 1;
  final perms = read | write;
  print('read | write = $perms (${perms.toRadixString(2)})');
  print('has write: ${perms & write != 0}, has exec: ${perms & exec != 0}');
}
Output
read | write = 6 (110)
has write: true, has exec: false
operator ^operator
int operator ^(int other)

Bit-wise exclusive-or operator.

Treating both this and other as sufficiently large two's component integers, the result is a number with the bits set that are set in one, but not both, of this and other

If the operands have the same sign, the result is non-negative, otherwise the result is negative.

Example:

print((2 ^ 1).toRadixString(2)); //  0010 ^ 0001 -> 0011
print((3 ^ 1).toRadixString(2)); //  0011 ^ 0001 -> 0010
print((10 ^ 2).toRadixString(2)); //  1010 ^ 0010 -> 1000
Example
void main() {
  print('12 ^ 10 = ${12 ^ 10}  (${(12 ^ 10).toRadixString(2)})');
  var a = 3, b = 9;
  a ^= b; b ^= a; a ^= b;
  print('xor swap: a=$a, b=$b');
}
Output
12 ^ 10 = 6  (110)
xor swap: a=9, b=3
operator ~operator
int operator ~()

The bit-wise negate operator.

Treating this as a sufficiently large two's component integer, the result is a number with the opposite bits set.

This maps any integer x to -x - 1.

Example
void main() {
  print('~0  = ${~0}');
  print('~5  = ${~5}  (-(5+1))');
  print('~5 & 0xFF = ${~5 & 0xFF}');
}
Output
~0  = -1
~5  = -6  (-(5+1))
~5 & 0xFF = 250
operator <<operator
int operator <<(int shiftAmount)

Shift the bits of this integer to the left by shiftAmount.

Shifting to the left makes the number larger, effectively multiplying the number by pow(2, shiftAmount).

There is no limit on the size of the result. It may be relevant to limit intermediate values by using the "and" operator with a suitable mask.

It is an error if shiftAmount is negative.

Example:

print((3 << 1).toRadixString(2)); // 0011 -> 0110
print((9 << 2).toRadixString(2)); // 1001 -> 100100
print((10 << 3).toRadixString(2)); // 1010 -> 1010000
Example
void main() {
  print('1 << 10  = ${1 << 10}');
  print('5 << 2   = ${5 << 2}');
  print('256 >> 4 = ${256 >> 4}');
  print('-16 >> 2 = ${-16 >> 2}');
  print('-16 >>> 60 = ${-16 >>> 60}');
}
Output
1 << 10  = 1024
5 << 2   = 20
256 >> 4 = 16
-16 >> 2 = -4
-16 >>> 60 = 15
operator >>operator
int operator >>(int shiftAmount)

Shift the bits of this integer to the right by shiftAmount.

Shifting to the right makes the number smaller and drops the least significant bits, effectively doing an integer division by pow(2, shiftAmount).

It is an error if shiftAmount is negative.

Example:

print((3 >> 1).toRadixString(2)); // 0011 -> 0001
print((9 >> 2).toRadixString(2)); // 1001 -> 0010
print((10 >> 3).toRadixString(2)); // 1010 -> 0001
print((-6 >> 2).toRadixString); // 111...1010 -> 111...1110 == -2
print((-85 >> 3).toRadixString); // 111...10101011 -> 111...11110101 == -11
Example
void main() {
  print('256 >> 4 = ${256 >> 4}');
  print('-16 >> 2 = ${-16 >> 2}  (sign is kept)');
  const rgb = 0x3366CC;
  print('red=${(rgb >> 16) & 0xFF}, green=${(rgb >> 8) & 0xFF}, blue=${rgb & 0xFF}');
}
Output
256 >> 4 = 16
-16 >> 2 = -4  (sign is kept)
red=51, green=102, blue=204
operator >>>operator
int operator >>>(int shiftAmount)

Bitwise unsigned right shift by shiftAmount bits.

The least significant shiftAmount bits are dropped, the remaining bits (if any) are shifted down, and zero-bits are shifted in as the new most significant bits.

The shiftAmount must be non-negative.

Example:

print((3 >>> 1).toRadixString(2)); // 0011 -> 0001
print((9 >>> 2).toRadixString(2)); // 1001 -> 0010
print(((-9) >>> 2).toRadixString(2)); // 111...1011 -> 001...1110 (> 0)
Example
void main() {
  print('16 >>> 2 = ${16 >>> 2}');
  print('-16 >> 60  = ${-16 >> 60}');
  print('-16 >>> 60 = ${-16 >>> 60}  (zero-filled from the left)');
}
Output
16 >>> 2 = 4
-16 >> 60  = -1
-16 >>> 60 = 15  (zero-filled from the left)
operator -operator
int operator -()

Return the negative value of this integer.

The result of negating an integer always has the opposite sign, except for zero, which is its own negation.

Example
void main() {
  const x = 5;
  print('-x = ${-x}');
  print('-(-x) = ${-(-x)}');
  print('-0 == 0: ${-0 == 0}');
}
Output
-x = -5
-(-x) = 5
-0 == 0: true
abstract class Invocation

Representation of the invocation of a member on an object.

This is the type of objects passed to Object.noSuchMethod when an object doesn't support the member invocation that was attempted on it.

Constructors

Invocationconstructor
Invocation()
Example
// noSuchMethod receives an Invocation describing the attempted call.
class Recorder {
  final calls = <String>[];
  @override
  dynamic noSuchMethod(Invocation i) {
    calls.add('${i.memberName} method=${i.isMethod} args=${i.positionalArguments}');
    return null;
  }
}

void main() {
  dynamic r = Recorder();
  r.save(1, 2);
  r.load('x');
  for (final c in (r as Recorder).calls) print(c);
}
Output
Symbol("save") method=true args=[1, 2]
Symbol("load") method=true args=[x]
factory Invocation.method(Symbol memberName, Iterable<Object?>? positionalArguments, [Map<Symbol, Object?>? namedArguments])

Creates an invocation corresponding to a method invocation.

The method invocation has no type arguments. If the named arguments are omitted, they default to no named arguments.

Example
void main() {
  final i = Invocation.method(#resize, [640, 480], {#keepRatio: true});
  print('member:     ${i.memberName}');
  print('isMethod:   ${i.isMethod}');
  print('positional: ${i.positionalArguments}');
  print('named:      ${i.namedArguments}');
}
Output
member:     Symbol("resize")
isMethod:   true
positional: [640, 480]
named:      {Symbol("keepRatio"): true}
factory Invocation.genericMethod(Symbol memberName, Iterable<Type>? typeArguments, Iterable<Object?>? positionalArguments, [Map<Symbol, Object?>? namedArguments])

Creates an invocation corresponding to a generic method invocation.

If typeArguments is null or empty, the constructor is equivalent to calling Invocation.method with the remaining arguments. All the individual type arguments must be non-null.

If the named arguments are omitted, they default to no named arguments.

Example
void main() {
  final i = Invocation.genericMethod(#cast, [int], ['7']);
  print('member:   ${i.memberName}');
  print('types:    ${i.typeArguments}');
  print('args:     ${i.positionalArguments}');
  print('isMethod: ${i.isMethod}');
}
Output
member:   Symbol("cast")
types:    [int]
args:     [7]
isMethod: true
factory Invocation.getter(Symbol name) = _Invocation.getter

Creates an invocation corresponding to a getter invocation.

Example
void main() {
  final i = Invocation.getter(#length);
  print('member:   ${i.memberName}');
  print('isGetter: ${i.isGetter}');
  print('isMethod: ${i.isMethod}');
  print('args:     ${i.positionalArguments}');
}
Output
member:   Symbol("length")
isGetter: true
isMethod: false
args:     []
factory Invocation.setter(Symbol memberName, Object? argument) = _Invocation.setter

Creates an invocation corresponding to a setter invocation.

This constructor accepts any Symbol as memberName, but remember that actual setter names end in =, so the invocation corresponding to object.member = value is

Invocation.setter(const Symbol("member="), value)
Example
void main() {
  final i = Invocation.setter(const Symbol('volume='), 11);
  print('member:   ${i.memberName}');
  print('isSetter: ${i.isSetter}');
  print('value:    ${i.positionalArguments.single}');
}
Output
member:   Symbol("volume=")
isSetter: true
value:    11

Properties

Symbol get memberName

The name of the invoked member.

List<Type> get typeArguments

An unmodifiable view of the type arguments of the call.

If the member is a getter, setter or operator, the type argument list is always empty.

List<dynamic> get positionalArguments

An unmodifiable view of the positional arguments of the call.

If the member is a getter, the positional arguments list is always empty.

Map<Symbol, dynamic> get namedArguments

An unmodifiable view of the named arguments of the call.

If the member is a getter, setter or operator, the named arguments map is always empty.

isMethodgetter
bool get isMethod

Whether the invocation was a method call.

isGettergetter
bool get isGetter

Whether the invocation was a getter call. If so, all three types of arguments lists are empty.

isSettergetter
bool get isSetter

Whether the invocation was a setter call.

If so, positionalArguments has exactly one positional argument, namedArguments is empty, and typeArguments is empty.

bool get isAccessor

Whether the invocation was a getter or a setter call.

abstract mixin class Iterable<E>

A collection of values, or "elements", that can be accessed sequentially.

The elements of the iterable are accessed by getting an Iterator using the iterator getter, and using it to step through the values. Stepping with the iterator is done by calling Iterator.moveNext, and if the call returns true, the iterator has now moved to the next element, which is then available as Iterator.current. If the call returns false, there are no more elements. The Iterator.current value must only be used when the most recent call to Iterator.moveNext has returned true. If it is used before calling Iterator.moveNext the first time on an iterator, or after a call has returned false or has thrown an error, reading Iterator.current may throw or may return an arbitrary value.

You can create more than one iterator from the same Iterable. Each time iterator is read, it returns a new iterator, and different iterators can be stepped through independently, each giving access to all the elements of the iterable. The iterators of the same iterable should provide the same values in the same order (unless the underlying collection is modified between the iterations, which some collections allow).

You can also iterate over the elements of an Iterable using the for-in loop construct, which uses the iterator getter behind the scenes. For example, you can iterate over all of the keys of a Map, because Map keys are iterable.

var kidsBooks = {'Matilda': 'Roald Dahl',
                 'Green Eggs and Ham': 'Dr Seuss',
                 'Where the Wild Things Are': 'Maurice Sendak'};
for (var book in kidsBooks.keys) {
  print('$book was written by ${kidsBooks[book]}');
}

The List and Set classes are both Iterable, as are most classes in the raya:collection library.

Some Iterable collections can be modified. Adding an element to a List or Set will change which elements it contains, and adding a new key to a Map changes the elements of Map.keys. Iterators created after the change will provide the new elements, and may or may not preserve the order of existing elements (for example, a HashSet may completely change its order when a single element is added).

Changing a collection while it is being iterated is generally not allowed. Doing so will break the iteration, which is typically signalled by throwing a ConcurrentModificationError the next time Iterator.moveNext is called. The current value of Iterator.current getter should not be affected by the change in the collection, the current value was set by the previous call to Iterator.moveNext.

Some iterables compute their elements dynamically every time they are iterated, like the one returned by Iterable.generate or the iterable returned by a sync* generator function. If the computation doesn't depend on other objects that may change, then the generated sequence should be the same one every time it's iterated.

The members of Iterable, other than iterator itself, work by looking at the elements of the iterable. This can be implemented by running through the iterator, but some classes may have more efficient ways of finding the result (like last or length on a List, or contains on a Set).

The methods that return another Iterable (like map and where) are all lazy - they will iterate the original (as necessary) every time the returned iterable is iterated, and not before.

Since an iterable may be iterated more than once, it's not recommended to have detectable side-effects in the iterator. For methods like map and where, the returned iterable will execute the argument function on every iteration, so those functions should also not have side effects.

The Iterable declaration provides a default implementation, which can be extended or mixed in to implement the Iterable interface. It implements every member other than the iterator getter, using the Iterator provided by iterator. An implementation of the Iterable interface should provide a more efficient implementation of the members of Iterable when it can do so.

Constructors

Iterableconstructor
const Iterable()
Example
// Extend Iterable and supply only an iterator; map, where, join... come free.
class Countdown extends Iterable<int> {
  final int from;
  Countdown(this.from);
  @override
  Iterator<int> get iterator => List.generate(from + 1, (i) => from - i).iterator;
}

void main() {
  final c = Countdown(5);
  print('items:  ${c.toList()}');
  print('evens:  ${c.where((x) => x.isEven).toList()}');
  print('sum:    ${c.fold(0, (a, b) => a + b)}');
  print('join:   ${c.join(' > ')}');
}
Output
items:  [5, 4, 3, 2, 1, 0]
evens:  [4, 2, 0]
sum:    15
join:   5 > 4 > 3 > 2 > 1 > 0
factory Iterable.generate(int count, [E generator(int index)?])

Creates an Iterable which generates its elements dynamically.

The generated iterable has count elements, and the element at index n is computed by calling generator(n). Values are not cached, so each iteration computes the values again.

If generator is omitted, it defaults to an identity function on integers (int x) => x, so it may only be omitted if the type parameter allows integer values. That is, if E is a super-type of int.

As an Iterable, Iterable.generate(n, generator)) is equivalent to const [0... n - 1].map(generator).

Example
void main() {
  final evens = Iterable.generate(5, (i) => i * 2);
  print('evens: ${evens.toList()}');
  print('lazy: ${evens.map((x) => x + 1)}');
}
Output
evens: [0, 2, 4, 6, 8]
lazy: (1, 3, 5, 7, 9)
factory Iterable.withIterator(Iterator<E> Function() iteratorFactory) = _WithIteratorIterable<E>

Creates an Iterable from the Iterator factory.

The returned iterable creates a new iterator each time iterator is read, by calling the provided iteratorFactory function. The iteratorFactory function must return a new instance of Iterator<E> on each call.

This factory is useful when you need to create an iterable from a custom iterator, or when you want to ensure a fresh iteration state on each use.

Example:

final numbers = Iterable.withIterator(() => [1, 2, 3].iterator);
print(numbers.toList()); // [1, 2, 3]
Example
class Fib implements Iterator<int> {
  int a = 0, b = 1, _cur = 0;
  @override
  int get current => _cur;
  @override
  bool moveNext() {
    _cur = a;
    final n = a + b;
    a = b;
    b = n;
    return true;
  }
}

void main() {
  final fibs = Iterable.withIterator(() => Fib());
  print('first 10: ${fibs.take(10).toList()}');
  print('again:    ${fibs.take(5).toList()}'); // a fresh iterator each time
}
Output
first 10: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
again:    [0, 1, 1, 2, 3]
const factory Iterable.empty() = EmptyIterable<E>

Creates an empty iterable.

The empty iterable has no elements, and iterating it always stops immediately.

Example
Iterable<int> squaresUpTo(int n) =>
    n <= 0 ? const Iterable.empty() : Iterable.generate(n, (i) => i * i);

void main() {
  print('squaresUpTo(4): ${squaresUpTo(4).toList()}');
  final none = squaresUpTo(0);
  print('isEmpty: ${none.isEmpty}, length: ${none.length}');
  print('firstOrNull-style: ${none.isEmpty ? 'nothing' : none.first}');
}
Output
squaresUpTo(4): [0, 1, 4, 9]
isEmpty: true, length: 0
firstOrNull-style: nothing

Static

castFromstaticmethod
static Iterable<T> castFrom<S, T>(Iterable<S> source)

Adapts source to be an Iterable<T>.

Any time the iterable would produce an element that is not a T, the element access will throw. If all elements of source are actually instances of T, or if only elements that are actually instances of T are accessed, then the resulting iterable can be used as an Iterable<T>.

Example
void main() {
  final Iterable<Object> mixed = <Object>[1, 2, 3];
  final ints = Iterable.castFrom<Object, int>(mixed);
  print('sum: ${ints.fold(0, (a, b) => a + b)}');
  final bad = Iterable.castFrom<Object, int>(<Object>[1, 'two']);
  try {
    print(bad.toList());
  } on TypeError {
    print('casting "two" to int fails lazily, on access');
  }
}
Output
sum: 6
casting "two" to int fails lazily, on access
static String iterableToShortString(Iterable iterable, [String leftDelimiter = '(', String rightDelimiter = ')'])

Convert an Iterable to a string like Iterable.toString.

Allows using other delimiters than '(' and ')'.

Handles circular references where converting one of the elements to a string ends up converting iterable to a string again.

Example
void main() {
  final many = Iterable.generate(200, (i) => i);
  final s = Iterable.iterableToShortString(many);
  print('length of text: ${s.length}');
  print('starts: ${s.substring(0, 20)}');
  print('ends:   ${s.substring(s.length - 20)}');
  print('custom: ${Iterable.iterableToShortString([1, 2, 3], '<', '>')}');
}
Output
length of text: 79
starts: (0, 1, 2, 3, 4, 5, 6
ends:   17, 18, 19, 20, ...)
custom: <1, 2, 3>
static String iterableToFullString(Iterable iterable, [String leftDelimiter = '(', String rightDelimiter = ')'])

Converts an Iterable to a string.

Converts each elements to a string, and separates the results by ", ". Then wraps the result in leftDelimiter and rightDelimiter.

Unlike iterableToShortString, this conversion doesn't omit any elements or puts any limit on the size of the result.

Handles circular references where converting one of the elements to a string ends up converting iterable to a string again.

Example
void main() {
  final xs = Iterable.generate(5, (i) => i * 10);
  print('default:  ${Iterable.iterableToFullString(xs)}');
  print('brackets: ${Iterable.iterableToFullString(xs, '[', ']')}');
  print('set-like: ${Iterable.iterableToFullString({'a', 'b'}, '{', '}')}');
}
Output
default:  (0, 10, 20, 30, 40)
brackets: [0, 10, 20, 30, 40]
set-like: {a, b}

Properties

iteratorgetter
Iterator<E> get iterator

A new Iterator that allows iterating the elements of this Iterable.

Iterable classes may specify the iteration order of their elements (for example List always iterate in index order), or they may leave it unspecified (for example a hash-based Set may iterate in any order).

Each time iterator is read, it returns a new iterator, which can be used to iterate through all the elements again. The iterators of the same iterable can be stepped through independently, but should return the same elements in the same order, as long as the underlying collection isn't changed.

Modifying the collection may cause new iterators to produce different elements, and may change the order of existing elements. A List specifies its iteration order precisely, so modifying the list changes the iteration order predictably. A hash-based Set may change its iteration order completely when adding a new element to the set.

Modifying the underlying collection after creating the new iterator may cause an error the next time Iterator.moveNext is called on that iterator. Any modifiable iterable class should specify which operations will break iteration.

lengthgetter
int get length

The number of elements in this Iterable.

Counting all elements may involve iterating through all elements and can therefore be slow. Some iterables have a more efficient way to find the number of elements. These must override the default implementation of length.

isEmptygetter
bool get isEmpty

Whether this collection has no elements.

May be computed by checking if iterator.moveNext returns false.

Example:

final emptyList = <int>[];
print(emptyList.isEmpty); // true;
print(emptyList.iterator.moveNext()); // false
bool get isNotEmpty

Whether this collection has at least one element.

May be computed by checking if iterator.moveNext returns true.

Example:

final numbers = <int>{1, 2, 3};
print(numbers.isNotEmpty); // true;
print(numbers.iterator.moveNext()); // true
firstgetter
E get first

The first element.

Throws a StateError if this is empty. Otherwise returns the first element in the iteration order, equivalent to this.elementAt(0).

lastgetter
E get last

The last element.

Throws a StateError if this is empty. Otherwise may iterate through the elements and returns the last one seen. Some iterables may have more efficient ways to find the last element (for example a list can directly access the last element, without iterating through the previous ones).

singlegetter
E get single

Checks that this iterable has only one element, and returns that element.

Throws a StateError if this is empty or has more than one element. This operation will not iterate past the second element.

Methods

castmethod
Iterable<R> cast<R>()

A view of this iterable as an iterable of R instances.

If this iterable only contains instances of R, all operations will work correctly. If any operation tries to access an element that is not an instance of R, the access will throw instead.

When the returned iterable creates a new object that depends on the type R, e.g. from toList, it will have exactly the type R.

Example
void main() {
  final List<num> nums = [1, 2, 3];
  final Iterable<int> ints = nums.cast<int>();
  print('as ints: ${ints.toList()}, bitLength sum: ${ints.map((i) => i.bitLength).reduce((a, b) => a + b)}');
  final List<Object> mixed = [1, 'x'];
  try {
    mixed.cast<int>().toList();
  } on TypeError {
    print('"x" is not an int -> TypeError when read');
  }
}
Output
as ints: [1, 2, 3], bitLength sum: 5
"x" is not an int -> TypeError when read
Iterable<E> followedBy(Iterable<E> other)

Creates the lazy concatenation of this iterable and other.

The returned iterable will provide the same elements as this iterable, and, after that, the elements of other, in the same order as in the original iterables.

Example:

var planets = <String>['Earth', 'Jupiter'];
var updated = planets.followedBy(['Mars', 'Venus']);
print(updated); // (Earth, Jupiter, Mars, Venus)
Example
void main() {
  final a = [1, 2], b = [3, 4];
  print(a.followedBy(b).toList());
  print(a.followedBy([0]).map((x) => x * 2).toList());
}
Output
[1, 2, 3, 4]
[2, 4, 0]
mapmethod
Iterable<T> map<T>(T toElement(E e))

The current elements of this iterable modified by toElement.

Returns a new lazy Iterable with elements that are created by calling toElement on each element of this Iterable in iteration order.

The returned iterable is lazy, so it won't iterate the elements of this iterable until it is itself iterated, and then it will apply toElement to create one element at a time. The converted elements are not cached. Iterating multiple times over the returned Iterable will invoke the supplied toElement function once per element for on each iteration.

Methods on the returned iterable are allowed to omit calling toElement on any element where the result isn't needed. For example, elementAt may call toElement only once.

Equivalent to:

Iterable<T> map<T>(T toElement(E e)) sync* {
  for (var value in this) {
    yield toElement(value);
  }
}

Example:

var products = jsonDecode('''
[
  {"name": "Screwdriver", "price": 42.00},
  {"name": "Wingnut", "price": 0.50}
]
''');
var values = products.map((product) => product['price'] as double);
var totalPrice = values.fold(0.0, (a, b) => a + b); // 42.5.
Example
void main() {
  final names = ['ada', 'grace', 'alan'];
  final caps = names.map((n) => n[0].toUpperCase() + n.substring(1));
  print('map:    ${caps.toList()}');
  print('lengths: ${names.map((n) => n.length).toList()}');
}
Output
map:    [Ada, Grace, Alan]
lengths: [3, 5, 4]
wheremethod
Iterable<E> where(bool test(E element))

Creates a new lazy Iterable with all elements that satisfy the predicate test.

The matching elements have the same order in the returned iterable as they have in iterator.

This method returns a view of the mapped elements. As long as the returned Iterable is not iterated over, the supplied function test will not be invoked. Iterating will not cache results, and thus iterating multiple times over the returned Iterable may invoke the supplied function test multiple times on the same element.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.where((x) => x < 5); // (1, 2, 3)
result = numbers.where((x) => x > 5); // (6, 7)
result = numbers.where((x) => x.isEven); // (2, 6)
Example
void main() {
  final xs = [4, 8, 15, 16, 23, 42];
  print('even:   ${xs.where((x) => x.isEven).toList()}');
  print('> 15:   ${xs.where((x) => x > 15).toList()}');
  final mixed = <Object>[1, 'two', 3.0, 'four'];
  print('strings: ${mixed.whereType<String>().toList()}');
}
Output
even:   [4, 8, 16, 42]
> 15:   [16, 23, 42]
strings: [two, four]
whereTypemethod
Iterable<T> whereType<T>()

Creates a new lazy Iterable with all elements that have type T.

The matching elements have the same order in the returned iterable as they have in iterator.

This method returns a view of the mapped elements. Iterating will not cache results, and thus iterating multiple times over the returned Iterable may yield different results, if the underlying elements change between iterations.

Example
void main() {
  final things = <Object?>[1, 'two', 3.0, null, 4, 'five'];
  print('ints:    ${things.whereType<int>().toList()}');
  print('strings: ${things.whereType<String>().toList()}');
  print('nums:    ${things.whereType<num>().toList()}');
  print('non-null count: ${things.whereType<Object>().length}');
}
Output
ints:    [1, 4]
strings: [two, five]
nums:    [1, 3.0, 4]
non-null count: 5
expandmethod
Iterable<T> expand<T>(Iterable<T> toElements(E element))

Expands each element of this Iterable into zero or more elements.

The resulting Iterable runs through the elements returned by toElements for each element of this, in iteration order.

The returned Iterable is lazy, and calls toElements for each element of this iterable every time the returned iterable is iterated.

Example:

Iterable<int> count(int n) sync* {
  for (var i = 1; i <= n; i++) {
    yield i;
   }
 }

var numbers = [1, 3, 0, 2];
print(numbers.expand(count)); // (1, 1, 2, 3, 1, 2)

Equivalent to:

Iterable<T> expand<T>(Iterable<T> toElements(E e)) sync* {
  for (var value in this) {
    yield* toElements(value);
  }
}
Example
void main() {
  final nested = [[1, 2], [3], [4, 5, 6]];
  print('flattened: ${nested.expand((x) => x).toList()}');
  print('repeated:  ${[1, 2, 3].expand((x) => [x, x]).toList()}');
}
Output
flattened: [1, 2, 3, 4, 5, 6]
repeated:  [1, 1, 2, 2, 3, 3]
containsmethod
bool contains(Object? element)

Whether the collection contains an element equal to element.

This operation will check each element in order for being equal to element, unless it has a more efficient way to find an element equal to element. Stops iterating on the first equal element.

The equality used to determine whether element is equal to an element of the iterable defaults to the [Object.==] of the element.

Some types of iterable may have a different equality used for its elements. For example, a Set may have a custom equality (see Set.identity) that its contains uses. Likewise the Iterable returned by a Map.keys call should use the same equality that the Map uses for keys.

Example:

final gasPlanets = <int, String>{1: 'Jupiter', 2: 'Saturn'};
final containsOne = gasPlanets.keys.contains(1); // true
final containsFive = gasPlanets.keys.contains(5); // false
final containsJupiter = gasPlanets.values.contains('Jupiter'); // true
final containsMercury = gasPlanets.values.contains('Mercury'); // false
Example
void main() {
  final xs = {'red', 'green'};
  print('contains red:  ${xs.contains('red')}');
  print('contains blue: ${xs.contains('blue')}');
}
Output
contains red:  true
contains blue: false
forEachmethod
void forEach(void action(E element))

Invokes action on each element of this iterable in iteration order.

Example:

final numbers = <int>[1, 2, 6, 7];
numbers.forEach(print);
// 1
// 2
// 6
// 7
Example
void main() {
  final prices = {'tea': 2.5, 'cake': 4.0};
  var total = 0.0;
  prices.values.forEach((p) => total += p);
  print('total: $total');
  ['a', 'b', 'c'].forEach(print);
}
Output
total: 6.5
a
b
c
reducemethod
E reduce(E combine(E value, E element))

Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

The iterable must have at least one element. If it has only one element, that element is returned.

Otherwise this method starts with the first element from the iterator, and then combines it with the remaining elements in iteration order, as if by:

E value = iterable.first;
iterable.skip(1).forEach((element) {
  value = combine(value, element);
});
return value;

Example of calculating the sum of an iterable:

final numbers = <double>[10, 2, 5, 0.5];
final result = numbers.reduce((value, element) => value + element);
print(result); // 17.5

Consider using fold if the iterable can be empty.

Example
void main() {
  final xs = [7, 3, 9, 4];
  print('max: ${xs.reduce((a, b) => a > b ? a : b)}');
  print('min: ${xs.reduce((a, b) => a < b ? a : b)}');
  print('joined: ${['a', 'b', 'c'].reduce((a, b) => '$a-$b')}');
}
Output
max: 9
min: 3
joined: a-b-c
foldmethod
T fold<T>(T initialValue, T combine(T previousValue, E element))

Reduces a collection to a single value by iteratively combining each element of the collection with an existing value

Uses initialValue as the initial value, then iterates through the elements and updates the value with each element using the combine function, as if by:

var value = initialValue;
for (E element in this) {
  value = combine(value, element);
}
return value;

Example of calculating the sum of an iterable:

final numbers = <double>[10, 2, 5, 0.5];
const initialValue = 100.0;
final result = numbers.fold<double>(
    initialValue, (previousValue, element) => previousValue + element);
print(result); // 117.5
Example
void main() {
  final xs = [1, 2, 3, 4, 5];
  print('sum:     ${xs.fold<int>(0, (s, x) => s + x)}');
  print('product: ${xs.fold<int>(1, (p, x) => p * x)}');
  final words = ['to', 'be', 'or', 'not'];
  print('total letters: ${words.fold<int>(0, (n, w) => n + w.length)}');
}
Output
sum:     15
product: 120
total letters: 9
everymethod
bool every(bool test(E element))

Checks whether every element of this iterable satisfies test.

Checks every element in iteration order, and returns false if any of them make test return false, otherwise returns true. Returns true if the iterable is empty.

Example:

final planetsByMass = <double, String>{0.06: 'Mercury', 0.81: 'Venus',
  0.11: 'Mars'};
// Checks whether all keys are smaller than 1.
final every = planetsByMass.keys.every((key) => key < 1.0); // true
Example
void main() {
  final passwords = ['hunter2', 'correct horse', 'x'];
  for (final p in passwords) {
    final ok = [p.length >= 6, p.contains(RegExp(r'[a-z]'))].every((c) => c);
    print('"$p" ok: $ok');
  }
}
Output
"hunter2" ok: true
"correct horse" ok: true
"x" ok: false
joinmethod
String join([String separator = ""])

Converts each element to a String and concatenates the strings.

Iterates through elements of this iterable, converts each one to a String by calling Object.toString, and then concatenates the strings, with the separator string interleaved between the elements.

Example:

final planetsByMass = <double, String>{0.06: 'Mercury', 0.81: 'Venus',
  0.11: 'Mars'};
final joinedNames = planetsByMass.values.join('-'); // Mercury-Venus-Mars
Example
void main() {
  final xs = [1, 2, 3];
  print('join():     ${xs.join()}');
  print('join(", "): ${xs.join(', ')}');
  print('as path:    ${['usr', 'local', 'bin'].join('/')}');
}
Output
join():     123
join(", "): 1, 2, 3
as path:    usr/local/bin
anymethod
bool any(bool test(E element))

Checks whether any element of this iterable satisfies test.

Checks every element in iteration order, and returns true if any of them make test return true, otherwise returns false. Returns false if the iterable is empty.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.any((element) => element >= 5); // true;
result = numbers.any((element) => element >= 10); // false;
Example
void main() {
  final xs = [3, 5, 8, 11];
  print('any even:     ${xs.any((x) => x.isEven)}');
  print('every odd:    ${xs.every((x) => x.isOdd)}');
  print('every > 2:    ${xs.every((x) => x > 2)}');
  print('empty any:    ${<int>[].any((x) => true)}');
}
Output
any even:     true
every odd:    false
every > 2:    true
empty any:    false
toListmethod
List<E> toList({bool growable = true})

Creates a List containing the elements of this Iterable.

The elements are in iteration order. The list is fixed-length if growable is false.

Example:

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Mars'};
final keysList = planets.keys.toList(growable: false); // [1, 2, 3]
final valuesList =
    planets.values.toList(growable: false); // [Mercury, Venus, Mars]
Example
void main() {
  final squares = Iterable.generate(4, (i) => i * i);
  final growable = squares.toList();
  growable.add(16);
  print('growable: $growable');
  final fixed = squares.toList(growable: false);
  try {
    fixed.add(16);
  } on UnsupportedError {
    print('fixed-length: $fixed (add throws)');
  }
}
Output
growable: [0, 1, 4, 9, 16]
fixed-length: [0, 1, 4, 9] (add throws)
toSetmethod
Set<E> toSet()

Creates a Set containing the same elements as this iterable.

The set may contain fewer elements than the iterable, if the iterable contains an element more than once, or it contains one or more elements that are equal. The order of the elements in the set is not guaranteed to be the same as for the iterable.

Example:

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Mars'};
final valueSet = planets.values.toSet(); // {Mercury, Venus, Mars}
Example
void main() {
  final xs = [3, 1, 3, 2, 1];
  print('toSet:  ${xs.toSet()}');
  print('toList: ${xs.toSet().toList()}');
}
Output
toSet:  {3, 1, 2}
toList: [3, 1, 2]
takemethod
Iterable<E> take(int count)

Creates a lazy iterable of the count first elements of this iterable.

The returned Iterable may contain fewer than count elements, if this contains fewer than count elements.

The elements can be computed by stepping through iterator until count elements have been seen.

The count must not be negative.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
final result = numbers.take(4); // (1, 2, 3, 5)
final takeAll = numbers.take(100); // (1, 2, 3, 5, 6, 7)
Example
void main() {
  final xs = Iterable.generate(10, (i) => i);
  print('take(3):        ${xs.take(3).toList()}');
  print('skip(7):        ${xs.skip(7).toList()}');
  print('skip(2).take(3): ${xs.skip(2).take(3).toList()}');
  print('takeWhile < 4:  ${xs.takeWhile((x) => x < 4).toList()}');
  print('skipWhile < 8:  ${xs.skipWhile((x) => x < 8).toList()}');
}
Output
take(3):        [0, 1, 2]
skip(7):        [7, 8, 9]
skip(2).take(3): [2, 3, 4]
takeWhile < 4:  [0, 1, 2, 3]
skipWhile < 8:  [8, 9]
takeWhilemethod
Iterable<E> takeWhile(bool test(E value))

Creates a lazy iterable of the leading elements satisfying test.

The filtering happens lazily. Every new iterator of the returned iterable starts iterating over the elements of this.

The elements can be computed by stepping through iterator until an element is found where test(element) is false. At that point, the returned iterable stops (its moveNext returns false).

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.takeWhile((x) => x < 5); // (1, 2, 3)
result = numbers.takeWhile((x) => x != 3); // (1, 2)
result = numbers.takeWhile((x) => x != 4); // (1, 2, 3, 5, 6, 7)
result = numbers.takeWhile((x) => x.isOdd); // (1)
Example
void main() {
  final readings = [3, 5, 8, 12, 4, 2];
  print('until >10: ${readings.takeWhile((r) => r <= 10).toList()}');
  final words = 'the quick brown fox'.split(' ');
  print('short words prefix: ${words.takeWhile((w) => w.length <= 3).toList()}');
}
Output
until >10: [3, 5, 8]
short words prefix: [the]
skipmethod
Iterable<E> skip(int count)

Creates an Iterable that provides all but the first count elements.

When the returned iterable is iterated, it starts iterating over this, first skipping past the initial count elements. If this has fewer than count elements, then the resulting Iterable is empty. After that, the remaining elements are iterated in the same order as in this iterable.

Some iterables may be able to find later elements without first iterating through earlier elements, for example when iterating a List. Such iterables are allowed to ignore the initial skipped elements.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
final result = numbers.skip(4); // (6, 7)
final skipAll = numbers.skip(100); // () - no elements.

The count must not be negative.

Example
void main() {
  // Pairs of neighbours, a zip of a list with itself shifted by one.
  final xs = [1, 4, 9, 16, 25];
  final diffs = [for (final (a, b) in zip(xs, xs.skip(1))) b - a];
  print('differences: $diffs');
}

Iterable<(int, int)> zip(Iterable<int> a, Iterable<int> b) sync* {
  final ia = a.iterator, ib = b.iterator;
  while (ia.moveNext() && ib.moveNext()) {
    yield (ia.current, ib.current);
  }
}
Output
differences: [3, 5, 7, 9]
skipWhilemethod
Iterable<E> skipWhile(bool test(E value))

Creates an Iterable that skips leading elements while test is satisfied.

The filtering happens lazily. Every new Iterator of the returned iterable iterates over all elements of this.

The returned iterable provides elements by iterating this iterable, but skipping over all initial elements where test(element) returns true. If all elements satisfy test the resulting iterable is empty, otherwise it iterates the remaining elements in their original order, starting with the first element for which test(element) returns false.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.skipWhile((x) => x < 5); // (5, 6, 7)
result = numbers.skipWhile((x) => x != 3); // (3, 5, 6, 7)
result = numbers.skipWhile((x) => x != 4); // ()
result = numbers.skipWhile((x) => x.isOdd); // (2, 3, 5, 6, 7)
Example
void main() {
  final lines = ['# header', '# comment', 'data 1', '# not skipped', 'data 2'];
  print('after leading comments: ${lines.skipWhile((l) => l.startsWith('#')).toList()}');
  print('skip zeros: ${[0, 0, 7, 0, 3].skipWhile((x) => x == 0).toList()}');
}
Output
after leading comments: [data 1, # not skipped, data 2]
skip zeros: [7, 0, 3]
E firstWhere(bool test(E element), {E orElse()?})

The first element that satisfies the given predicate test.

Iterates through elements and returns the first to satisfy test.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.firstWhere((element) => element < 5); // 1
result = numbers.firstWhere((element) => element > 5); // 6
result =
    numbers.firstWhere((element) => element > 10, orElse: () => -1); // -1

If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError. Stops iterating on the first matching element.

Example
void main() {
  final xs = [3, 7, 10, 12];
  print('first even:  ${xs.firstWhere((x) => x.isEven)}');
  print('last even:   ${xs.lastWhere((x) => x.isEven)}');
  print('first > 100: ${xs.firstWhere((x) => x > 100, orElse: () => -1)}');
}
Output
first even:  10
last even:   12
first > 100: -1
lastWheremethod
E lastWhere(bool test(E element), {E orElse()?})

The last element that satisfies the given predicate test.

An iterable that can access its elements directly may check its elements in any order (for example a list starts by checking the last element and then moves towards the start of the list). The default implementation iterates elements in iteration order, checks test(element) for each, and finally returns that last one that matched.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.lastWhere((element) => element < 5); // 3
result = numbers.lastWhere((element) => element > 5); // 7
result = numbers.lastWhere((element) => element > 10,
    orElse: () => -1); // -1

If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.

Example
void main() {
  final temps = [12, 18, 25, 21, 30, 16];
  print('last above 20: ${temps.lastWhere((t) => t > 20)}');
  print('last above 40: ${temps.lastWhere((t) => t > 40, orElse: () => -1)}');
  try {
    temps.lastWhere((t) => t > 40);
  } on StateError catch (e) {
    print('no orElse -> ${e.message}');
  }
}
Output
last above 20: 30
last above 40: -1
no orElse -> No element
E singleWhere(bool test(E element), {E orElse()?})

The single element that satisfies test.

Checks elements to see if test(element) returns true. If exactly one element satisfies test, that element is returned. If more than one matching element is found, throws StateError. If no matching element is found, returns the result of orElse. If orElse is omitted, it defaults to throwing a StateError.

Example:

final numbers = <int>[2, 2, 10];
var result = numbers.singleWhere((element) => element > 5); // 10

When no matching element is found, the result of calling orElse is returned instead.

result = numbers.singleWhere((element) => element == 1,
    orElse: () => -1); // -1

There must not be more than one matching element.

result = numbers.singleWhere((element) => element == 2); // Throws Error.
Example
void main() {
  final users = [(id: 1, name: 'ada'), (id: 2, name: 'alan')];
  final u = users.singleWhere((u) => u.id == 2);
  print('found: ${u.name}');
  print('single of [7]: ${[7].single}');
}
Output
found: alan
single of [7]: 7
elementAtmethod
E elementAt(int index)

Returns the indexth element.

The index must be non-negative and less than length. Index zero represents the first element (so iterable.elementAt(0) is equivalent to iterable.first).

May iterate through the elements in iteration order, ignoring the first index elements and then returning the next. Some iterables may have a more efficient way to find the element.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
final elementAt = numbers.elementAt(4); // 6
Example
void main() {
  final s = {'x', 'y', 'z'};
  print('elementAt(1): ${s.elementAt(1)}');
  print('first ${s.first}, last ${s.last}');
}
Output
elementAt(1): y
first x, last z
toStringmethod
String toString()

Returns a string representation of (some of) the elements of this.

Elements are represented by their own toString results.

The default representation always contains the first three elements. If there are less than a hundred elements in the iterable, it also contains the last two elements.

If the resulting string isn't above 80 characters, more elements are included from the start of the iterable.

The conversion may omit calling toString on some elements if they are known to not occur in the output, and it may stop iterating after a hundred elements.

Example
void main() {
  print('lazy map:   ${[1, 2, 3].map((x) => x * 2)}');
  print('list:       ${[1, 2, 3]}');
  print('set:        ${{1, 2, 3}}');
  print('long lazy:  ${Iterable.generate(150, (i) => i)}');
}
Output
lazy map:   (2, 4, 6)
list:       [1, 2, 3]
set:        {1, 2, 3}
long lazy:  (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...)
abstract interface class Iterator<E>

An interface for getting items, one at a time, from an object.

The for-in construct transparently uses Iterator to test for the end of the iteration, and to get each item (or element).

If the object iterated over is changed during the iteration, the behavior is unspecified.

The Iterator is initially positioned before the first element. Before accessing the first element the iterator must thus be advanced using moveNext to point to the first element. If no element is left, then moveNext returns false, and all further calls to moveNext will also return false.

The current value must not be accessed before calling moveNext or after a call to moveNext has returned false.

A typical usage of an Iterator looks as follows:

var it = obj.iterator;
while (it.moveNext()) {
  use(it.current);
}
Example
void main() {
  final it = ['a', 'b', 'c'].iterator;
  while (it.moveNext()) {
    print('current: ${it.current}');
  }
}
Output
current: a
current: b
current: c

Properties

currentgetter
E get current

The current element.

If the iterator has not yet been moved to the first element (moveNext has not been called yet), or if the iterator has been moved past the last element of the Iterable (moveNext has returned false), then current is unspecified. An Iterator may either throw or return an iterator specific default value in that case.

The current getter should keep its value until the next call to moveNext, even if an underlying collection changes. After a successful call to moveNext, the user doesn't need to cache the current value, but can keep reading it from the iterator.

final colors = ['blue', 'yellow', 'red'];
var colorsIterator = colors.iterator;
while (colorsIterator.moveNext()) {
  print(colorsIterator.current);
}

The output of the example is:

blue
yellow
red

Methods

moveNextmethod
bool moveNext()

Advances the iterator to the next element of the iteration.

Should be called before reading current. If the call to moveNext returns true, then current will contain the next element of the iteration until moveNext is called again. If the call returns false, there are no further elements and current should not be used any more.

It is safe to call moveNext after it has already returned false, but it must keep returning false and not have any other effect.

A call to moveNext may throw for various reasons, including a concurrent change to an underlying collection. If that happens, the iterator may be in an inconsistent state, and any further behavior of the iterator is unspecified, including the effect of reading current.

final colors = ['blue', 'yellow', 'red'];
final colorsIterator = colors.iterator;
print(colorsIterator.moveNext()); // true
print(colorsIterator.moveNext()); // true
print(colorsIterator.moveNext()); // true
print(colorsIterator.moveNext()); // false
Example
// A custom iterator: the Collatz sequence from a start value down to 1.
class Collatz implements Iterator<int> {
  int? _n;
  final int start;
  Collatz(this.start);
  @override
  int get current => _n!;
  @override
  bool moveNext() {
    if (_n == 1) return false;
    _n = _n == null ? start : (_n!.isEven ? _n! ~/ 2 : 3 * _n! + 1);
    return true;
  }
}

void main() {
  final it = Collatz(6);
  final seen = <int>[];
  while (it.moveNext()) seen.add(it.current);
  print('collatz(6): $seen');
}
Output
collatz(6): [6, 3, 10, 5, 16, 8, 4, 2, 1]
class

List

abstract interface class List<E> implements Iterable<E>, _ListIterable<E>

An indexable collection of objects with a length.

Subclasses of this class implement different kinds of lists. The most common kinds of lists are:

  • Fixed-length list

An error occurs when attempting to use operations that can change the length of the list.

  • Growable list

Full implementation of the API defined in this class.

The default growable list, as created by [], keeps an internal buffer, and grows that buffer when necessary. This guarantees that a sequence of add operations will each execute in amortized constant time. Setting the length directly may take time proportional to the new length, and may change the internal capacity so that a following add operation will need to immediately increase the buffer capacity. Other list implementations may have different performance behavior.

Example of fixed-length list:

final fixedLengthList = List<int>.filled(5, 0); // Creates fixed-length list.
print(fixedLengthList); // [0, 0, 0, 0, 0]
fixedLengthList[0] = 87;
fixedLengthList.setAll(1, [1, 2, 3]);
print(fixedLengthList); // [87, 1, 2, 3, 0]
// Fixed length list length can't be changed or increased
fixedLengthList.length = 0;  // Throws
fixedLengthList.add(499);    // Throws

Example of growable list:

final growableList = <String>['A', 'B']; // Creates growable list.

To add data to the growable list, use [operator[]=], add or addAll.

growableList[0] = 'G';
print(growableList); // [G, B]
growableList.add('X');
growableList.addAll({'C', 'B'});
print(growableList); // [G, B, X, C, B]

To check whether, and where, the element is in the list, use indexOf or lastIndexOf.

final indexA = growableList.indexOf('A'); // -1 (not in the list)
final firstIndexB = growableList.indexOf('B'); // 1
final lastIndexB = growableList.lastIndexOf('B'); // 4

To remove an element from the growable list, use remove, removeAt, removeLast, removeRange or removeWhere.

growableList.remove('C');
growableList.removeLast();
print(growableList); // [G, B, X]

To insert an element at position in the list, use insert or insertAll.

growableList.insert(1, 'New');
print(growableList); // [G, New, B, X]

To replace a range of elements in the list, use fillRange, replaceRange or setRange.

growableList.replaceRange(0, 2, ['AB', 'A']);
print(growableList); // [AB, A, B, X]
growableList.fillRange(2, 4, 'F');
print(growableList); // [AB, A, F, F]

To sort the elements of the list, use sort.

growableList.sort((a, b) => a.compareTo(b));
print(growableList); // [A, AB, F, F]

To shuffle the elements of this list randomly, use shuffle.

growableList.shuffle();
print(growableList); // e.g. [AB, F, A, F]

To find the first element satisfying some predicate, or give a default value if none do, use firstWhere.

bool isVowel(String char) => char.length == 1 && "AEIOU".contains(char);
final firstVowel = growableList.firstWhere(isVowel, orElse: () => ''); // ''

There are similar lastWhere and singleWhere methods.

A list is an Iterable and supports all its methods, including where, map, whereType and toList.

Lists are Iterable. Iteration occurs over values in index order. Changing the values does not affect iteration, but changing the valid indices&mdash;that is, changing the list's length&mdash;between iteration steps causes a ConcurrentModificationError. This means that only growable lists can throw ConcurrentModificationError. If the length changes temporarily and is restored before continuing the iteration, the iterator might not detect it.

It is generally not allowed to modify the list's length (adding or removing elements) while an operation on the list is being performed, for example during a call to forEach or sort. Changing the list's length while it is being iterated, either by iterating it directly or through iterating an Iterable that is backed by the list, will break the iteration.

Example
void main() {
  final xs = [3, 1, 4, 1, 5, 9, 2, 6];
  print('first ${xs.first}, last ${xs.last}, length ${xs.length}');
  print('max via reduce: ${xs.reduce((a, b) => a > b ? a : b)}');
  print('sum via fold:   ${xs.fold(0, (s, x) => s + x)}');
  print('evens doubled:  ${xs.where((x) => x.isEven).map((x) => x * 2).toList()}');
}
Output
first 3, last 6, length 8
max via reduce: 9
sum via fold:   31
evens doubled:  [8, 4, 12]

Constructors

external factory List.filled(int length, E fill, {bool growable = false})

Creates a list of the given length with fill at each position.

The length must be a non-negative integer.

Example:

final zeroList = List<int>.filled(3, 0, growable: true); // [0, 0, 0]

The created list is fixed-length if growable is false (the default) and growable if growable is true. If the list is growable, increasing its length will not initialize new entries with fill. After being created and filled, the list is no different from any other growable or fixed-length list created using [] or other List constructors.

All elements of the created list share the same fill value.

final shared = List.filled(3, []);
shared[0].add(499);
print(shared);  // [[499], [499], [499]]

You can use List.generate to create a list with a fixed length and a new object at each position.

final unique = List.generate(3, (_) => []);
unique[0].add(499);
print(unique); // [[499], [], []]
Example
void main() {
  final zeros = List.filled(4, 0);
  print('filled: $zeros');
  final growable = List.filled(2, 'x', growable: true)..add('y');
  print('growable: $growable');
}
Output
filled: [0, 0, 0, 0]
growable: [x, x, y]
List.emptyfactory
external factory List.empty({bool growable = false})

Creates a new empty list.

If growable is false, which is the default, the list is a fixed-length list of length zero. If growable is true, the list is growable and equivalent to <E>[].

final growableList = List.empty(growable: true); // []
growableList.add(1); // [1]

final fixedLengthList = List.empty(growable: false);
fixedLengthList.add(1); // error
Example
void main() {
  final fixed = List<int>.empty();
  print('fixed: $fixed, length ${fixed.length}');
  try {
    fixed.add(1);
  } on UnsupportedError {
    print('fixed empty list cannot grow');
  }
  final grow = List<int>.empty(growable: true)..add(1)..add(2);
  print('growable: $grow');
}
Output
fixed: [], length 0
fixed empty list cannot grow
growable: [1, 2]
List.fromfactory
external factory List.from(Iterable<Object?> elements, {bool growable = true})

Creates a list containing all elements.

The Iterator of elements provides the order of the elements.

All the elements should be instances of E.

Example:

final numbers = <num>[1, 2, 3];
final listFrom = List<int>.from(numbers);
print(listFrom); // [1, 2, 3]

The elements iterable itself may have any element type, so this constructor can be used to down-cast a List, for example as:

const jsonArray = '''
  [{"text": "foo", "value": 1, "status": true},
   {"text": "bar", "value": 2, "status": false}]
''';
final List<dynamic> dynamicList = jsonDecode(jsonArray);
final List<Map<String, dynamic>> fooData =
    List.from(dynamicList.where((x) => x is Map && x['text'] == 'foo'));
print(fooData); // [{text: foo, value: 1, status: true}]

This constructor creates a growable list when growable is true; otherwise, it returns a fixed-length list.

Example
void main() {
  final Set<Object> raw = {3, 1, 2};
  final ints = List<int>.from(raw); // checks element types at runtime
  print('from set: $ints');
  final copy = List.from(ints)..add(9);
  print('copy: $copy, original: $ints');
  try {
    List<int>.from(<Object>[1, 'x']);
  } on TypeError {
    print('"x" rejected: TypeError');
  }
}
Output
from set: [3, 1, 2]
copy: [3, 1, 2, 9], original: [3, 1, 2]
"x" rejected: TypeError
List.offactory
external factory List.of(Iterable<E> elements, {bool growable = true})

Creates a list from elements.

The Iterator of elements provides the order of the elements.

This constructor creates a growable list when growable is true; otherwise, it returns a fixed-length list.

final numbers = <int>[1, 2, 3];
final listOf = List<num>.of(numbers);
print(listOf); // [1, 2, 3]
Example
void main() {
  final original = [1, 2, 3];
  final copy = List.of(original)..add(4);
  print('copy: $copy, original: $original');
  final fixed = List.of({'a', 'b'}, growable: false);
  print('from a set, fixed length: $fixed');
}
Output
copy: [1, 2, 3, 4], original: [1, 2, 3]
from a set, fixed length: [a, b]
external factory List.generate(int length, E generator(int index), {bool growable = true})

Generates a list of values.

Creates a list with length positions and fills it with values created by calling generator for each index in the range 0.. length - 1 in increasing order.

final growableList =
    List<int>.generate(3, (int index) => index * index, growable: true);
print(growableList); // [0, 1, 4]

final fixedLengthList =
    List<int>.generate(3, (int index) => index * index, growable: false);
print(fixedLengthList); // [0, 1, 4]

The created list is fixed-length if growable is set to false.

The length must be non-negative.

Example
void main() {
  final squares = List.generate(6, (i) => i * i);
  print('squares: $squares');
  final grid = List.generate(3, (r) => List.generate(3, (c) => r * 3 + c));
  print('grid:    $grid');
}
Output
squares: [0, 1, 4, 9, 16, 25]
grid:    [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
external factory List.unmodifiable(Iterable elements)

Creates an unmodifiable list containing all elements.

The Iterator of elements provides the order of the elements.

An unmodifiable list cannot have its length or elements changed. If the elements are themselves immutable, then the resulting list is also immutable.

final numbers = <int>[1, 2, 3];
final unmodifiableList = List.unmodifiable(numbers); // [1, 2, 3]
unmodifiableList[1] = 87; // Throws.
Example
void main() {
  final src = [1, 2, 3];
  final frozen = List<int>.unmodifiable(src);
  src.add(4); // the unmodifiable copy is independent
  print('frozen: $frozen, src: $src');
  try {
    frozen[0] = 9;
  } on UnsupportedError {
    print('frozen[0] = 9 -> UnsupportedError');
  }
}
Output
frozen: [1, 2, 3], src: [1, 2, 3, 4]
frozen[0] = 9 -> UnsupportedError
factory List.unmodifiableOf(Iterable<E> elements) = List<E>.unmodifiable

Creates an unmodifiable list containing all elements.

The Iterator of elements provides the order of the elements.

An unmodifiable list cannot have its length or elements changed. If the elements are themselves immutable, then the resulting list is also immutable.

final numbers = <int>[1, 2, 3];
final unmodifiableList = List.unmodifiable(numbers); // [1, 2, 3]
unmodifiableList[1] = 87; // Throws.
Example
void main() {
  final days = List<String>.unmodifiableOf(['mon', 'tue', 'wed']);
  print('days: $days, length ${days.length}');
  try {
    days.add('thu');
  } on UnsupportedError {
    print('add -> UnsupportedError');
  }
}
Output
days: [mon, tue, wed], length 3
add -> UnsupportedError

Static

castFromstaticmethod
static List<T> castFrom<S, T>(List<S> source)

Adapts source to be a List<T>.

Any time the list would produce an element that is not a T, the element access will throw.

Any time a T value is attempted stored into the adapted list, the store will throw unless the value is also an instance of S.

If all accessed elements of source are actually instances of T, and if all elements stored into the returned list are actually instance of S, then the returned list can be used as a List<T>.

Methods which accept Object? as argument, like contains and remove, will pass the argument directly to the this list's method without any checks.

Example
void main() {
  final List<Object> boxed = <Object>[1, 2, 3];
  final ints = List.castFrom<Object, int>(boxed);
  ints[0] = 10; // writes go through to the source
  print('ints:  $ints');
  print('boxed: $boxed');
}
Output
ints:  [10, 2, 3]
boxed: [10, 2, 3]
copyRangestaticmethod
static void copyRange<T>(List<T> target, int at, List<T> source, [int? start, int? end])

Copy a range of one list into another list.

This is a utility function that can be used to implement methods like setRange.

The range from start to end must be a valid range of source, and there must be room for end - start elements from position at. If start is omitted, it defaults to zero. If end is omitted, it defaults to source.length.

If source and target are the same list, overlapping source and target ranges are respected so that the target range ends up containing the initial content of the source range. Otherwise the order of element copying is not guaranteed.

Example
void main() {
  final target = List.filled(8, 0);
  final source = [1, 2, 3, 4, 5];
  List.copyRange(target, 2, source, 1, 4); // source[1..4) -> target at 2
  print('target: $target');
  List.copyRange(target, 0, source); // whole source
  print('target: $target');
}
Output
target: [0, 0, 2, 3, 4, 0, 0, 0]
target: [1, 2, 3, 4, 5, 0, 0, 0]
writeIterablestaticmethod
static void writeIterable<T>(List<T> target, int at, Iterable<T> source)

Write the elements of an iterable into a list.

This is a utility function that can be used to implement methods like setAll.

The elements of source are written into target from position at. The source must not contain more elements after writing the last position of target.

If the source is a list, the copyRange function is likely to be more efficient.

Example
void main() {
  final row = List.filled(6, '.');
  List.writeIterable(row, 1, 'abc'.split(''));
  print('row: ${row.join()}');
  List.writeIterable(row, 4, Iterable.generate(2, (i) => '$i'));
  print('row: ${row.join()}');
}
Output
row: .abc..
row: .abc01

Properties

firstsetter
void set first(E value)

The first element of the list.

The list must be non-empty when accessing its first element.

The first element of a list can be modified, unlike an Iterable. A list.first is equivalent to list[0], both for getting and setting the value.

final numbers = <int>[1, 2, 3];
print(numbers.first); // 1
numbers.first = 10;
print(numbers.first); // 10
numbers.clear();
numbers.first; // Throws.
Example
void main() {
  final queue = ['draft', 'review', 'ship'];
  queue.first = 'write';
  print('after first = write: $queue');
  try {
    <String>[].first = 'x';
  } on StateError {
    print('empty list: setting first throws StateError');
  }
}
Output
after first = write: [write, review, ship]
empty list: setting first throws StateError
lastsetter
void set last(E value)

The last element of the list.

The list must be non-empty when accessing its last element.

The last element of a list can be modified, unlike an Iterable. A list.last is equivalent to theList[theList.length - 1], both for getting and setting the value.

final numbers = <int>[1, 2, 3];
print(numbers.last); // 3
numbers.last = 10;
print(numbers.last); // 10
numbers.clear();
numbers.last; // Throws.
Example
void main() {
  final path = ['home', 'docs', 'old.txt'];
  path.last = 'new.txt';
  print('path: ${path.join('/')}');
}
Output
path: home/docs/new.txt
lengthgetter
int get length

The number of objects in this list.

The valid indices for a list are 0 through length - 1.

final numbers = <int>[1, 2, 3];
print(numbers.length); // 3
lengthsetter
set length(int newLength)

Setting the length changes the number of elements in the list.

The list must be growable. If newLength is greater than current length, new entries are initialized to null, so newLength must not be greater than the current length if the element type E is non-nullable.

final maybeNumbers = <int?>[1, null, 3];
maybeNumbers.length = 5;
print(maybeNumbers); // [1, null, 3, null, null]
maybeNumbers.length = 2;
print(maybeNumbers); // [1, null]

final numbers = <int>[1, 2, 3];
numbers.length = 1;
print(numbers); // [1]
numbers.length = 5; // Throws, cannot add `null`s.
Example
void main() {
  final xs = [1, 2, 3, 4, 5];
  xs.length = 3; // truncate
  print('truncated: $xs');
  final ys = <int?>[1, 2];
  ys.length = 4; // grow with nulls (element type must be nullable)
  print('grown:     $ys');
}
Output
truncated: [1, 2, 3]
grown:     [1, 2, null, null]
reversedgetter
Iterable<E> get reversed

An Iterable of the objects in this list in reverse order.

final numbers = <String>['two', 'three', 'four'];
final reverseOrder = numbers.reversed;
print(reverseOrder.toList()); // [four, three, two]
Example
void main() {
  final xs = [1, 2, 3, 4];
  print('reversed: ${xs.reversed.toList()}');
  print('original: $xs');
}
Output
reversed: [4, 3, 2, 1]
original: [1, 2, 3, 4]

Methods

castmethod
List<R> cast<R>()

Returns a view of this list as a list of R instances.

If this list contains only instances of R, all read operations will work correctly. If any operation tries to read an element that is not an instance of R, the access will throw instead.

Elements added to the list (e.g. by using add or addAll) must be instances of R to be valid arguments to the adding function, and they must also be instances of E to be accepted by this list as well.

Methods which accept Object? as argument, like contains and remove, will pass the argument directly to the this list's method without any checks. That means that you can do listOfStrings.cast<int>.remove("a") successfully, even if it looks like it shouldn't have any effect.

Typically implemented as List.castFrom<E, R>(this).

Example
void main() {
  final List<Object> values = <Object>[3, 1, 2];
  final ints = values.cast<int>();
  ints.sort();
  print('sorted via view: $values');
  print('max: ${ints.reduce((a, b) => a > b ? a : b)}');
}
Output
sorted via view: [1, 2, 3]
max: 3
addmethod
void add(E value)

Adds value to the end of this list, extending the length by one.

The list must be growable.

final numbers = <int>[1, 2, 3];
numbers.add(4);
print(numbers); // [1, 2, 3, 4]
Example
void main() {
  final xs = <int>[1, 2];
  xs.add(3);
  print('after add:    $xs');
  xs.addAll([4, 5]);
  print('after addAll: $xs');
  xs.insert(0, 0);
  print('after insert: $xs');
}
Output
after add:    [1, 2, 3]
after addAll: [1, 2, 3, 4, 5]
after insert: [0, 1, 2, 3, 4, 5]
addAllmethod
void addAll(Iterable<E> iterable)

Appends all objects of iterable to the end of this list.

Extends the length of the list by the number of objects in iterable. The list must be growable.

final numbers = <int>[1, 2, 3];
numbers.addAll([4, 5, 6]);
print(numbers); // [1, 2, 3, 4, 5, 6]
Example
void main() {
  final cart = ['apple'];
  cart.addAll(['bread', 'milk']);
  cart.addAll({'eggs'});
  cart.addAll(Iterable.generate(2, (i) => 'extra $i'));
  print('cart: $cart');
}
Output
cart: [apple, bread, milk, eggs, extra 0, extra 1]
sortmethod
void sort([int compare(E a, E b)?])

Sorts this list according to the order specified by the compare function.

The compare function must act as a Comparator.

final numbers = <String>['two', 'three', 'four'];
// Sort from shortest to longest.
numbers.sort((a, b) => a.length.compareTo(b.length));
print(numbers); // [two, four, three]

The default List implementations use Comparable.compare if compare is omitted.

final numbers = <int>[13, 2, -11, 0];
numbers.sort();
print(numbers); // [-11, 0, 2, 13]

In that case, the elements of the list must be Comparable to each other.

A Comparator may compare objects as equal (return zero), even if they are distinct objects. The sort function is not guaranteed to be stable, so distinct objects that compare as equal may occur in any order in the result:

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.sort((a, b) => a.length.compareTo(b.length));
print(numbers); // [one, two, four, three] OR [two, one, four, three]
Example
void main() {
  final nums = [5, 2, 9, 1, 7];
  nums.sort();
  print('ascending:  $nums');
  nums.sort((a, b) => b.compareTo(a));
  print('descending: $nums');
  final words = ['kiwi', 'fig', 'banana', 'apple'];
  words.sort((a, b) => a.length != b.length ? a.length - b.length : a.compareTo(b));
  print('by length, then A-Z: $words');
}
Output
ascending:  [1, 2, 5, 7, 9]
descending: [9, 7, 5, 2, 1]
by length, then A-Z: [fig, kiwi, apple, banana]
shufflemethod
void shuffle([Random? random])

Shuffles the elements of this list randomly.

final numbers = <int>[1, 2, 3, 4, 5];
numbers.shuffle();
print(numbers); // [1, 3, 4, 5, 2] OR some other random result.
Example
import 'raya:math';

void main() {
  final xs = List.generate(10, (i) => i);
  xs.shuffle(Random(1));
  xs.sort();
  print('shuffled and sorted again: $xs');
  print('same elements kept: ${xs.length == 10}');
}
Output
shuffled and sorted again: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
same elements kept: true
indexOfmethod
int indexOf(E element, [int start = 0])

The first index of element in this list.

Searches the list from index start to the end of the list. The first time an object o is encountered so that o == element, the index of o is returned.

final notes = <String>['do', 're', 'mi', 're'];
print(notes.indexOf('re')); // 1

final indexWithStart = notes.indexOf('re', 2); // 3

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.indexOf('fa'); // -1
Example
void main() {
  final xs = ['a', 'b', 'c', 'b'];
  print('indexOf b:       ${xs.indexOf('b')}');
  print('lastIndexOf b:   ${xs.lastIndexOf('b')}');
  print('indexOf z:       ${xs.indexOf('z')}');
  print('indexWhere > a:  ${xs.indexWhere((s) => s.compareTo('a') > 0)}');
}
Output
indexOf b:       1
lastIndexOf b:   3
indexOf z:       -1
indexWhere > a:  1
int indexWhere(bool test(E element), [int start = 0])

The first index in the list that satisfies the provided test.

Searches the list from index start to the end of the list. The first time an object o is encountered so that test(o) is true, the index of o is returned.

final notes = <String>['do', 're', 'mi', 're'];
final first = notes.indexWhere((note) => note.startsWith('r')); // 1
final second = notes.indexWhere((note) => note.startsWith('r'), 2); // 3

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.indexWhere((note) => note.startsWith('k')); // -1
Example
void main() {
  final scores = [40, 72, 55, 90, 68];
  print('first pass (>=60): index ${scores.indexWhere((s) => s >= 60)}');
  print('first pass after 2: index ${scores.indexWhere((s) => s >= 60, 2)}');
  print('none above 95: ${scores.indexWhere((s) => s > 95)}');
}
Output
first pass (>=60): index 1
first pass after 2: index 3
none above 95: -1
int lastIndexWhere(bool test(E element), [int? start])

The last index in the list that satisfies the provided test.

Searches the list from index start to 0. The first time an object o is encountered so that test(o) is true, the index of o is returned. If start is omitted, it defaults to the length of the list.

final notes = <String>['do', 're', 'mi', 're'];
final first = notes.lastIndexWhere((note) => note.startsWith('r')); // 3
final second = notes.lastIndexWhere((note) => note.startsWith('r'),
    2); // 1

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.lastIndexWhere((note) => note.startsWith('k'));
print(index); // -1
Example
void main() {
  final log = ['ok', 'warn', 'ok', 'warn', 'ok'];
  print('last warn: ${log.lastIndexWhere((e) => e == 'warn')}');
  print('last warn at or before 2: ${log.lastIndexWhere((e) => e == 'warn', 2)}');
  print('no error: ${log.lastIndexWhere((e) => e == 'error')}');
}
Output
last warn: 3
last warn at or before 2: 1
no error: -1
int lastIndexOf(E element, [int? start])

The last index of element in this list.

Searches the list backwards from index start to 0.

The first time an object o is encountered so that o == element, the index of o is returned.

final notes = <String>['do', 're', 'mi', 're'];
const startIndex = 2;
final index = notes.lastIndexOf('re', startIndex); // 1

If start is not provided, this method searches from the end of the list.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.lastIndexOf('re'); // 3

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.lastIndexOf('fa'); // -1
Example
void main() {
  final letters = 'banana'.split('');
  print('last a: ${letters.lastIndexOf('a')}');
  print('last a at or before 4: ${letters.lastIndexOf('a', 4)}');
  print('last z: ${letters.lastIndexOf('z')}');
}
Output
last a: 5
last a at or before 4: 3
last z: -1
clearmethod
void clear()

Removes all objects from this list; the length of the list becomes zero.

The list must be growable.

final numbers = <int>[1, 2, 3];
numbers.clear();
print(numbers.length); // 0
print(numbers); // []
Example
void main() {
  final inbox = ['m1', 'm2', 'm3'];
  inbox.clear();
  print('after clear: $inbox, isEmpty ${inbox.isEmpty}');
  final fixed = List.filled(2, 0);
  try {
    fixed.clear();
  } on UnsupportedError {
    print('fixed-length list cannot be cleared');
  }
}
Output
after clear: [], isEmpty true
fixed-length list cannot be cleared
insertmethod
void insert(int index, E element)

Inserts element at position index in this list.

This increases the length of the list by one and shifts all objects at or after the index towards the end of the list.

The list must be growable. The index value must be non-negative and no greater than length.

final numbers = <int>[1, 2, 3, 4];
const index = 2;
numbers.insert(index, 10);
print(numbers); // [1, 2, 10, 3, 4]
Example
void main() {
  final steps = ['mix', 'bake'];
  steps.insert(0, 'preheat');
  steps.insert(2, 'pour');
  steps.insert(steps.length, 'cool'); // index == length appends
  print('steps: $steps');
}
Output
steps: [preheat, mix, pour, bake, cool]
insertAllmethod
void insertAll(int index, Iterable<E> iterable)

Inserts all objects of iterable at position index in this list.

This increases the length of the list by the length of iterable and shifts all later objects towards the end of the list.

The list must be growable. The index value must be non-negative and no greater than length.

final numbers = <int>[1, 2, 3, 4];
final insertItems = [10, 11];
numbers.insertAll(2, insertItems);
print(numbers); // [1, 2, 10, 11, 3, 4]
Example
void main() {
  final xs = [1, 5];
  xs.insertAll(1, [2, 3, 4]);
  print('filled gap: $xs');
  xs.insertAll(0, [-1, 0]);
  print('prepended:  $xs');
}
Output
filled gap: [1, 2, 3, 4, 5]
prepended:  [-1, 0, 1, 2, 3, 4, 5]
setAllmethod
void setAll(int index, Iterable<E> iterable)

Overwrites elements with the objects of iterable.

The elements of iterable are written into this list, starting at position index. This operation does not increase the length of the list.

The index must be non-negative and no greater than length.

The iterable must not have more elements than what can fit from index to length.

If iterable is based on this list, its values may change during the setAll operation.

final list = <String>['a', 'b', 'c', 'd'];
list.setAll(1, ['bee', 'sea']);
print(list); // [a, bee, sea, d]
Example
void main() {
  final board = List.filled(6, '-');
  board.setAll(2, ['X', 'O', 'X']);
  print('board: ${board.join()}');
  try {
    board.setAll(5, ['A', 'B']); // would run past the end
  } on RangeError {
    print('setAll past the end -> RangeError');
  }
}
Output
board: --XOX-
setAll past the end -> RangeError
removemethod
bool remove(Object? value)

Removes the first occurrence of value from this list.

Returns true if value was in the list, false otherwise. The list must be growable.

final parts = <String>['head', 'shoulders', 'knees', 'toes'];
final retVal = parts.remove('head'); // true
print(parts); // [shoulders, knees, toes]

The method has no effect if value was not in the list.

final parts = <String>['shoulders', 'knees', 'toes'];
// Note: 'head' has already been removed.
final retVal = parts.remove('head'); // false
print(parts); // [shoulders, knees, toes]
Example
void main() {
  final tags = ['red', 'blue', 'red'];
  print('remove red: ${tags.remove('red')} -> $tags'); // only the first
  print('remove green: ${tags.remove('green')} -> $tags');
}
Output
remove red: true -> [blue, red]
remove green: false -> [blue, red]
removeAtmethod
E removeAt(int index)

Removes the object at position index from this list.

This method reduces the length of this by one and moves all later objects down by one position.

Returns the removed value.

The index must be in the range 0 ≤ index < length. The list must be growable.

final parts = <String>['head', 'shoulder', 'knees', 'toes'];
final retVal = parts.removeAt(2); // knees
print(parts); // [head, shoulder, toes]
Example
void main() {
  final xs = [10, 20, 30, 40];
  print('removeAt(1) -> ${xs.removeAt(1)}, list $xs');
  print('removeLast() -> ${xs.removeLast()}, list $xs');
  print('remove(10) -> ${xs.remove(10)}, list $xs');
}
Output
removeAt(1) -> 20, list [10, 30, 40]
removeLast() -> 40, list [10, 30]
remove(10) -> true, list [30]
E removeLast()

Removes and returns the last object in this list.

The list must be growable and non-empty.

final parts = <String>['head', 'shoulder', 'knees', 'toes'];
final retVal = parts.removeLast(); // toes
print(parts); // [head, shoulder, knees]
Example
void main() {
  final stack = [1, 2, 3];
  print('pop: ${stack.removeLast()}, stack $stack');
  print('pop: ${stack.removeLast()}, stack $stack');
  stack.removeLast();
  try {
    stack.removeLast();
  } on RangeError {
    print('empty -> RangeError');
  }
}
Output
pop: 3, stack [1, 2]
pop: 2, stack [1]
empty -> RangeError
void removeWhere(bool test(E element))

Removes all objects from this list that satisfy test.

An object o satisfies test if test(o) is true.

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.removeWhere((item) => item.length == 3);
print(numbers); // [three, four]

The list must be growable.

Example
void main() {
  final xs = List.generate(10, (i) => i);
  xs.removeWhere((x) => x.isOdd);
  print('without odd numbers: $xs');
  xs.retainWhere((x) => x > 2);
  print('kept > 2:            $xs');
}
Output
without odd numbers: [0, 2, 4, 6, 8]
kept > 2:            [4, 6, 8]
void retainWhere(bool test(E element))

Removes all objects from this list that fail to satisfy test.

An object o satisfies test if test(o) is true.

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.retainWhere((item) => item.length == 3);
print(numbers); // [one, two]

The list must be growable.

Example
void main() {
  final nums = List.generate(12, (i) => i + 1);
  nums.retainWhere((n) => n % 3 == 0);
  print('multiples of 3: $nums');
}
Output
multiples of 3: [3, 6, 9, 12]
sublistmethod
List<E> sublist(int start, [int? end])

Returns a new list containing the elements between start and end.

The new list is a List<E> containing the elements of this list at positions greater than or equal to start and less than end in the same order as they occur in this list.

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
print(colors.sublist(1, 3)); // [green, blue]

If end is omitted, it defaults to the length of this list.

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
print(colors.sublist(3)); // [orange, pink]

The start and end positions must satisfy the relations 0 ≤ start ≤ end ≤ length. If end is equal to start, then the returned list is empty.

Example
void main() {
  final xs = ['a', 'b', 'c', 'd', 'e'];
  print('sublist(1, 3): ${xs.sublist(1, 3)}');
  print('sublist(3):    ${xs.sublist(3)}');
  print('getRange(0, 2): ${xs.getRange(0, 2).toList()}');
}
Output
sublist(1, 3): [b, c]
sublist(3):    [d, e]
getRange(0, 2): [a, b]
getRangemethod
Iterable<E> getRange(int start, int end)

Creates an Iterable that iterates over a range of elements.

The returned iterable iterates over the elements of this list with positions greater than or equal to start and less than end.

The provided range, start and end, must be valid at the time of the call. A range from start to end is valid if 0 ≤ start ≤ end ≤ length. An empty range (with end == start) is valid.

The returned Iterable behaves like skip(start).take(end - start). That is, it does not break if this list changes size, it just ends early if it reaches the end of the list early (if end, or even start, becomes greater than length).

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
final firstRange = colors.getRange(0, 3);
print(firstRange.join(', ')); // red, green, blue

final secondRange = colors.getRange(2, 5);
print(secondRange.join(', ')); // blue, orange, pink
Example
void main() {
  final letters = 'abcdefg'.split('');
  final mid = letters.getRange(2, 5);
  print('range 2..5: ${mid.toList()}');
  print('joined:     ${mid.join()}');
}
Output
range 2..5: [c, d, e]
joined:     cde
setRangemethod
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0])

Writes some elements of iterable into a range of this list.

Copies the objects of iterable, skipping skipCount objects first, into the range from start, inclusive, to end, exclusive, of this list.

final list1 = <int>[1, 2, 3, 4];
final list2 = <int>[5, 6, 7, 8, 9];
// Copies the 4th and 5th items in list2 as the 2nd and 3rd items
// of list1.
const skipCount = 3;
list1.setRange(1, 3, list2, skipCount);
print(list1); // [1, 8, 9, 4]

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ start ≤ end ≤ length. An empty range (with end == start) is valid.

The iterable must have enough objects to fill the range from start to end after skipping skipCount objects.

If iterable is this list, the operation correctly copies the elements originally in the range from skipCount to skipCount + (end - start) to the range start to end, even if the two ranges overlap.

If iterable depends on this list in some other way, no guarantees are made.

Example
void main() {
  final xs = List.filled(7, 0);
  xs.setRange(1, 4, [7, 8, 9]);
  print('setRange(1,4): $xs');
  xs.setRange(4, 6, [1, 2, 3, 4], 2); // skip the first 2 source items
  print('with skip 2:   $xs');
}
Output
setRange(1,4): [0, 7, 8, 9, 0, 0, 0]
with skip 2:   [0, 7, 8, 9, 3, 4, 0]
void removeRange(int start, int end)

Removes a range of elements from the list.

Removes the elements with positions greater than or equal to start and less than end, from the list. This reduces the list's length by end - start.

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ start ≤ end ≤ length. An empty range (with end == start) is valid.

The list must be growable.

final numbers = <int>[1, 2, 3, 4, 5];
numbers.removeRange(1, 4);
print(numbers); // [1, 5]
Example
void main() {
  final xs = [0, 1, 2, 3, 4, 5, 6];
  xs.removeRange(2, 5);
  print('removed 2..5: $xs');
}
Output
removed 2..5: [0, 1, 5, 6]
fillRangemethod
void fillRange(int start, int end, [E? fillValue])

Overwrites a range of elements with fillValue.

Sets the positions greater than or equal to start and less than end, to fillValue.

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ start ≤ end ≤ length. An empty range (with end == start) is valid.

If the element type is not nullable, the fillValue must be provided and must be non-null.

Example:

final words = List.filled(5, 'old');
print(words); // [old, old, old, old, old]
words.fillRange(1, 3, 'new');
print(words); // [old, new, new, old, old]
Example
void main() {
  final xs = List.filled(8, 0);
  xs.fillRange(2, 5, 1);
  print('fillRange: $xs');
  xs.setRange(5, 8, [7, 8, 9]);
  print('setRange:  $xs');
}
Output
fillRange: [0, 0, 1, 1, 1, 0, 0, 0]
setRange:  [0, 0, 1, 1, 1, 7, 8, 9]
void replaceRange(int start, int end, Iterable<E> replacements)

Replaces a range of elements with the elements of replacements.

Removes the objects in the range from start to end, then inserts the elements of replacements at start.

final numbers = <int>[1, 2, 3, 4, 5];
final replacements = [6, 7];
numbers.replaceRange(1, 4, replacements);
print(numbers); // [1, 6, 7, 5]

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ start ≤ end ≤ length. An empty range (with end == start) is valid.

The operation list.replaceRange(start, end, replacements) is roughly equivalent to:

final numbers = <int>[1, 2, 3, 4, 5];
numbers.removeRange(1, 4);
final replacements = [6, 7];
numbers.insertAll(1, replacements);
print(numbers); // [1, 6, 7, 5]

But may be more efficient.

The list must be growable. This method does not work on fixed-length lists, even when replacements has the same number of elements as the replaced range. In that case use setRange instead.

Example
void main() {
  final words = ['I', 'like', 'cold', 'tea'];
  words.replaceRange(2, 3, ['hot', 'green']); // replacement may differ in length
  print(words.join(' '));
  words.replaceRange(0, 2, []);
  print(words.join(' '));
}
Output
I like hot green tea
hot green tea
asMapmethod
Map<int, E> asMap()

An unmodifiable Map view of this list.

The map uses the indices of this list as keys and the corresponding objects as values. The Map.keys Iterable iterates the indices of this list in numerical order.

var words = <String>['fee', 'fi', 'fo', 'fum'];
var map = words.asMap();  // {0: fee, 1: fi, 2: fo, 3: fum}
map.keys.toList(); // [0, 1, 2, 3]
Example
void main() {
  final fruit = ['apple', 'pear', 'plum'];
  final m = fruit.asMap();
  print('asMap: $m');
  m.forEach((i, f) => print('#$i $f'));
}
Output
asMap: {0: apple, 1: pear, 2: plum}
#0 apple
#1 pear
#2 plum

Operators

operator []operator
E operator [](int index)

The object at the given index in the list.

The index must be a valid index of this list, which means that index must be non-negative and less than length.

Example
void main() {
  final primes = [2, 3, 5, 7, 11];
  print('primes[0] = ${primes[0]}');
  print('primes[4] = ${primes[4]}');
  print('last via index: ${primes[primes.length - 1]}');
  try {
    primes[5];
  } on RangeError {
    print('primes[5] -> RangeError');
  }
}
Output
primes[0] = 2
primes[4] = 11
last via index: 11
primes[5] -> RangeError
operator []=operator
void operator []=(int index, E value)

Sets the value at the given index in the list to value.

The index must be a valid index of this list, which means that index must be non-negative and less than length.

Example
void main() {
  final grid = List.filled(5, 0);
  for (var i = 0; i < grid.length; i++) {
    grid[i] = i * i;
  }
  print('squares: $grid');
  grid[2] += 100;
  print('grid[2] += 100: $grid');
}
Output
squares: [0, 1, 4, 9, 16]
grid[2] += 100: [0, 1, 104, 9, 16]
operator +operator
List<E> operator +(List<E> other)

Returns the concatenation of this list and other.

Returns a new list containing the elements of this list followed by the elements of other.

The default behavior is to return a normal growable list. Some list types may choose to return a list of the same type as themselves (see [Uint8List.+]);

Example
void main() {
  final a = [1, 2], b = [3, 4];
  print('a + b:   ${a + b}');
  print('spread:  ${[...a, 0, ...b]}');
  print('if/for:  ${[for (final x in a) x * 10, if (b.length > 1) 99]}');
}
Output
a + b:   [1, 2, 3, 4]
spread:  [1, 2, 0, 3, 4]
if/for:  [10, 20, 99]
operator ==operator
bool operator ==(Object other)

Whether this list is equal to other.

Lists are, by default, only equal to themselves. Even if other is also a list, the equality comparison does not compare the elements of the two lists.

Example
void main() {
  final a = [1, 2, 3];
  final b = [1, 2, 3];
  print('a == b:      ${a == b}'); // identity, not contents
  print('a == a:      ${a == a}');
  bool sameItems(List x, List y) =>
      x.length == y.length && Iterable.generate(x.length).every((i) => x[i] == y[i]);
  print('same items:  ${sameItems(a, b)}');
  print('const lists: ${identical(const [1, 2], const [1, 2])}');
}
Output
a == b:      false
a == a:      true
same items:  true
const lists: true
class

Map

abstract interface class Map<K, V>

A collection of key/value pairs, from which you retrieve a value using its associated key.

There is a finite number of keys in the map, and each key has exactly one value associated with it.

Maps, and their keys and values, can be iterated. The order of iteration is defined by the individual type of map. Examples:

  • The plain HashMap is unordered (no order is guaranteed),
  • The LinkedHashMap iterates in key insertion order,
  • And a sorted map like SplayTreeMap iterates the keys in sorted order.

It is generally not allowed to modify the map (add or remove keys) while an operation is being performed on the map, for example in functions called during a forEach call. Modifying the map while iterating the keys or values may also break the iteration.

It is generally not allowed to modify the equality of keys (and thus not their hashcode) while they are in the map. Some specialized subtypes may be more permissive, in which case they should document this behavior.

Key equality must be an equality relation. If the key stored in a map and the key used for lookup do not agree on whether the two are equal, so equality is not symmetric, then lookup behavior is unspecified.

Example
void main() {
  final m = <String, List<int>>{};
  for (final n in [1, 2, 3, 4, 5, 6]) {
    (m[n.isEven ? 'even' : 'odd'] ??= []).add(n);
  }
  print(m);
  print('length ${m.length}, isEmpty ${m.isEmpty}');
}
Output
{odd: [1, 3, 5], even: [2, 4, 6]}
length 2, isEmpty false

Constructors

Mapfactory
external factory Map()

Creates an empty LinkedHashMap.

This constructor is equivalent to the non-const map literal <K, V>{}.

A LinkedHashMap requires the keys to implement compatible operator== and hashCode. It iterates in key insertion order.

Example
void main() {
  final ages = Map<String, int>();
  ages['Ada'] = 36;
  ages['Alan'] = 41;
  ages['Ada'] = 37;
  print('map: $ages');
  print('keeps insertion order: ${ages.keys.toList()}');
  print('same as a literal: ${ages.runtimeType == <String, int>{}.runtimeType}');
}
Output
map: {Ada: 37, Alan: 41}
keeps insertion order: [Ada, Alan]
same as a literal: true
Map.fromfactory
factory Map.from(Map other) = LinkedHashMap<K, V>.from

Creates a LinkedHashMap with the same keys and values as other.

The keys must all be instances of K and the values of V. The other map itself can have any type, unlike for Map.of, and the key and value types are checked (and can fail) at run-time.

Prefer using Map.of when possible, and only use Map.from to create a new map with more precise types than the original, and when it's known that all the keys and values have those more precise types.

A LinkedHashMap requires the keys to implement compatible operator== and hashCode. It iterates in key insertion order.

final planets = <num, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars'};
final mapFrom = Map<int, String>.from(planets);
print(mapFrom); // {1: Mercury, 2: Venus, 3: Earth, 4: Mars}
Example
void main() {
  final Map<Object, Object> loose = {'a': 1, 'b': 2};
  // Map.from checks every entry against the new types at run time.
  final strict = Map<String, int>.from(loose);
  print('copy: $strict');
  strict['c'] = 3;
  print('original untouched: $loose');
}
Output
copy: {a: 1, b: 2}
original untouched: {a: 1, b: 2}
Map.offactory
factory Map.of(Map<K, V> other) = LinkedHashMap<K, V>.of

Creates a LinkedHashMap with the same keys and values as other.

A LinkedHashMap requires the keys to implement compatible operator== and hashCode, and it allows null as a key. It iterates in key insertion order.

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
final mapOf = Map<num, String>.of(planets);
print(mapOf); // {1: Mercury, 2: Venus, 3: Earth}
Example
void main() {
  final base = {'x': 1, 'y': 2};
  final copy = Map.of(base)..['z'] = 3;
  print('copy:     $copy');
  print('original: $base');
}
Output
copy:     {x: 1, y: 2, z: 3}
original: {x: 1, y: 2}
external factory Map.unmodifiable(Map<dynamic, dynamic> other)

Creates an unmodifiable hash-based map containing the entries of other.

The keys must all be instances of K and the values of V. The other map itself can have any type.

The map requires the keys to implement compatible operator== and hashCode. The created map iterates keys in a fixed order, preserving the order provided by other.

The resulting map behaves like the result of Map.from, except that the map returned by this constructor is not modifiable.

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
final unmodifiableMap = Map.unmodifiable(planets);
unmodifiableMap[4] = 'Mars'; // Throws
Example
void main() {
  final source = {'one': 1, 'two': 2};
  final frozen = Map<String, int>.unmodifiable(source);
  source['three'] = 3;
  print('frozen is a snapshot: $frozen');
  try {
    frozen['four'] = 4;
  } on UnsupportedError {
    print('writing throws UnsupportedError');
  }
}
Output
frozen is a snapshot: {one: 1, two: 2}
writing throws UnsupportedError
factory Map.unmodifiableOf(Map<K, V> other) = Map<K, V>.unmodifiable

Creates an unmodifiable hash-based map containing the entries of other.

The map requires the keys to implement compatible operator== and hashCode. The created map iterates keys in a fixed order, preserving the order provided by other.

The resulting map behaves like the result of Map.of, except that the map returned by this constructor is not modifiable.

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
final unmodifiableMap = Map.unmodifiableOf(planets);
unmodifiableMap[4] = 'Mars'; // Throws
Example
void main() {
  final frozen = Map<String, int>.unmodifiableOf({'a': 1, 'b': 2});
  print('frozen: $frozen, a = ${frozen['a']}');
  try {
    frozen.remove('a');
  } on UnsupportedError {
    print('remove throws UnsupportedError');
  }
}
Output
frozen: {a: 1, b: 2}, a = 1
remove throws UnsupportedError
factory Map.identity() = LinkedHashMap<K, V>.identity

Creates an identity map with the default implementation, LinkedHashMap.

An identity map uses identical for equality and identityHashCode for hash codes of keys instead of the intrinsic [Object.==] and Object.hashCode of the keys.

The map iterates in key insertion order.

Example
void main() {
  final a = [1, 2], b = [1, 2];
  // Keys compare by identity, not by ==.
  final byIdentity = Map<List<int>, String>.identity()
    ..[a] = 'first'
    ..[b] = 'second';
  print('identity map has ${byIdentity.length} keys');
  print('lookup with a: ${byIdentity[a]}, with b: ${byIdentity[b]}');
}
Output
identity map has 2 keys
lookup with a: first, with b: second
factory Map.fromIterable(Iterable iterable, {K key(dynamic element)?, V value(dynamic element)?}) = LinkedHashMap<K, V>.fromIterable

Creates a Map instance in which the keys and values are computed from the iterable.

For each element of the iterable, a key/value pair is computed by applying key and value respectively to the element of the iterable.

Equivalent to the map literal:

<K, V>{for (var v in iterable) key(v): value(v)}

The literal is generally preferable because it allows for a more precise typing.

The example below creates a new map from a list of integers. The keys of map are the list values converted to strings, and the values of the map are the squares of the list values:

final numbers = <int>[1, 2, 3];
final map = Map<String, int>.fromIterable(numbers,
    key: (item) => item.toString(),
    value: (item) => item * item);
print(map); // {1: 1, 2: 4, 3: 9}

If no values are specified for key and value, the default is the identity function. In that case, the iterable element must be assignable to the key or value type of the created map.

In the following example, the keys and corresponding values of map are the list values directly:

final numbers = <int>[1, 2, 3];
final map = Map.fromIterable(numbers);
print(map); // {1: 1, 2: 2, 3: 3}

The keys computed by the source iterable do not need to be unique. The last occurrence of a key will overwrite the value of any previous occurrence.

The created map is a LinkedHashMap. A LinkedHashMap requires the keys to implement compatible operator== and hashCode. It iterates in key insertion order.

Example
void main() {
  final words = ['kiwi', 'fig', 'banana'];
  final lengths = Map<String, int>.fromIterable(words, value: (w) => (w as String).length);
  print('lengths: $lengths');
  final squares = Map<int, int>.fromIterable([1, 2, 3], key: (n) => n, value: (n) => n * n);
  print('squares: $squares');
}
Output
lengths: {kiwi: 4, fig: 3, banana: 6}
squares: {1: 1, 2: 4, 3: 9}
factory Map.fromIterables(Iterable<K> keys, Iterable<V> values) = LinkedHashMap<K, V>.fromIterables

Creates a map associating the given keys to the given values.

The map construction iterates over keys and values simultaneously, and adds an entry to the map for each pair of key and value.

final rings = <bool>[false, false, true, true];
final planets = <String>{'Earth', 'Mars', 'Jupiter', 'Saturn'};
final map = Map<String, bool>.fromIterables(planets, rings);
print(map); // {Earth: false, Mars: false, Jupiter: true, Saturn: true}

If keys contains the same object multiple times, the value of the last occurrence overwrites any previous value.

The two Iterables must have the same length.

The created map is a LinkedHashMap. A LinkedHashMap requires the keys to implement compatible operator== and hashCode. It iterates in key insertion order.

Example
void main() {
  final keys = ['x', 'y', 'z'];
  final values = [1, 2, 3];
  print(Map.fromIterables(keys, values));
  print(Map.fromEntries([MapEntry('k', 'v')]));
  print(Map.fromIterable([1, 2, 3], value: (x) => x * x));
}
Output
{x: 1, y: 2, z: 3}
{k: v}
{1: 1, 2: 4, 3: 9}
factory Map.fromEntries(Iterable<MapEntry<K, V>> entries)

Creates a new map and adds all entries.

Returns a new Map<K, V> where all entries of entries have been added in iteration order.

If multiple entries have the same key, later occurrences overwrite the value of the earlier ones.

Equivalent to the map literal:

<K, V>{for (var e in entries) e.key: e.value}

Example:

final moonCount = <String, int>{'Mercury': 0, 'Venus': 0, 'Earth': 1,
  'Mars': 2, 'Jupiter': 79, 'Saturn': 82, 'Uranus': 27, 'Neptune': 14};
final map = Map.fromEntries(moonCount.entries);
Example
void main() {
  final entries = [MapEntry('a', 1), MapEntry('b', 2)];
  print('fromEntries: ${Map.fromEntries(entries)}');
  // Swap keys and values of an existing map.
  final codes = {'red': 1, 'green': 2};
  print('swapped: ${Map.fromEntries(codes.entries.map((e) => MapEntry(e.value, e.key)))}');
}
Output
fromEntries: {a: 1, b: 2}
swapped: {1: red, 2: green}

Static

castFromstaticmethod
static Map<K2, V2> castFrom<K, V, K2, V2>(Map<K, V> source)

Adapts source to be a Map<K2, V2>.

Any time the set would produce a key or value that is not a K2 or V2, the access will throw.

Any time K2 key or V2 value is attempted added into the adapted map, the store will throw unless the key is also an instance of K and the value is also an instance of V.

If all accessed entries of source have K2 keys and V2 values, and if all entries added to the returned map have K keys and V values, then the returned map can be used as a Map<K2, V2>.

Methods which accept Object? as argument, like containsKey, remove and [operator []], will pass the argument directly to the this map's method without any checks.

Example
void main() {
  final Map<Object, Object> raw = {'a': 1, 'b': 2};
  final typed = Map.castFrom<Object, Object, String, int>(raw);
  print('typed: $typed, a + b = ${typed['a']! + typed['b']!}');
  typed['c'] = 3;
  print('a view: writes reach the source: $raw');
}
Output
typed: {a: 1, b: 2}, a + b = 3
a view: writes reach the source: {a: 1, b: 2, c: 3}

Properties

entriesgetter
Iterable<MapEntry<K, V>> get entries

The map entries of this Map.

Example
void main() {
  final ages = {'ada': 36, 'alan': 41, 'grace': 85};
  for (final e in ages.entries) {
    print('${e.key} is ${e.value}');
  }
  final oldest = ages.entries.reduce((a, b) => a.value > b.value ? a : b);
  print('oldest: ${oldest.key}');
}
Output
ada is 36
alan is 41
grace is 85
oldest: grace
keysgetter
Iterable<K> get keys

The keys of this Map.

The returned iterable has efficient length and contains operations, based on length and containsKey of the map.

The order of iteration is defined by the individual Map implementation, but must be consistent between changes to the map.

Modifying the map while iterating the keys may break the iteration.

Example
void main() {
  final m = {'b': 2, 'a': 1, 'c': 3};
  print('keys (insertion order): ${m.keys.toList()}');
  print('values:                 ${m.values.toList()}');
  print('sorted keys:            ${m.keys.toList()..sort()}');
}
Output
keys (insertion order): [b, a, c]
values:                 [2, 1, 3]
sorted keys:            [a, b, c]
valuesgetter
Iterable<V> get values

The values of this Map.

The values are iterated in the order of their corresponding keys. This means that iterating keys and values in parallel will provide matching pairs of keys and values.

The returned iterable has an efficient length method based on the length of the map. Its Iterable.contains method is based on == comparison.

Modifying the map while iterating the values may break the iteration.

lengthgetter
int get length

The number of key/value pairs in the map.

isEmptygetter
bool get isEmpty

Whether there is no key/value pair in the map.

bool get isNotEmpty

Whether there is at least one key/value pair in the map.

Methods

castmethod
Map<RK, RV> cast<RK, RV>()

Provides a view of this map as having RK keys and RV instances, if necessary.

If this map is already a Map<RK, RV>, it is returned unchanged.

If this set contains only keys of type RK and values of type RV, all read operations will work correctly. If any operation exposes a non-RK key or non-RV value, the operation will throw instead.

Entries added to the map must be valid for both a Map<K, V> and a Map<RK, RV>.

Methods which accept Object? as argument, like containsKey, remove and [operator []], will pass the argument directly to the this map's method without any checks. That means that you can do mapWithStringKeys.cast<int,int>.remove("a") successfully, even if it looks like it shouldn't have any effect.

Example
void main() {
  final Map<String, Object> raw = {'w': 3, 'h': 4};
  final dims = raw.cast<String, int>();
  print('area: ${dims['w']! * dims['h']!}');
  print('view of the same map: ${identical(raw, dims) ? 'same object' : 'a wrapper'}');
}
Output
area: 12
view of the same map: a wrapper
bool containsValue(Object? value)

Whether this map contains the given value.

Returns true if any of the values in the map are equal to value according to the == operator.

final moonCount = <String, int>{'Mercury': 0, 'Venus': 0, 'Earth': 1,
  'Mars': 2, 'Jupiter': 79, 'Saturn': 82, 'Uranus': 27, 'Neptune': 14};
final moons3 = moonCount.containsValue(3); // false
final moons82 = moonCount.containsValue(82); // true
Example
void main() {
  final stock = {'pens': 4, 'ink': 0};
  print('containsValue 0: ${stock.containsValue(0)}');
  print('containsValue 9: ${stock.containsValue(9)}');
  print('containsKey vs containsValue: ${stock.containsKey('ink')} / ${stock.containsValue('ink')}');
}
Output
containsValue 0: true
containsValue 9: false
containsKey vs containsValue: true / false
bool containsKey(Object? key)

Whether this map contains the given key.

Returns true if any of the keys in the map are equal to key according to the equality used by the map.

final moonCount = <String, int>{'Mercury': 0, 'Venus': 0, 'Earth': 1,
  'Mars': 2, 'Jupiter': 79, 'Saturn': 82, 'Uranus': 27, 'Neptune': 14};
final containsUranus = moonCount.containsKey('Uranus'); // true
final containsPluto = moonCount.containsKey('Pluto'); // false
Example
void main() {
  final m = {'a': 1, 'b': null};
  print('containsKey a: ${m.containsKey('a')}');
  print('containsKey b: ${m.containsKey('b')}, value ${m['b']}');
  print('containsKey z: ${m.containsKey('z')}, value ${m['z']}');
  print('containsValue 1: ${m.containsValue(1)}');
}
Output
containsKey a: true
containsKey b: true, value null
containsKey z: false, value null
containsValue 1: true
mapmethod
Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> convert(K key, V value))

Returns a new map where all entries of this map are transformed by the given convert function.

Example
void main() {
  final prices = {'tea': 3, 'cake': 5};
  final inCents = prices.map((k, v) => MapEntry(k.toUpperCase(), v * 100));
  print(inCents);
  final swapped = prices.map((k, v) => MapEntry(v, k));
  print(swapped);
}
Output
{TEA: 300, CAKE: 500}
{3: tea, 5: cake}
void addEntries(Iterable<MapEntry<K, V>> newEntries)

Adds all key/value pairs of newEntries to this map.

If a key of newEntries is already in this map, the corresponding value is overwritten.

The operation is equivalent to doing this[entry.key] = entry.value for each MapEntry of the iterable.

final planets = <int, String>{1: 'Mercury', 2: 'Venus',
  3: 'Earth', 4: 'Mars'};
final gasGiants = <int, String>{5: 'Jupiter', 6: 'Saturn'};
final iceGiants = <int, String>{7: 'Uranus', 8: 'Neptune'};
planets.addEntries(gasGiants.entries);
planets.addEntries(iceGiants.entries);
print(planets);
// {1: Mercury, 2: Venus, 3: Earth, 4: Mars, 5: Jupiter, 6: Saturn,
//  7: Uranus, 8: Neptune}
Example
void main() {
  final m = {'a': 1};
  m.addEntries([MapEntry('b', 2), MapEntry('a', 10)]);
  print('after addEntries: $m');
}
Output
after addEntries: {a: 10, b: 2}
updatemethod
V update(K key, V update(V value), {V ifAbsent()?})

Updates the value for the provided key.

Returns the new value associated with the key.

If the key is present, invokes update with the current value and stores the new value in the map.

If the key is not present and ifAbsent is provided, calls ifAbsent and adds the key with the returned value to the map.

If the key is not present, ifAbsent must be provided.

final planetsFromSun = <int, String>{1: 'Mercury', 2: 'unknown',
  3: 'Earth'};
// Update value for known key value 2.
planetsFromSun.update(2, (value) => 'Venus');
print(planetsFromSun); // {1: Mercury, 2: Venus, 3: Earth}

final largestPlanets = <int, String>{1: 'Jupiter', 2: 'Saturn',
  3: 'Neptune'};
// Key value 8 is missing from list, add it using [ifAbsent].
largestPlanets.update(8, (value) => 'New', ifAbsent: () => 'Mercury');
print(largestPlanets); // {1: Jupiter, 2: Saturn, 3: Neptune, 8: Mercury}
Example
void main() {
  final counts = <String, int>{};
  for (final w in 'the cat and the hat and the bat'.split(' ')) {
    counts.update(w, (n) => n + 1, ifAbsent: () => 1);
  }
  print(counts);
}
Output
{the: 3, cat: 1, and: 2, hat: 1, bat: 1}
updateAllmethod
void updateAll(V update(K key, V value))

Updates all values.

Iterates over all entries in the map and updates them with the result of invoking update.

final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
terrestrial.updateAll((key, value) => value.toUpperCase());
print(terrestrial); // {1: MERCURY, 2: VENUS, 3: EARTH}
Example
void main() {
  final scores = {'ada': 7, 'alan': 9};
  scores.updateAll((k, v) => v * 10);
  print(scores);
}
Output
{ada: 70, alan: 90}
void removeWhere(bool test(K key, V value))

Removes all entries of this map that satisfy the given test.

final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
terrestrial.removeWhere((key, value) => value.startsWith('E'));
print(terrestrial); // {1: Mercury, 2: Venus}
Example
void main() {
  final stock = {'apples': 3, 'pears': 0, 'plums': 7, 'figs': 0};
  stock.removeWhere((k, v) => v == 0);
  print('in stock: $stock');
}
Output
in stock: {apples: 3, plums: 7}
V putIfAbsent(K key, V ifAbsent())

Look up the value of key, or add a new entry if it isn't there.

Returns the value associated to key, if there is one. Otherwise calls ifAbsent to get a new value, associates key to that value, and then returns the new value.

That is, if the key is currently in the map, map.putIfAbsent(key, ifAbsent) is equivalent to map[key]. If the key is not currently in the map, it's instead equivalent to map[key] = ifAbsent (but without any guarantee that the [] and []= operators are actually called to achieve that effect).

final diameters = <num, String>{1.0: 'Earth'};
final otherDiameters = <double, String>{0.383: 'Mercury', 0.949: 'Venus'};

for (final item in otherDiameters.entries) {
  diameters.putIfAbsent(item.key, () => item.value);
}
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

// If the key already exists, the current value is returned.
final result = diameters.putIfAbsent(0.383, () => 'Random');
print(result); // Mercury
print(diameters); // {1.0: Earth, 0.383: Mercury, 0.949: Venus}

The ifAbsent function is allowed to modify the map, and if so, it behaves the same as the equivalent map[key] = ifAbsent.

Example
void main() {
  final cache = <String, int>{};
  int lookups = 0;
  int lengthOf(String s) => cache.putIfAbsent(s, () { lookups++; return s.length; });
  print(lengthOf('raya'));
  print(lengthOf('raya'));
  print(lengthOf('playground'));
  print('computed $lookups times, cache $cache');
}
Output
4
4
10
computed 2 times, cache {raya: 4, playground: 10}
addAllmethod
void addAll(Map<K, V> other)

Adds all key/value pairs of other to this map.

If a key of other is already in this map, its value is overwritten.

The operation is equivalent to doing this[key] = value for each key and associated value in other. It iterates over other, which must therefore not change during the iteration.

final planets = <int, String>{1: 'Mercury', 2: 'Earth'};
planets.addAll({5: 'Jupiter', 6: 'Saturn'});
print(planets); // {1: Mercury, 2: Earth, 5: Jupiter, 6: Saturn}
Example
void main() {
  final defaults = {'theme': 'light', 'size': 'm'};
  final user = {'size': 'l'};
  final settings = {...defaults}..addAll(user);
  print('defaults + user: $settings');
}
Output
defaults + user: {theme: light, size: l}
removemethod
V? remove(Object? key)

Removes key and its associated value, if present, from the map.

Returns the value associated with key before it was removed. Returns null if key was not in the map.

Note that some maps allow null as a value, so a returned null value doesn't always mean that the key was absent.

final terrestrial = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
final removedValue = terrestrial.remove(2); // Venus
print(terrestrial); // {1: Mercury, 3: Earth}
Example
void main() {
  final m = {'a': 1, 'b': 2};
  print('remove a -> ${m.remove('a')}, map $m');
  print('remove z -> ${m.remove('z')}, map $m');
}
Output
remove a -> 1, map {b: 2}
remove z -> null, map {b: 2}
clearmethod
void clear()

Removes all entries from the map.

After this, the map is empty.

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Earth'};
planets.clear(); // {}
Example
void main() {
  final m = {'a': 1, 'b': 2};
  m.clear();
  print('after clear: $m, isEmpty ${m.isEmpty}');
}
Output
after clear: {}, isEmpty true
forEachmethod
void forEach(void action(K key, V value))

Applies action to each key/value pair of the map.

Calling action must not add or remove keys from the map.

final planetsByMass = <num, String>{0.81: 'Venus', 1: 'Earth',
  0.11: 'Mars', 17.15: 'Neptune'};

planetsByMass.forEach((key, value) {
  print('$key: $value');
  // 0.81: Venus
  // 1: Earth
  // 0.11: Mars
  // 17.15: Neptune
});
Example
void main() {
  final prices = {'tea': 3, 'cake': 5};
  var total = 0;
  prices.forEach((item, price) {
    print('$item costs $price');
    total += price;
  });
  print('total: $total');
}
Output
tea costs 3
cake costs 5
total: 8

Operators

operator []operator
V? operator [](Object? key)

The value for the given key, or null if key is not in the map.

Some maps allow null as a value. For those maps, a lookup using this operator cannot distinguish between a key not being in the map, and the key being there with a null value. Methods like containsKey or putIfAbsent can be used if the distinction is important.

Example
void main() {
  final m = {'a': 1, 'b': null};
  print("m['a'] = ${m['a']}");
  print("m['b'] = ${m['b']} (stored null), containsKey: ${m.containsKey('b')}");
  print("m['z'] = ${m['z']} (missing), containsKey: ${m.containsKey('z')}");
}
Output
m['a'] = 1
m['b'] = null (stored null), containsKey: true
m['z'] = null (missing), containsKey: false
operator []=operator
void operator []=(K key, V value)

Associates the key with the given value.

If the key was already in the map, its associated value is changed. Otherwise the key/value pair is added to the map.

Example
void main() {
  final counts = <String, int>{};
  for (final w in 'the cat and the hat'.split(' ')) {
    counts[w] = (counts[w] ?? 0) + 1;
  }
  print('word counts: $counts');
}
Output
word counts: {the: 2, cat: 1, and: 1, hat: 1}
final class MapEntry<K, V>

A key/value pair representing an entry in a Map.

The Map interface contains various methods that can inspect or modify the map based on entry objects.

final map = {'1': 'A', '2': 'B'};
map.addEntries([
 MapEntry('3', 'C'),
 MapEntry('4', 'D'),
]);
print(map); // {1: A, 2: B, 3: C, 4: D}

Do not extend or implement the MapEntry class. If the Raya language introduces value types, the MapEntry class will be changed to such a type, and will likely no longer be able to be implemented or extended by classes.

Example
void main() {
  final e = MapEntry('pi', 3.14159);
  print('key ${e.key}, value ${e.value}');
  print(e);
  final m = Map.fromEntries([e, const MapEntry('e', 2.71828)]);
  print(m);
}
Output
key pi, value 3.14159
MapEntry(pi: 3.14159)
{pi: 3.14159, e: 2.71828}

Constructors

MapEntryfactory
const factory MapEntry(K key, V value) = MapEntry<K, V>._

Creates an entry with key and value.

Example
void main() {
  const e = MapEntry('pi', 3.14159);
  print('key ${e.key}, value ${e.value}');
  final m = Map.fromEntries([e, const MapEntry('e', 2.71828)]);
  print('map: $m');
}
Output
key pi, value 3.14159
map: {pi: 3.14159, e: 2.71828}

Properties

keyfield
final K key

The key of the entry.

final map = {'theKey': 'theValue'}; // Map<String, String>
var entry = map.entries.first; // MapEntry<String, String>
print(entry.key); // 'theKey'
valuefield
final V value

The value associated to key in a map.

final map = {'theKey': 'theValue'}; // Map<String, String>
var entry = map.entries.first; // MapEntry<String, String>
print(entry.value); // 'theValue'

Methods

toStringmethod
String toString()

String representation intended for debugging only.

Not guaranteed to be stable over time.

Example
void main() {
  print(const MapEntry('a', 1).toString());
  print({'x': 1, 'y': 2}.entries.toList());
}
Output
MapEntry(a: 1)
[MapEntry(x: 1), MapEntry(y: 2)]
class

Null

final class Null

The reserved word null denotes an object that is the sole instance of this class.

The Null class is the only class which does not implement Object. It is a compile-time error for a class to attempt to extend or implement Null.

The language contains a number of specialized operators for working with null value. Examples:

e1!       // Throws if e1 is null.
e2 ?? e3  // Same as e2, unless e2 is null, then use value of e3
x ??= e4  // Same as x unless x is null, then same as `x = e4`.
e5?.foo() // call `foo` on e5, unless e5 is null.
[...? e6] // spreads e6 into the list literal, unless e6 is null.

Properties

hashCodegetter
external int get hashCode

Methods

toStringmethod
String toString()

Returns the string "null".

Example
void main() {
  Object? nothing;
  print('null.toString(): ${null.toString()}');
  print('interpolated: $nothing');
  print('length: ${null.toString().length}');
}
Output
null.toString(): null
interpolated: null
length: 4
class

num

sealed class num implements Comparable<num>

An integer or floating-point number.

It is a compile-time error for any type other than int or double to attempt to extend or implement num.

See also:

  • int: An integer number.
  • double: A double-precision floating point number.

Static

parsestaticmethod
static num parse(String input, [@deprecated num onError(String input)?])

Parses a string containing a number literal into a number.

The method first tries to read the input as integer (similar to int.parse without a radix). If that fails, it tries to parse the input as a double (similar to double.parse). If that fails, too, it throws a FormatException.

Rather than throwing and immediately catching the FormatException, instead use tryParse to handle a potential parsing error.

For any number n, this function satisfies identical(n, num.parse(n.toString)) (except when n is a NaN double with a payload).

The onError parameter is deprecated and will be removed. Instead of num.parse(string, (string) {... }), you should use `num.tryParse(string) ??

Examples:

var value = num.parse('2021'); // 2021
value = num.parse('3.14'); // 3.14
value = num.parse('  3.14 \xA0'); // 3.14
value = num.parse('0.'); // 0.0
value = num.parse('.0'); // 0.0
value = num.parse('-1.e3'); // -1000.0
value = num.parse('1234E+7'); // 12340000000.0
value = num.parse('+.12e-9'); // 1.2e-10
value = num.parse('-NaN'); // NaN
value = num.parse('0xFF'); // 255
value = num.parse(double.infinity.toString()); // Infinity
value = num.parse('1f'); // Throws.
Example
void main() {
  print('${num.parse('42')} is ${num.parse('42').runtimeType}');
  print('${num.parse('4.2')} is ${num.parse('4.2').runtimeType}');
  print('${num.parse('1e3')}');
  print('tryParse("x"): ${num.tryParse('x')}');
}
Output
42 is int
4.2 is double
1000.0
tryParse("x"): null
tryParsestaticmethod
static num? tryParse(String input)

Parses a string containing a number literal into a number.

Like parse, except that this function returns null for invalid inputs instead of throwing.

Examples:

var value = num.tryParse('2021'); // 2021
value = num.tryParse('3.14'); // 3.14
value = num.tryParse('  3.14 \xA0'); // 3.14
value = num.tryParse('0.'); // 0.0
value = num.tryParse('.0'); // 0.0
value = num.tryParse('-1.e3'); // -1000.0
value = num.tryParse('1234E+7'); // 12340000000.0
value = num.tryParse('+.12e-9'); // 1.2e-10
value = num.tryParse('-NaN'); // NaN
value = num.tryParse('0xFF'); // 255
value = num.tryParse(double.infinity.toString()); // Infinity
value = num.tryParse('1f'); // null
Example
void main() {
  for (final s in ['42', '-3.5', '1e3', '0x1F', ' 7 ', 'NaN', 'abc']) {
    final n = num.tryParse(s);
    print('${"'$s'".padRight(7)} -> $n (${n.runtimeType})');
  }
}
Output
'42'    -> 42 (int)
'-3.5'  -> -3.5 (double)
'1e3'   -> 1000.0 (double)
'0x1F'  -> 31 (int)
' 7 '   -> 7 (int)
'NaN'   -> NaN (double)
'abc'   -> null (Null)

Properties

hashCodegetter
int get hashCode

Returns a hash code for a numerical value.

The hash code is compatible with equality. It returns the same value for an int and a double with the same numerical value, and therefore the same value for the doubles zero and minus zero.

No guarantees are made about the hash code of NaN values.

isNaNgetter
bool get isNaN

Whether this number is a Not-a-Number value.

Is true if this number is the double.nan value or any other of the possible double NaN values. Is false if this number is an integer, a finite double or an infinite double (double.infinity or double.negativeInfinity).

All numbers satisfy exactly one of isInfinite, isFinite and isNaN.

Example
void main() {
  const x = 0.0 / 0.0;
  print('0/0 = $x, isNaN ${x.isNaN}');
  print('1/0 = ${1 / 0}, isInfinite ${(1 / 0).isInfinite}');
  print('-0.0 isNegative ${(-0.0).isNegative}');
  print('NaN == NaN: ${x == x}');
}
Output
0/0 = NaN, isNaN true
1/0 = Infinity, isInfinite true
-0.0 isNegative true
NaN == NaN: false
bool get isNegative

Whether this number is negative.

A number is negative if it's smaller than zero, or if it is the double -0.0. This precludes a NaN value like double.nan from being negative.

bool get isInfinite

Whether this number is positive infinity or negative infinity.

Only satisfied by double.infinity and double.negativeInfinity.

All numbers satisfy exactly one of isInfinite, isFinite and isNaN.

isFinitegetter
bool get isFinite

Whether this number is finite.

The only non-finite numbers are NaN values, positive infinity, and negative infinity. All integers are finite.

All numbers satisfy exactly one of isInfinite, isFinite and isNaN.

signgetter
num get sign

Negative one, zero or positive one depending on the sign and numerical value of this number.

The value minus one if this number is less than zero, plus one if this number is greater than zero, and zero if this number is equal to zero.

Returns NaN if this number is a double NaN value.

Returns a number of the same type as this number. For doubles, (-0.0).sign is -0.0.

The result satisfies:

n == n.sign * n.abs()

For all numbers n (except NaN, because NaN isn't == to itself).

Methods

compareTomethod
int compareTo(num other)

Compares this to other.

Returns a negative number if this is less than other, zero if they are equal, and a positive number if this is greater than other.

The ordering represented by this method is a total ordering of num values. All distinct doubles are non-equal, as are all distinct integers, but integers are equal to doubles if they have the same numerical value.

For doubles, the compareTo operation is different from the partial ordering given by [operator==], [operator<] and [operator>]. For example, IEEE doubles impose that 0.0 == -0.0 and all comparison operations on NaN return false.

This function imposes a complete ordering for doubles. When using compareTo, the following properties hold:

  • All NaN values are considered equal, and greater than any numeric value.
  • -0.0 is less than 0.0 (and the integer 0), but greater than any non-zero negative value.
  • Negative infinity is less than all other values and positive infinity is greater than all non-NaN values.
  • All other values are compared using their numeric value.

Examples:

print(1.compareTo(2)); // => -1
print(2.compareTo(1)); // => 1
print(1.compareTo(1)); // => 0

// The following comparisons yield different results than the
// corresponding comparison operators.
print((-0.0).compareTo(0.0));  // => -1
print(double.nan.compareTo(double.nan));  // => 0
print(double.infinity.compareTo(double.nan)); // => -1

// -0.0, and NaN comparison operators have rules imposed by the IEEE
// standard.
print(-0.0 == 0.0); // => true
print(double.nan == double.nan);  // => false
print(double.infinity < double.nan);  // => false
print(double.nan < double.infinity);  // => false
print(double.nan == double.infinity);  // => false
Example
void main() {
  print('1.compareTo(2)   = ${1.compareTo(2)}');
  print('2.compareTo(2.0) = ${2.compareTo(2.0)}');
  final xs = [3, 1.5, -2, 10];
  xs.sort((a, b) => a.compareTo(b));
  print('sorted: $xs');
}
Output
1.compareTo(2)   = -1
2.compareTo(2.0) = 0
sorted: [-2, 1.5, 3, 10]
remaindermethod
num remainder(num other)

The remainder of the truncating division of this by other.

As a consequence, the remainder r has the same sign as the dividend this.

The result is an int, as described by int.remainder, if both this number and other are integers, otherwise the result is a double.

Example:

print(5.remainder(3)); // 2
print(-5.remainder(3)); // -2
print(5.remainder(-3)); // 2
print(-5.remainder(-3)); // -2
Example
void main() {
  print('-7 % 3            = ${-7 % 3}');
  print('(-7).remainder(3) = ${(-7).remainder(3)}');
  print('7.5 % 2           = ${7.5 % 2}');
}
Output
-7 % 3            = 2
(-7).remainder(3) = -1
7.5 % 2           = 1.5
absmethod
num abs()

The absolute value of this number.

The absolute value is the value itself, if the value is non-negative, and -value if the value is negative.

Integer overflow may cause the result of -value to stay negative.

print((2).abs()); // 2
print((-2.5).abs()); // 2.5
Example
void main() {
  final List<num> xs = [-3, 2.5, -0.0, -7.25];
  for (final x in xs) print('$x.abs() = ${x.abs()}');
}
Output
-3.abs() = 3
2.5.abs() = 2.5
-0.0.abs() = 0.0
-7.25.abs() = 7.25
roundmethod
int round()

The integer closest to this number.

Rounds away from zero when there is no closest integer: (3.5).round == 4 and (-3.5).round == -4.

The number must be finite (see isFinite).

If the value is greater than the highest representable positive integer, the result is that highest positive integer. If the value is smaller than the highest representable negative integer, the result is that highest negative integer.

Example
void main() {
  for (final x in [2.5, 3.5, -2.5, 2.4, 2.6]) {
    print('$x: round ${x.round()}, floor ${x.floor()}, ceil ${x.ceil()}, truncate ${x.truncate()}');
  }
}
Output
2.5: round 3, floor 2, ceil 3, truncate 2
3.5: round 4, floor 3, ceil 4, truncate 3
-2.5: round -3, floor -3, ceil -2, truncate -2
2.4: round 2, floor 2, ceil 3, truncate 2
2.6: round 3, floor 2, ceil 3, truncate 2
floormethod
int floor()

The greatest integer no greater than this number.

Rounds fractional values towards negative infinity.

The number must be finite (see isFinite).

If the value is greater than the highest representable positive integer, the result is that highest positive integer. If the value is smaller than the highest representable negative integer, the result is that highest negative integer.

Example
void main() {
  for (final num x in [2.7, -2.7, 5, -0.5]) print('$x.floor() = ${x.floor()}');
}
Output
2.7.floor() = 2
-2.7.floor() = -3
5.floor() = 5
-0.5.floor() = -1
ceilmethod
int ceil()

The least integer no smaller than this.

Rounds fractional values towards positive infinity.

The number must be finite (see isFinite).

If the value is greater than the highest representable positive integer, the result is that highest positive integer. If the value is smaller than the highest representable negative integer, the result is that highest negative integer.

Example
void main() {
  for (final num x in [2.1, -2.1, 5, -0.5]) print('$x.ceil() = ${x.ceil()}');
  // Pages needed for 23 items, 10 per page:
  print('pages: ${(23 / 10).ceil()}');
}
Output
2.1.ceil() = 3
-2.1.ceil() = -2
5.ceil() = 5
-0.5.ceil() = 0
pages: 3
truncatemethod
int truncate()

The integer obtained by discarding any fractional digits from this.

Rounds fractional values towards zero.

The number must be finite (see isFinite).

If the value is greater than the highest representable positive integer, the result is that highest positive integer. If the value is smaller than the highest representable negative integer, the result is that highest negative integer.

Example
void main() {
  for (final num x in [2.7, -2.7, 9]) print('$x.truncate() = ${x.truncate()}  floor ${x.floor()}');
}
Output
2.7.truncate() = 2  floor 2
-2.7.truncate() = -2  floor -3
9.truncate() = 9  floor 9
double roundToDouble()

The double integer value closest to this value.

Rounds away from zero when there is no closest integer: (3.5).roundToDouble == 4 and (-3.5).roundToDouble == -4.

If this is already an integer valued double, including -0.0, or it is a non-finite double value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0, and -0.0 is therefore considered closer to negative numbers than 0.0. This means that for a value d in the range -0.5 < d < 0.0, the result is -0.0.

Example
void main() {
  for (final num x in [2.5, -2.5, 3.49, 7]) {
    print('$x.roundToDouble() = ${x.roundToDouble()}');
  }
}
Output
2.5.roundToDouble() = 3.0
-2.5.roundToDouble() = -3.0
3.49.roundToDouble() = 3.0
7.roundToDouble() = 7.0
double floorToDouble()

Returns the greatest double integer value no greater than this.

If this is already an integer valued double, including -0.0, or it is a non-finite double value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0. A number d in the range 0.0 < d < 1.0 will return 0.0.

Example
void main() {
  for (final num x in [2.7, -2.7, 4]) print('$x.floorToDouble() = ${x.floorToDouble()}');
}
Output
2.7.floorToDouble() = 2.0
-2.7.floorToDouble() = -3.0
4.floorToDouble() = 4.0
double ceilToDouble()

Returns the least double integer value no smaller than this.

If this is already an integer valued double, including -0.0, or it is a non-finite double value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0. A number d in the range -1.0 < d < 0.0 will return -0.0.

Example
void main() {
  for (final num x in [2.1, -2.1, 4]) print('$x.ceilToDouble() = ${x.ceilToDouble()}');
}
Output
2.1.ceilToDouble() = 3.0
-2.1.ceilToDouble() = -2.0
4.ceilToDouble() = 4.0
double truncateToDouble()

Returns the double integer value obtained by discarding any fractional digits from the double value of this.

If this is already an integer valued double, including -0.0, or it is a non-finite double value, the value is returned unmodified.

For the purpose of rounding, -0.0 is considered to be below 0.0. A number d in the range -1.0 < d < 0.0 will return -0.0, and in the range 0.0 < d < 1.0 it will return 0.0.

Example
void main() {
  for (final num x in [2.9, -2.9, 4]) print('$x.truncateToDouble() = ${x.truncateToDouble()}');
}
Output
2.9.truncateToDouble() = 2.0
-2.9.truncateToDouble() = -2.0
4.truncateToDouble() = 4.0
clampmethod
num clamp(num lowerLimit, num upperLimit)

Returns this num clamped to be in the range lowerLimit-upperLimit.

The comparison is done using compareTo and therefore takes -0.0 into account. This also implies that double.nan is treated as the maximal double value.

The arguments lowerLimit and upperLimit must form a valid range where lowerLimit.compareTo(upperLimit) <= 0.

Example:

var result = 10.5.clamp(5, 10.0); // 10.0
result = 0.75.clamp(5, 10.0); // 5
result = (-10).clamp(-5, 5.0); // -5
result = (-0.0).clamp(-5, 5.0); // -0.0
Example
void main() {
  print('15.clamp(0, 10)    = ${15.clamp(0, 10)}');
  print('(-3).clamp(0, 10)  = ${(-3).clamp(0, 10)}');
  print('0.75.clamp(0, 0.5) = ${0.75.clamp(0, 0.5)}');
}
Output
15.clamp(0, 10)    = 10
(-3).clamp(0, 10)  = 0
0.75.clamp(0, 0.5) = 0.5
toIntmethod
int toInt()

Truncates this num to an integer and returns the result as an int.

Equivalent to truncate.

Example
void main() {
  print('3.99.toInt()  = ${3.99.toInt()}');
  print('(-3.99).toInt() = ${(-3.99).toInt()}');
  print('7.toDouble()  = ${7.toDouble()}');
}
Output
3.99.toInt()  = 3
(-3.99).toInt() = -3
7.toDouble()  = 7.0
toDoublemethod
double toDouble()

This number as a double.

If an integer number is not precisely representable as a double, an approximation is returned.

Example
void main() {
  final num a = 7;
  final d = a.toDouble();
  print('7.toDouble() = $d (${d.runtimeType})');
  print('average of ints: ${[1, 2, 4].reduce((x, y) => x + y).toDouble() / 3}');
}
Output
7.toDouble() = 7.0 (double)
average of ints: 2.3333333333333335
String toStringAsFixed(int fractionDigits)

A decimal-point string-representation of this number.

Converts this number to a double before computing the string representation, as by toDouble.

If the absolute value of this is greater than or equal to 10^21, then this methods returns an exponential representation computed by this.toStringAsExponential. Otherwise the result is the closest string representation with exactly fractionDigits digits after the decimal point. If fractionDigits equals 0, then the decimal point is omitted.

The parameter fractionDigits must be an integer satisfying: 0 <= fractionDigits <= 20.

Examples:

1.toStringAsFixed(3);  // 1.000
(4321.12345678).toStringAsFixed(3);  // 4321.123
(4321.12345678).toStringAsFixed(5);  // 4321.12346
123456789012345.toStringAsFixed(3);  // 123456789012345.000
10000000000000000.toStringAsFixed(4); // 10000000000000000.0000
5.25.toStringAsFixed(0); // 5
Example
void main() {
  const x = 3.14159;
  print('toStringAsFixed(2):       ${x.toStringAsFixed(2)}');
  print('toStringAsFixed(0):       ${x.toStringAsFixed(0)}');
  print('toStringAsPrecision(3):   ${x.toStringAsPrecision(3)}');
  print('toStringAsExponential(2): ${12345.678.toStringAsExponential(2)}');
}
Output
toStringAsFixed(2):       3.14
toStringAsFixed(0):       3
toStringAsPrecision(3):   3.14
toStringAsExponential(2): 1.23e+4
String toStringAsExponential([int? fractionDigits])

An exponential string-representation of this number.

Converts this number to a double before computing the string representation.

If fractionDigits is given, then it must be an integer satisfying: 0 <= fractionDigits <= 20. In this case the string contains exactly fractionDigits after the decimal point. Otherwise, without the parameter, the returned string uses the shortest number of digits that accurately represent this number.

If fractionDigits equals 0, then the decimal point is omitted. Examples:

1.toStringAsExponential();       // 1e+0
1.toStringAsExponential(3);      // 1.000e+0
123456.toStringAsExponential();  // 1.23456e+5
123456.toStringAsExponential(3); // 1.235e+5
123.toStringAsExponential(0);    // 1e+2
Example
void main() {
  print('123456.toStringAsExponential()  = ${123456.toStringAsExponential()}');
  print('123456.toStringAsExponential(2) = ${123456.toStringAsExponential(2)}');
  print('0.00042.toStringAsExponential(1) = ${0.00042.toStringAsExponential(1)}');
}
Output
123456.toStringAsExponential()  = 1.23456e+5
123456.toStringAsExponential(2) = 1.23e+5
0.00042.toStringAsExponential(1) = 4.2e-4
String toStringAsPrecision(int precision)

A string representation with precision significant digits.

Converts this number to a double and returns a string representation of that value with exactly precision significant digits.

The parameter precision must be an integer satisfying: 1 <= precision <= 21.

Examples:

1.toStringAsPrecision(2);       // 1.0
1e15.toStringAsPrecision(3);    // 1.00e+15
1234567.toStringAsPrecision(3); // 1.23e+6
1234567.toStringAsPrecision(9); // 1234567.00
12345678901234567890.toStringAsPrecision(20); // 12345678901234567168
12345678901234567890.toStringAsPrecision(14); // 1.2345678901235e+19
0.00000012345.toStringAsPrecision(15); // 1.23450000000000e-7
0.0000012345.toStringAsPrecision(15);  // 0.00000123450000000000
Example
void main() {
  const x = 3.14159265;
  for (final p in [1, 3, 6]) print('pi to $p significant digits: ${x.toStringAsPrecision(p)}');
  print('123456.toStringAsPrecision(2) = ${123456.toStringAsPrecision(2)}');
}
Output
pi to 1 significant digits: 3
pi to 3 significant digits: 3.14
pi to 6 significant digits: 3.14159
123456.toStringAsPrecision(2) = 1.2e+5
toStringmethod
String toString()

The shortest string that correctly represents this number.

All doubles in the range 10^-6 (inclusive) to 10^21 (exclusive) are converted to their decimal representation with at least one digit after the decimal point. For all other doubles, except for special values like NaN or Infinity, this method returns an exponential representation (see toStringAsExponential).

Returns "NaN" for double.nan, "Infinity" for double.infinity, and "-Infinity" for double.negativeInfinity.

An int is converted to a decimal representation with no decimal point.

Examples:

(0.000001).toString();  // "0.000001"
(0.0000001).toString(); // "1e-7"
(111111111111111111111.0).toString();  // "111111111111111110000.0"
(100000000000000000000.0).toString();  // "100000000000000000000.0"
(1000000000000000000000.0).toString(); // "1e+21"
(1111111111111111111111.0).toString(); // "1.1111111111111111e+21"
1.toString(); // "1"
111111111111111111111.toString();  // "111111111111111110000"
100000000000000000000.toString();  // "100000000000000000000"
1000000000000000000000.toString(); // "1000000000000000000000"
1111111111111111111111.toString(); // "1111111111111111111111"
1.234e5.toString();   // 123400
1234.5e6.toString();  // 1234500000
12.345e67.toString(); // 1.2345e+68

Note: the conversion may round the output if the returned string is accurate enough to uniquely identify the input-number. For example the most precise representation of the double 9e59 equals "899999999999999918767229449717619953810131273674690656206848", but this method returns the shorter (but still uniquely identifying) "9e59".

Example
void main() {
  final List<num> xs = [42, 42.0, 0.1 + 0.2, 1e21, 1e-7, -0.0];
  for (final x in xs) print(x.toString());
}
Output
42
42.0
0.30000000000000004
1e+21
1e-7
-0.0

Operators

operator ==operator
bool operator ==(Object other)

Test whether this value is numerically equal to other.

If both operands are doubles, they are equal if they have the same representation, except that:

  • Zero and minus zero (0.0 and -0.0) are considered equal. They both have the numerical value zero.
  • NaN is not equal to anything, including NaN. If either operand is NaN, the result is always false.

If one operand is a double and the other is an int, they are equal if the double has an integer value (finite with no fractional part) and the numbers have the same numerical value.

If both operands are integers, they are equal if they have the same value.

Returns false if other is not a num.

Notice that the behavior for NaN is non-reflexive. This means that equality of double values is not a proper equality relation, as is otherwise required of operator==. Using NaN in, e.g. a HashSet will fail to work. The behavior is the standard IEEE-754 equality of doubles.

If you can avoid NaN values, the remaining doubles do have a proper equality relation, and can be used safely.

Use compareTo for a comparison that distinguishes zero and minus zero, and that considers NaN values as equal.

Example
void main() {
  print('1 == 1.0:        ${1 == 1.0}');
  print('0.1 + 0.2 == 0.3: ${0.1 + 0.2 == 0.3}');
  print('NaN == NaN:      ${double.nan == double.nan}');
  print('0.0 == -0.0:     ${0.0 == -0.0}');
}
Output
1 == 1.0:        true
0.1 + 0.2 == 0.3: false
NaN == NaN:      false
0.0 == -0.0:     true
operator +operator
num operator +(num other)

Adds other to this number.

The result is an int, as described by [int.+], if both this number and other is an integer, otherwise the result is a double.

Example
void main() {
  num a = 2, b = 0.5;
  print('2 + 3   = ${a + 3} (${(a + 3).runtimeType})');
  print('2 + 0.5 = ${a + b} (${(a + b).runtimeType})');
}
Output
2 + 3   = 5 (int)
2 + 0.5 = 2.5 (double)
operator -operator
num operator -(num other)

Subtracts other from this number.

The result is an int, as described by [int.-], if both this number and other is an integer, otherwise the result is a double.

Example
void main() {
  num a = 10;
  print('10 - 4   = ${a - 4}');
  print('10 - 2.5 = ${a - 2.5}');
  print('0.3 - 0.1 = ${0.3 - 0.1}');
}
Output
10 - 4   = 6
10 - 2.5 = 7.5
0.3 - 0.1 = 0.19999999999999998
operator *operator
num operator *(num other)

Multiplies this number by other.

The result is an int, as described by [int.*], if both this number and other are integers, otherwise the result is a double.

Example
void main() {
  num a = 6;
  print('6 * 7   = ${a * 7}');
  print('6 * 0.5 = ${a * 0.5}');
}
Output
6 * 7   = 42
6 * 0.5 = 3.0
operator %operator
num operator %(num other)

Euclidean modulo of this number by other.

Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs.

The Euclidean division is only defined for integers, but can be easily extended to work with doubles. In that case, q is still an integer, but r may have a non-integer value that still satisfies 0 <= r < |b|.

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

The result is an int, as described by [int.%], if both this number and other are integers, otherwise the result is a double.

Example:

print(5 % 3); // 2
print(-5 % 3); // 1
print(5 % -3); // 2
print(-5 % -3); // 1
Example
void main() {
  num a = -7;
  print('-7 % 3   = ${a % 3}  (always non-negative)');
  print('-7.remainder(3) = ${a.remainder(3)}');
  print('5.5 % 2  = ${5.5 % 2}');
}
Output
-7 % 3   = 2  (always non-negative)
-7.remainder(3) = -1
5.5 % 2  = 1.5
operator /operator
double operator /(num other)

Divides this number by other.

Example
void main() {
  num a = 7;
  print('7 / 2 = ${a / 2}  (always a double)');
  print('6 / 3 = ${6 / 3}');
  print('1 / 0 = ${1 / 0}');
}
Output
7 / 2 = 3.5  (always a double)
6 / 3 = 2.0
1 / 0 = Infinity
operator ~/operator
int operator ~/(num other)

Truncating division operator.

Performs truncating division of this number by other. Truncating division is division where a fractional result is converted to an integer by rounding towards zero.

If both operands are ints, then other must not be zero.

If either operand is a double, then the other operand is converted to a double before performing the division and truncation of the result. This means that the intermediate result of the double division must be a finite integer (not an infinity or double.nan).

Example
void main() {
  num a = 7;
  print('7 ~/ 2    = ${a ~/ 2}');
  print('-7 ~/ 2   = ${-7 ~/ 2}  (truncates toward zero)');
  print('7.9 ~/ 2  = ${7.9 ~/ 2}');
}
Output
7 ~/ 2    = 3
-7 ~/ 2   = -3  (truncates toward zero)
7.9 ~/ 2  = 3
operator -operator
num operator -()

The negation of this value.

The negation of a number is a number of the same kind (int or double) representing the negation of the numbers numerical value (the result of subtracting the number from zero), if that value exists.

Negating a double gives a number with the same magnitude as the original value (number.abs == (-number).abs), and the opposite sign (-(number.sign) == (-number).sign).

Negating an integer, -number, is equivalent to subtracting it from zero, 0 - number.

(Both properties generally also hold for the other type, but with a few edge case exceptions).

Example
void main() {
  num a = 5, b = -2.5;
  print('-a = ${-a}, -b = ${-b}');
  print('-0.0 is negative: ${(-0.0).isNegative}');
}
Output
-a = -5, -b = 2.5
-0.0 is negative: true
operator <operator
bool operator <(num other)

Whether this number is numerically smaller than other.

Returns true if this number is smaller than other. Returns false if this number is greater than or equal to other or if either value is a NaN value like double.nan.

Example
void main() {
  num a = 2, b = 2.0, c = 3.5;
  print('2 < 2.0: ${a < b}');
  print('2 < 3.5: ${a < c}');
  print('3.5 < 2: ${c < a}');
  print('NaN < 1: ${double.nan < 1}');
}
Output
2 < 2.0: false
2 < 3.5: true
3.5 < 2: false
NaN < 1: false
operator <=operator
bool operator <=(num other)

Whether this number is numerically smaller than or equal to other.

Returns true if this number is smaller than or equal to other. Returns false if this number is greater than other or if either value is a NaN value like double.nan.

Example
void main() {
  num a = 2, b = 2.0, c = 3.5;
  print('2 <= 2.0: ${a <= b}');
  print('2 <= 3.5: ${a <= c}');
  print('3.5 <= 2: ${c <= a}');
  print('NaN <= 1: ${double.nan <= 1}');
}
Output
2 <= 2.0: true
2 <= 3.5: true
3.5 <= 2: false
NaN <= 1: false
operator >operator
bool operator >(num other)

Whether this number is numerically greater than other.

Returns true if this number is greater than other. Returns false if this number is smaller than or equal to other or if either value is a NaN value like double.nan.

Example
void main() {
  num a = 2, b = 2.0, c = 3.5;
  print('2 > 2.0: ${a > b}');
  print('2 > 3.5: ${a > c}');
  print('3.5 > 2: ${c > a}');
  print('NaN > 1: ${double.nan > 1}');
}
Output
2 > 2.0: false
2 > 3.5: false
3.5 > 2: true
NaN > 1: false
operator >=operator
bool operator >=(num other)

Whether this number is numerically greater than or equal to other.

Returns true if this number is greater than or equal to other. Returns false if this number is smaller than other or if either value is a NaN value like double.nan.

Example
void main() {
  num a = 2, b = 2.0, c = 3.5;
  print('2 >= 2.0: ${a >= b}');
  print('2 >= 3.5: ${a >= c}');
  print('3.5 >= 2: ${c >= a}');
  print('NaN >= 1: ${double.nan >= 1}');
}
Output
2 >= 2.0: true
2 >= 3.5: false
3.5 >= 2: true
NaN >= 1: false
class

Object

class Object

The base class for all Raya objects except null.

Because Object is a root of the non-nullable Raya class hierarchy, every other non-Null Raya class is a subclass of Object.

When you define a class, you should consider overriding toString to return a string describing an instance of that class.

Constructors

Objectconstructor
const Object()

Creates a new Object instance.

Object instances have no meaningful state, and are only useful through their identity. An Object instance is equal to itself only.

Example
class Token {
  const Token();
}

void main() {
  final a = Object(), b = Object();
  print('two Objects equal: ${a == b}');
  print('identical to itself: ${identical(a, a)}');
  print('const instances are shared: ${identical(const Token(), const Token())}');
}
Output
two Objects equal: false
identical to itself: true
const instances are shared: true

Static

hashstaticmethod
static int hash(Object? object1, Object? object2, [Object? object3 = sentinelValue, Object? object4 = sentinelValue, Object? object5 = sentinelValue, Object? object6 = sentinelValue, Object? object7 = sentinelValue, Object? object8 = sentinelValue, Object? object9 = sentinelValue, Object? object10 = sentinelValue, Object? object11 = sentinelValue, Object? object12 = sentinelValue, Object? object13 = sentinelValue, Object? object14 = sentinelValue, Object? object15 = sentinelValue, Object? object16 = sentinelValue, Object? object17 = sentinelValue, Object? object18 = sentinelValue, Object? object19 = sentinelValue, Object? object20 = sentinelValue])

Creates a combined hash code for a number of objects.

The hash code is computed for all arguments that are actually supplied, even if they are null, by numerically combining the Object.hashCode of each argument.

Example:

class SomeObject {
  final Object a, b, c;
  SomeObject(this.a, this.b, this.c);
  bool operator ==(Object other) =>
      other is SomeObject && a == other.a && b == other.b && c == other.c;
  int get hashCode => Object.hash(a, b, c);
}

The computed value will be consistent when the function is called with the same arguments multiple times during the execution of a single program.

The hash value generated by this function is not guaranteed to be stable over different runs of the same program, or between code run in different isolates of the same program. The exact algorithm used may differ between different platforms, or between different versions of the platform libraries, and it may depend on values that change on each program execution.

The hashAll function gives the same result as this function when called with a collection containing the actual arguments to this function in the same order.

Example
class Point3 {
  final int x, y, z;
  const Point3(this.x, this.y, this.z);
  @override
  bool operator ==(Object o) => o is Point3 && o.x == x && o.y == y && o.z == z;
  @override
  int get hashCode => Object.hash(x, y, z);
}

void main() {
  final a = Point3(1, 2, 3), b = Point3(1, 2, 3);
  print('a == b: ${a == b}');
  print('same hash: ${a.hashCode == b.hashCode}');
  print('set size: ${{a, b, Point3(3, 2, 1)}.length}');
  print('hashAll matches: ${Object.hashAll([1, 2]) == Object.hashAll([1, 2])}');
}
Output
a == b: true
same hash: true
set size: 2
hashAll matches: true
hashAllstaticmethod
static int hashAll(Iterable<Object?> objects)

Creates a combined hash code for a sequence of objects.

The hash code is computed for elements in objects, even if they are null, by numerically combining the Object.hashCode of each element in iteration order.

The result of hashAll([o]) is not o.hashCode.

Example:

class SomeObject {
  final List<String> path;
  SomeObject(this.path);
  bool operator ==(Object other) {
    if (other is SomeObject) {
      if (path.length != other.path.length) return false;
      for (int i = 0; i < path.length; i++) {
        if (path[i] != other.path[i]) return false;
      }
      return true;
    }
    return false;
  }

  int get hashCode => Object.hashAll(path);
}

The computed value will be consistent when the function is called again with objects that have the same hash codes in the same order during an execution of a single program.

The hash value generated by this function is not guaranteed to be stable over different runs of the same program, or between code run in different isolates of the same program. The exact algorithm used may differ between different platforms, or between different versions of the platform libraries, and it may depend on values that change on each program execution.

Example
class Path {
  final List<String> parts;
  Path(this.parts);
  @override
  bool operator ==(Object o) => o is Path && o.parts.join('/') == parts.join('/');
  @override
  int get hashCode => Object.hashAll(parts);
}

void main() {
  final a = Path(['usr', 'lib']), b = Path(['usr', 'lib']), c = Path(['lib', 'usr']);
  print('equal paths, equal hashes: ${a == b && a.hashCode == b.hashCode}');
  print('order matters: ${Object.hashAll([1, 2]) == Object.hashAll([2, 1])}');
  print('set dedupes: ${{a, b, c}.length}');
}
Output
equal paths, equal hashes: true
order matters: false
set dedupes: 2
hashAllUnorderedstaticmethod
static int hashAllUnordered(Iterable<Object?> objects)

Creates a combined hash code for a collection of objects.

The hash code is computed for elements in objects, even if they are null, by numerically combining the Object.hashCode of each element in an order independent way.

The result of hashAllUnordered({o}) is not o.hashCode.

Example:

bool setEquals<T>(Set<T> set1, Set<T> set2) {
  var hashCode1 = Object.hashAllUnordered(set1);
  var hashCode2 = Object.hashAllUnordered(set2);
  if (hashCode1 != hashCode2) return false;
  // Compare elements ...
}

The computed value will be consistent when the function is called again with objects that have the same hash codes during an execution of a single program, even if the objects are not necessarily in the same order,

The hash value generated by this function is not guaranteed to be stable over different runs of the same program. The exact algorithm used may differ between different platforms, or between different versions of the platform libraries, and it may depend on values that change on each program execution.

Example
void main() {
  final h1 = Object.hashAllUnordered(['x', 'y', 'z']);
  final h2 = Object.hashAllUnordered(['z', 'x', 'y']);
  print('order ignored: ${h1 == h2}');
  print('ordered hash differs: ${Object.hashAll(['x', 'y', 'z']) == Object.hashAll(['z', 'x', 'y'])}');
}
Output
order ignored: true
ordered hash differs: false

Properties

hashCodegetter
external int get hashCode

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.

external Type get runtimeType

A representation of the runtime type of the object.

Methods

toStringmethod
external String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Example
class Point {
  final int x, y;
  Point(this.x, this.y);
  @override
  String toString() => 'Point($x, $y)';
}

void main() {
  print('custom: ${Point(1, 2)}');
  print('in a list: ${[Point(0, 0), Point(3, 4)]}');
  print('int: ${42.toString()}, bool: ${true.toString()}');
}
Output
custom: Point(1, 2)
in a list: [Point(0, 0), Point(3, 4)]
int: 42, bool: true
external dynamic noSuchMethod(Invocation invocation)

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.

Example
class Recorder {
  final calls = <String>[];
  @override
  dynamic noSuchMethod(Invocation inv) {
    if (inv.memberName == #greet) calls.add('greet(${inv.positionalArguments.join(', ')})');
    if (inv.memberName == #count) return calls.length;
    return null;
  }
}

void main() {
  final dynamic r = Recorder();
  r.greet('Ada');
  r.greet('Alan', 2);
  print('recorded: ${(r as Recorder).calls}');
  print('count: ${(r as dynamic).count}');
}
Output
recorded: [greet(Ada), greet(Alan, 2)]
count: 2

Operators

operator ==operator
external bool operator ==(Object other)

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 == o must be true.
  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.
  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must 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.

Example
class Money {
  final int cents;
  const Money(this.cents);
  @override
  bool operator ==(Object other) => other is Money && other.cents == cents;
  @override
  int get hashCode => cents.hashCode;
}

void main() {
  print('Money(5) == Money(5): ${Money(5) == Money(5)}');
  print('identical: ${identical(Money(5), Money(5))}');
  print('in a set: ${{Money(5), Money(5), Money(7)}.length} distinct');
}
Output
Money(5) == Money(5): true
identical: false
in a set: 2 distinct
class

Pattern

abstract interface class Pattern

An interface for basic searches within strings.

Methods

Iterable<Match> allMatches(String string, [int start = 0])

Matches this pattern against the string repeatedly.

If start is provided, matching will start at that index.

The returned iterable lazily finds non-overlapping matches of the pattern in the string. If a user only requests the first match, this function should not compute all possible matches.

The matches are found by repeatedly finding the first match of the pattern in the string, initially starting from start, and then from the end of the previous match (but always at least one position later than the start of the previous match, in case the pattern matches an empty substring).

RegExp exp = RegExp(r'(\w+)');
var str = 'Dash is a bird';
Iterable<Match> matches = exp.allMatches(str, 8);
for (final Match m in matches) {
  String match = m[0]!;
  print(match);
}

The output of the example is:

a
bird
Example
void main() {
  final Pattern digits = RegExp(r'\d+');
  print('numbers: ${digits.allMatches('a1 b22 c333').map((m) => m[0]).toList()}');
  final Pattern word = 'ab';
  print("'ab' in 'abcabab': ${word.allMatches('abcabab').map((m) => m.start).toList()}");
}
Output
numbers: [1, 22, 333]
'ab' in 'abcabab': [0, 3, 5]
Match? matchAsPrefix(String string, [int start = 0])

Matches this pattern against the start of string.

Returns a match if the pattern matches a substring of string starting at start, and null if the pattern doesn't match at that point.

The start must be non-negative and no greater than string.length.

final string = 'Dash is a bird';

var regExp = RegExp(r'bird');
var match = regExp.matchAsPrefix(string, 10); // Match found.

regExp = RegExp(r'bird');
match = regExp.matchAsPrefix(string); // null
Example
void main() {
  final Pattern p = RegExp(r'[a-z]+');
  print("at 0: ${p.matchAsPrefix('hello world')?[0]}");
  print("at 5: ${p.matchAsPrefix('hello world', 5)?[0]}");
  print("at 6: ${p.matchAsPrefix('hello world', 6)?[0]}");
  print("String pattern: ${'he'.matchAsPrefix('hello')?.end}");
}
Output
at 0: hello
at 5: null
at 6: world
String pattern: 2
class

Match

abstract interface class Match

A result from searching within a string.

A Match or an Iterable of Match objects is returned from the Pattern matching methods (Pattern.allMatches and Pattern.matchAsPrefix).

The following example finds all matches of a RegExp in a String and iterates through the returned iterable of Match objects.

final regExp = RegExp(r'(\w+)');
const string = 'Parse my string';
final matches = regExp.allMatches(string);
for (final m in matches) {
  String match = m[0]!;
  print(match);
}

The output of the example is:

Parse
my
string

Some patterns, regular expressions in particular, may record substrings that were part of the matching. These are called groups in the Match object. Some patterns may never have any groups, and their matches always have zero groupCount.

Properties

startgetter
int get start

The index in the string where the match starts.

endgetter
int get end

The index in the string after the last character of the match.

int get groupCount

Returns the number of captured groups in the match.

Some patterns may capture parts of the input that was used to compute the full match. This is the number of captured groups, which is also the maximal allowed argument to the group method.

inputgetter
String get input

The string on which this match was computed.

patterngetter
Pattern get pattern

The pattern used to search in input.

Methods

groupmethod
String? group(int group)

The string matched by the given group.

If group is 0, returns the entire match of the pattern.

The result may be null if the pattern didn't assign a value to it as part of this match.


final string = '[00:13.37] This is a chat message.';
final regExp = RegExp(r'^\[\s*(\d+):(\d+)\.(\d+)\]\s*(.*)$');
final match = regExp.firstMatch(string)!;
final message = jsonEncode(match.group(0)!); // '[00:13.37] This is a chat message.'
final hours = jsonEncode(match.group(1)!); // '00'
final minutes = jsonEncode(match.group(2)!); // '13'
final seconds = jsonEncode(match.group(3)!); // '37'
final text = jsonEncode(match.group(4)!); // 'This is a chat message.'
Example
void main() {
  final m = RegExp(r'(\w+)@(\w+)\.com').firstMatch('mail ada@example.com now')!;
  print('group(0): ${m.group(0)}');
  print('group(1): ${m.group(1)}');
  print('group(2): ${m.group(2)}');
  print('groups([1, 2]): ${m.groups([1, 2])}');
  print('groupCount: ${m.groupCount}, start ${m.start}, end ${m.end}');
}
Output
group(0): ada@example.com
group(1): ada
group(2): example
groups([1, 2]): [ada, example]
groupCount: 2, start 5, end 20
groupsmethod
List<String?> groups(List<int> groupIndices)

A list of the groups with the given indices.

The list contains the strings returned by group for each index in groupIndices.


final string = '[00:13.37] This is a chat message.';
final regExp = RegExp(r'^\[\s*(\d+):(\d+)\.(\d+)\]\s*(.*)$');
final match = regExp.firstMatch(string)!;
final message = jsonEncode(match.groups([1, 2, 3, 4]));
// ['00','13','37','This is a chat message.']
Example
void main() {
  final m = RegExp(r'(\d{4})-(\d{2})-(\d{2})').firstMatch('due 2026-11-29')!;
  print('groups([1, 2, 3]): ${m.groups([1, 2, 3])}');
  print('groups([3, 1]):    ${m.groups([3, 1])}');
}
Output
groups([1, 2, 3]): [2026, 11, 29]
groups([3, 1]):    [29, 2026]

Operators

operator []operator
String? operator [](int group)

The string matched by the given group.

If group is 0, returns the match of the pattern.

Short alias for Match.group.

Example
void main() {
  final m = RegExp(r'(\w+)@(\w+)\.com').firstMatch('mail ada@example.com now')!;
  print('m[0] = ${m[0]}');
  print('m[1] = ${m[1]}, m[2] = ${m[2]}');
  final opt = RegExp(r'a(b)?').firstMatch('a')!;
  print('unmatched optional group: ${opt[1]}');
}
Output
m[0] = ada@example.com
m[1] = ada, m[2] = example
unmatched optional group: null
class

Record

abstract final class Record

A record value.

The Record class is a supertype of all record types, but is not itself the runtime type of any object instances (it's an abstract class). All objects that implement Record has a record type as their runtime type.

A record value, described by a record type, consists of a number of fields, which are each either positional or named.

Record values and record types are written similarly to argument lists and simplified function type parameter lists (no required modifier allowed, or needed, since record fields are never optional). Example:

(int, String, {bool isValid}) triple = (1, "one", isValid: true);

Is syntactically similar to

typedef F = void Function(int, String, {bool isValid});
void callIt(F f) => f(1, "one", isValid: true);

Every record and record type has a shape, given by the number of positional fields and the names of named fields. For example:

(double value, String name, {String isValid}) another = (
     3.14, "Pi", isValid: "real");

Is another record declaration with the same shape (two positional fields, one named field named isValid), but with a different type. The names written on the positional fields are entirely for documentation purposes, they have no effect on the program (same as names on positional parameters in function types, like typedef F = int Function(int value);, where the identifier value has no effect).

Record values are mainly destructured using patterns, like:

switch (triple) {
  case (int value, String name, isValid: bool ok): // ....
}

The individual fields can also be accessed using named getters, using $1, $2, etc. for positional fields, and the names themselves for named fields.

int value = triple.$1;
String name = triple.$2;
bool ok = triple.isValid;

Because of that, some identifiers cannot be used as names of named fields:

  • The names of Object members: hashCode, runtimeType, toString and noSuchMethod.
  • The name of a positional getter in the same record, so (0, $1: 0) is invalid, but (0, $2: 0) is valid, since there is no positional field with getter $2 in that record shape. (It'll still be confusing, and should be avoided in practice.)
  • Also, no name starting with an underscore, _, is allowed. Field names cannot be library private.

The run-time type of a record object is a record type, and as such, a subtype of Record, and transitively of Object and its supertypes.

Record values do not have a persistent identical behavior. A reference to a record object can change at any time to a reference to another record object with the same shape and field values.

Other than that, a record type can only be a subtype of another record type with the same shape, and only if the former record type's field types are subtypes of the other record type's corresponding field types. That is, (int, String, {bool isValid}) is a subtype of (num, String, {Object isValid}), because they have the same shape, and the field types are pointwise subtypes. Record types with different shapes are unrelated to each other.

Example
(int, int) divmod(int a, int b) => (a ~/ b, a % b);

({double min, double max}) range(List<double> xs) =>
    (min: xs.reduce((a, b) => a < b ? a : b), max: xs.reduce((a, b) => a > b ? a : b));

void main() {
  final (q, r) = divmod(17, 5);
  print('17 = 5 * $q + $r');
  final r2 = range([2.5, -1.0, 7.25]);
  print('min ${r2.min}, max ${r2.max}');
  print('record: ${(1, 'a', flag: true)}');
  print('equal by value: ${(1, 2) == (1, 2)}');
}
Output
17 = 5 * 3 + 2
min -1.0, max 7.25
record: (1, a, flag: true)
equal by value: true

Properties

Type get runtimeType

A Type object representing the runtime type of a record.

The runtime type of a record is defined by the record's shape, the number of positional fields and names of named fields, and the runtime type of each of those fields. (The runtime type of the record does not depend on the runtimeType getter of its fields' values, which may have overridden Object.runtimeType.)

The Type object of a record type is only equal to another Type object for a record type, and only if the other record type has the same shape, and if the corresponding fields have the same types.

hashCodegetter
int get hashCode

A hash-code compatible with ==.

Since [operator==] is defined in terms of the == operators of the record's field values, the hash code is also computed based on the Object.hashCode of the field values.

There is no guaranteed order in which the hashCode of field values is accessed. It's unspecified how those values are combined, other than it being consistent throughout a single program execution.

Methods

toStringmethod
String toString()

Creates a string-representation of the record.

The string representation is only intended for debugging, and may differ between development and production. There is no guaranteed format in production mode.

In development mode, the string will strive to be a parenthesized comma separated list of field representations, where the field representation is the toString of the value for positional fields, and someName: followed by that for a named field named someName.

Example
void main() {
  final r = (1, 'two', flag: true);
  print('record: $r');
  print('positional only: ${(3.5, null)}');
}
Output
record: (1, two, flag: true)
positional only: (3.5, null)

Operators

operator ==operator
bool operator ==(Object other)

Checks whether other has the same shape and equal fields to this record.

A record is only equal to another record with the same shape, and then only when the value of every field is equal, occording to its ==, to the corresponding field value of other.

There is no guaranteed order in which field value equality is checked, and it's unspecified whether further fields are checked after finding corresponding fields which are not equal. It's not even guaranteed that the order is consistent within a single program execution.

As usual, be very careful around objects which break the equality contract, like double.nan which is not equal to itself. For example

var pair = ("a", double.nan);
if (pair != pair) print("Oops");

Will print the "Oops", because pair == pair is defined to be equal to "a" == "a" & double.nan == double.nan, which is false.

Example
void main() {
  print('(1, 2) == (1, 2): ${(1, 2) == (1, 2)}');
  print('(1, 2) == (2, 1): ${(1, 2) == (2, 1)}');
  print('named order ignored: ${(a: 1, b: 2) == (b: 2, a: 1)}');
  print('records as map keys: ${{(0, 0): 'origin'}[(0, 0)]}');
}
Output
(1, 2) == (1, 2): true
(1, 2) == (2, 1): false
named order ignored: true
records as map keys: origin
class

RegExp

abstract interface class RegExp implements Pattern

A regular expression pattern.

Regular expressions (abbreviated as regex or regexp) consist of a sequence of characters that specify a match-checking algorithm for text inputs. Applying a regexp to an input text results either in the regexp matching, or accepting, the text, or the text being rejected. When the regexp matches the text, it further provides some information about how it matched the text.

Raya regular expressions have the same syntax and semantics as JavaScript regular expressions. To learn more about JavaScript regular expressions, see <https://ecma-international.org/ecma-262/9.0/#sec-regexp-regular-expression-objects>.

Raya provides the basic regexp matching algorithm as matchAsPrefix, which checks if the regexp matches a part of the input starting at a specific position. If the regexp matches, Raya returns the details of the match as a RegExpMatch.

You can build all the other methods of RegExp from that basic match check.

The most common use of a regexp is to search for a match in the input. The firstMatch method provides this functionality. This method searches a string for the first position where the regexp matches. Again, if a match is found, Raya returns its details as a RegExpMatch.

The following example finds the first match of a regular expression in a string.

RegExp exp = RegExp(r'(\w+)');
String str = 'Parse my string';
RegExpMatch? match = exp.firstMatch(str);
print(match![0]); // "Parse"

Use allMatches to look for all matches of a regular expression in a string.

The following example finds all matches of a regular expression in a string.

RegExp exp = RegExp(r'(\w+)');
String str = 'Parse my string';
Iterable<RegExpMatch> matches = exp.allMatches(str);
for (final m in matches) {
  print(m[0]);
}

The output of the example is:

Parse
my
string

The preceding examples use a raw string, a specific string type that prefixes the string literal with r. Use a raw string to treat each character, including \ and $, in a string as a literal character. Each character then gets passed to the RegExp parser. You should use a raw string as the argument to the RegExp constructor.

Performance Notice: Regular expressions do not resolve issues magically. Anyone can write a regexp that performs inefficiently when applied to some string inputs. Often, such a regexp will perform well enough on small or common inputs, but have pathological performance on large and uncommon inputs. This inconsistent behavior makes performance issues harder to detect in testing.

A regexp might not find text any faster than using String operations to inspect a string. The strength of regexp comes from the ability to specify somewhat complicated patterns in very few characters. These regexps provide reasonable efficiency in most common cases. This conciseness comes at a cost of readability. Due to their syntactic complexity, regexes cannot be considered self documenting.

Raya regexps implement the ECMAScript RegExp specification. This specification provides a both common and well-known regexp behavior. When compiling Raya for the web, the compiled code can use the browser’s regexp implementation.

The specification defines ECMAScript regexp behavior using backtracking. When a regexp can choose between different ways to match, it tries each way in the order given in the pattern. For example: RegExp(r"(foo|bar)baz") wants to check for foo or bar, so it checks for foo first. If continuing along that path doesn't match the input, the regexp implementation backtracks. The implementation resets to the original state from before checking for foo, forgetting all the work it has done after that, and then tries the next choice; bar in this example.

The specification defines these choices and the order in which they must be attempted. If a regexp could match an input in more than one way, the order of the choices decides which match the regexp returns. Commonly used regexps order their matching choices to ensure a specific result. The ECMAScript regexp specification limits how Raya can implement regular expressions. It must be a backtracking implementation which checks choices in a specific order. Raya cannot choose a different regexp implementation, because then regexp matching would behave differently.

The backtracking approach works, but at a cost. For some regexps and some inputs, finding a correct match can take a lot of tries. It can take even more tries to reject an input that the regexp almost matches.

A well-known dangerous regexp pattern comes from nesting quantifiers like *:

var re = RegExp(r"^(a*|b)*c");
print(re.hasMatch("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));

The regexp pattern doesn't match the input string of only as as the input doesn’t contain the required c. There exists an exponential number of different ways for (a*|b)* to match all the as. The backtracking regexp implementation tries all of them before deciding that none of those can lead to a complete match. Each extra a added to the input doubles the time the regexp takes to return false. (When backtracking has this exponential potential, it is called “catastrophic backtracking”).

Sequential quantifiers provide another dangerous pattern, but they provide “only” polynomial complexity.

// Like `\w*-\d`, but check for `b` and `c` in that order.
var re = RegExp(r"^\w*(b)?\w*(c)?\w*-\d");
print(re.hasMatch("a" * 512));

Again the input doesn’t match, but RegExp must try n<sup>3</sup> ways to match the n as before deciding that. Doubling the input’s length increases the time to return false eightfold. This exponent increases with the number of sequential quantifiers.

Both of these patterns look trivial when reduced to such simple regexps. However, these "trivial" patterns often arise as parts of more complicated regular expressions, where your ability to find the problem gets more difficult.

In general, if a regexp has potential for super-linear complexity, you can craft an input that takes an inordinate amount of time to search. These patterns can then be used for denial of service attacks if you apply vulnerable regexp patterns to user-provided inputs.

No guaranteed solution exists for this problem. Be careful to not use regexps with super-linear behavior where the program may match that regexp against inputs with no guaranteed match.

Rules of thumb to avoid regexps with super-linear execution time include:

  • Whenever the regexp has a choice, try to make sure that the choice can be made based on the next character (or very limited look-ahead). This limits the need to perform a lot of computation along both choices.
  • When using quantifiers, ensure that the same string cannot match both one and more-than-one iteration of the quantifier's regular expression. (For (a*|b)*, the string "aa" can match both (a*|b){1} and (a*|b){2}.)
  • Most uses of Raya regular expressions search for a match, for example using firstMatch. If you do not anchor the pattern to the start of a line or input using ^, this search acts as if the regexp began with an implicit [^]*. Starting your actual regular expression with .* then results in potential quadratic behavior for the search. Use anchors or matchAsPrefix where appropriate, or avoid starting the regexp with a quantified pattern.
  • Other regular expression dialects use this to limit backtracking. If an atomic capture group succeeds once, the regexp cannot backtrack into the same match later. As lookarounds also serve as atomic groups, something similar can be achieved using a lookahead: var re = RegExp(r"^(?=((a*|b)*))\1d"); The preceding example does the same inefficient matching of (a*|b)*. Once the regexp has matched as far as possible, it completes the positive lookahead. Then it skips what the lookahead matched using a back-reference. After that, it can no longer backtrack and try other combinations of as.

Try to reduce how many ways the regexp can match the same string. That reduces the number of possible backtracks performed when the regexp does not find a match. Several guides to improving the performance of regular expressions exist on the internet. Use these as inspirations, too.

Example
void main() {
  final email = RegExp(r'^[\w.]+@[\w]+\.[a-z]{2,}$');
  for (final s in ['ada@example.org', 'not-an-email', 'a.b@site.io']) {
    print('$s: ${email.hasMatch(s)}');
  }
}
Output
ada@example.org: true
not-an-email: false
a.b@site.io: true

Constructors

RegExpfactory
external factory RegExp(String source, {bool multiLine = false, bool caseSensitive = true, bool unicode = false, bool dotAll = false})

Constructs a regular expression.

Throws a FormatException if source does not follow valid regular expression syntax.

If your code enables multiLine, then ^ and $ will match the beginning and end of a line, as well as matching beginning and end of the input, respectively.

If your code disables caseSensitive, then Raya ignores the case of letters when matching. For example, with caseSensitive disable, the regexp pattern a matches both a and A.

If your code enables unicode, then Raya treats the pattern as a Unicode pattern per the ECMAScript standard.

If your code enables dotAll, then the . pattern will match all characters, including line terminators.

Example:

final wordPattern = RegExp(r'(\w+)');
final digitPattern = RegExp(r'(\d+)');

These examples use a raw string as the argument. You should prefer to use a raw string as argument to the RegExp constructor, because it makes it easy to write the \ and $ characters as regexp reserved characters.

The same examples written using non-raw strings would be:

final wordPattern = RegExp('(\\w+)'); // Should be raw string.
final digitPattern = RegExp('(\\d+)'); // Should be raw string.

Use a non-raw string only when you need to use string interpolation. For example:

Pattern keyValuePattern(String keyIdentifier) =>
    RegExp('$keyIdentifier=(\\w+)');

When including a string verbatim into the regexp pattern like this, be careful that the string does not contain regular expression reserved characters. If that risk exists, use the escape function to convert those characters to safe versions of the reserved characters and match only the string itself:

Pattern keyValuePattern(String anyStringKey) =>
    RegExp('${RegExp.escape(anyStringKey)}=(\\w+)');
Example
void main() {
  final re = RegExp(r'raya', caseSensitive: false);
  print(re.allMatches('Raya, RAYA, raya').length);
  final lines = RegExp(r'^\w+', multiLine: true);
  print(lines.allMatches('one\ntwo\nthree').map((m) => m[0]).toList());
}
Output
3
[one, two, three]

Static

escapestaticmethod
external static String escape(String text)

Creates regular expression syntax that matches the input text.

If text contains regular expression reserved characters, the resulting regular expression matches those characters literally. If text contains no regular expression reserved characters, Raya returns the expression unmodified.

The reserved characters in regular expressions are: (, ), [, ], {, }, *, +, ?, ., ^, $, | and \.

Use this method to create a pattern to be included in a larger regular expression. Since a String is itself a Pattern which matches itself, converting the string to a regular expression isn't needed to search for that exact string.

print(RegExp.escape('dash@example.com')); // dash@example\.com
print(RegExp.escape('a+b')); // a\+b
print(RegExp.escape('a*b')); // a\*b
print(RegExp.escape('{a-b}')); // \{a-b\}
print(RegExp.escape('a?')); // a\?
Example
void main() {
  const literal = 'a.b*c';
  final re = RegExp(RegExp.escape(literal));
  print('pattern: ${re.pattern}');
  print('matches "a.b*c": ${re.hasMatch('xa.b*cx')}');
  print('matches "aXbbc": ${re.hasMatch('aXbbc')}');
}
Output
pattern: a\.b\*c
matches "a.b*c": true
matches "aXbbc": false

Properties

patterngetter
String get pattern

The regular expression pattern source of this RegExp.

final regExp = RegExp(r'\p{L}');
print(regExp.pattern); // \p{L}
bool get isMultiLine

Whether this regular expression matches multiple lines.

If the regexp does match multiple lines, the "^" and "$" characters match the beginning and end of lines. If not, the characters match the beginning and end of the input.

bool get isCaseSensitive

Whether this regular expression is case sensitive.

If the regular expression is not case sensitive, it will match an input letter with a pattern letter even if the two letters are different case versions of the same letter.

final text = 'Parse my string';
var regExp = RegExp(r'STRING', caseSensitive: false);
print(regExp.isCaseSensitive); // false
print(regExp.hasMatch(text)); // true, matches.

regExp = RegExp(r'STRING', caseSensitive: true);
print(regExp.isCaseSensitive); // true
print(regExp.hasMatch(text)); // false, no match.
isUnicodegetter
bool get isUnicode

Whether this regular expression uses Unicode mode.

In Unicode mode, Raya treats UTF-16 surrogate pairs in the original string as a single code point and will not match each code unit in the pair separately. Otherwise, Raya treats the target string as a sequence of individual code units and does not treat surrogates as special.

In Unicode mode, Raya restricts the syntax of the RegExp pattern, for example disallowing some unescaped uses of restricted regexp characters, and disallowing unnecessary \-escapes ("identity escapes"), which have both historically been allowed in non-Unicode mode. Raya also allows some pattern features, like Unicode property escapes, only in this mode.

var regExp = RegExp(r'^\p{L}$', unicode: true);
print(regExp.hasMatch('a')); // true
print(regExp.hasMatch('b')); // true
print(regExp.hasMatch('?')); // false
print(regExp.hasMatch(r'p{L}')); // false

// U+1F600 (😀), one code point, two code units.
var smiley = '\ud83d\ude00';

regExp = RegExp(r'^.$', unicode: true); // Matches one code point.
print(regExp.hasMatch(smiley)); // true
regExp = RegExp(r'^..$', unicode: true); // Matches two code points.
print(regExp.hasMatch(smiley)); // false

regExp = RegExp(r'^\p{L}$', unicode: false);
print(regExp.hasMatch('a')); // false
print(regExp.hasMatch('b')); // false
print(regExp.hasMatch('?')); // false
print(regExp.hasMatch(r'p{L}')); // true

regExp = RegExp(r'^.$', unicode: false);  // Matches one code unit.
print(regExp.hasMatch(smiley)); // false
regExp = RegExp(r'^..$', unicode: false);  // Matches two code units.
print(regExp.hasMatch(smiley)); // true
isDotAllgetter
bool get isDotAll

Whether "." in this regular expression matches line terminators.

When false, the "." character matches a single character, unless that character terminates a line. When true, then the "." character will match any single character including line terminators.

This feature is distinct from isMultiLine. They affect the behavior of different pattern characters, so they can be used together or separately.

Methods

RegExpMatch? firstMatch(String input)

Finds the first match of the regular expression in the string input.

Returns null if there is no match.

final string = '[00:13.37] This is a chat message.';
final regExp = RegExp(r'c\w*');
final match = regExp.firstMatch(string)!;
print(match[0]); // chat
Example
void main() {
  final date = RegExp(r'(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})');
  final m = date.firstMatch('Released on 2026-11-29.')!;
  print('year ${m.namedGroup('year')}, month ${m.namedGroup('month')}, day ${m.namedGroup('day')}');
  print('no match: ${date.firstMatch('no date here')}');
}
Output
year 2026, month 11, day 29
no match: null
Iterable<RegExpMatch> allMatches(String input, [int start = 0])
Example
void main() {
  final text = 'Call 555-1234 or 555-9876 today';
  final phone = RegExp(r'(\d{3})-(\d{4})');
  for (final m in phone.allMatches(text)) {
    print('found ${m[0]} at ${m.start}: prefix ${m[1]}, line ${m[2]}');
  }
  print('count: ${phone.allMatches(text).length}');
}
Output
found 555-1234 at 5: prefix 555, line 1234
found 555-9876 at 17: prefix 555, line 9876
count: 2
hasMatchmethod
bool hasMatch(String input)

Checks whether this regular expression has a match in the input.

var string = 'Dash is a bird';
var regExp = RegExp(r'(humming)?bird');
var match = regExp.hasMatch(string); // true

regExp = RegExp(r'dog');
match = regExp.hasMatch(string); // false
Example
void main() {
  final hex = RegExp(r'^#?[0-9a-fA-F]{6}$');
  for (final s in ['#007AFF', 'ff00ff', '#xyz123']) {
    print('$s is a colour: ${hex.hasMatch(s)}');
  }
}
Output
#007AFF is a colour: true
ff00ff is a colour: true
#xyz123 is a colour: false
String? stringMatch(String input)

Finds the string of the first match of this regular expression in input.

Searches for a match for this regular expression in input, just like firstMatch, but returns only the matched substring if a match is found, not a RegExpMatch.

var string = 'Dash is a bird';
var regExp = RegExp(r'(humming)?bird');
var match = regExp.stringMatch(string); // Match

regExp = RegExp(r'dog');
match = regExp.stringMatch(string); // No match
Example
void main() {
  final word = RegExp(r'[A-Z]\w+');
  print(word.stringMatch('the Raya language'));
  print(word.stringMatch('nothing here'));
}
Output
Raya
null
abstract interface class RegExpMatch implements Match

A regular expression match.

Regular expression matches are Matches. They also include the ability to retrieve the names for any named capture groups and to retrieve matches for named capture groups by name instead of by their index.

Example:

const pattern =
    r'^\[(?<Time>\s*((?<hour>\d+)):((?<minute>\d+))\.((?<second>\d+)))\]'
    r'\s(?<Message>\s*(.*)$)';

final regExp = RegExp(
  pattern,
  multiLine: true,
);

const multilineText = '[00:13.37] This is a first message.\n'
    '[01:15.57] This is a second message.\n';

RegExpMatch regExpMatch = regExp.firstMatch(multilineText)!;
print(regExpMatch.groupNames.join('-')); // hour-minute-second-Time-Message.
final time = regExpMatch.namedGroup('Time'); // 00:13.37
final hour = regExpMatch.namedGroup('hour'); // 00
final minute = regExpMatch.namedGroup('minute'); // 13
final second = regExpMatch.namedGroup('second'); // 37
final message =
    regExpMatch.namedGroup('Message'); // This is the first message.
final date = regExpMatch.namedGroup('Date'); // Undefined `Date`, throws.

Iterable<RegExpMatch> matches = regExp.allMatches(multilineText);
for (final m in matches) {
  print(m.namedGroup('Time'));
  print(m.namedGroup('Message'));
  // 00:13.37
  // This is the first message.
  // 01:15.57
  // This is the second message.
}

Properties

Iterable<String> get groupNames

The names of the named capture groups of pattern.

patterngetter
RegExp get pattern

Methods

String? namedGroup(String name)

The string captured by the named capture group name.

Returns the substring of the input that the labeled capture group, labeled name, matched, or null if that capture group was not part of the match.

The name must be the name of a named capture group in the regular expression pattern which created this match. That is, the name must be in groupNames.

Example
void main() {
  final re = RegExp(r'(?<key>\w+)=(?<value>\w+)');
  for (final m in re.allMatches('a=1 b=22 c=333')) {
    print('${m.namedGroup('key')} -> ${m.namedGroup('value')}');
  }
  print(re.firstMatch('x=y')!.groupNames.toList());
}
Output
a -> 1
b -> 22
c -> 333
[key, value]
class

Set

abstract interface class Set<E> implements Iterable<E>, _SetIterable<E>

A collection of objects in which each object can occur only once.

That is, for each object of the element type, the object is either considered to be in the set, or to not be in the set.

Set implementations may consider some elements indistinguishable. These elements are treated as being the same for any operation on the set.

The default Set implementation, LinkedHashSet, considers objects indistinguishable if they are equal with regard to [Object.==] and Object.hashCode.

Iterating over elements of a set may be either unordered or ordered in some way. Examples:

  • A HashSet is unordered, which means that its iteration order is unspecified,
  • LinkedHashSet iterates in the insertion order of its elements, and
  • A sorted set like SplayTreeSet iterates the elements in sorted order.

It is generally not allowed to modify the set (add or remove elements) while an operation on the set is being performed, for example during a call to forEach or containsAll. Nor is it allowed to modify the set while iterating either the set itself or any Iterable that is backed by the set, such as the ones returned by methods like where and map.

It is generally not allowed to modify the equality of elements (and thus not their hashcode) while they are in the set. Some specialized subtypes may be more permissive, in which case they should document this behavior.

Example
void main() {
  final words = 'the quick the lazy the end'.split(' ');
  final unique = words.toSet();
  print('unique words: $unique (${unique.length} of ${words.length})');
  print('set literal: ${{3, 1, 2}}');
}
Output
unique words: {the, quick, lazy, end} (4 of 6)
set literal: {3, 1, 2}

Constructors

Setfactory
factory Set() = LinkedHashSet<E>

Creates an empty Set.

The created Set is a plain LinkedHashSet. As such, it considers elements that are equal (using [operator ==]) to be indistinguishable, and requires them to have a compatible Object.hashCode implementation.

The set is equivalent to one created by LinkedHashSet<E>.

Example
void main() {
  final s = Set<String>();
  print('add a: ${s.add('a')}, add a again: ${s.add('a')}');
  s.addAll(['c', 'b']);
  print('set: $s (insertion order)');
}
Output
add a: true, add a again: false
set: {a, c, b} (insertion order)
factory Set.identity() = LinkedHashSet<E>.identity

Creates an empty identity Set.

The created Set is a LinkedHashSet that uses identity as equality relation.

The set is equivalent to one created by LinkedHashSet<E>.identity.

Example
void main() {
  final s1 = 'ab', s2 = String.fromCharCodes([97, 98]);
  print('s1 == s2: ${s1 == s2}, identical: ${identical(s1, s2)}');
  // A plain set uses ==, an identity set uses identical.
  print('plain set:    ${{s1, s2}.length} element(s)');
  print('identity set: ${(Set<String>.identity()..addAll([s1, s2])).length} element(s)');
}
Output
s1 == s2: true, identical: false
plain set:    1 element(s)
identity set: 2 element(s)
Set.fromfactory
factory Set.from(Iterable elements) = LinkedHashSet<E>.from

Creates a Set that contains all elements.

All the elements should be instances of E. The elements iterable itself can have any type, so this constructor can be used to down-cast a Set, for example as:

Set<SuperType> superSet = ...;
Set<SubType> subSet =
    Set<SubType>.from(superSet.where((e) => e is SubType));

The created Set is a LinkedHashSet. As such, it considers elements that are equal (using [operator ==]) to be indistinguishable, and requires them to have a compatible Object.hashCode implementation.

The set is equivalent to one created by LinkedHashSet<E>.from(elements).

final numbers = <num>{10, 20, 30};
final setFrom = Set<int>.from(numbers);
print(setFrom); // {10, 20, 30}
Example
void main() {
  final List<Object> mixed = [3, 1, 3, 2];
  final ints = Set<int>.from(mixed);
  print('Set<int>.from: $ints');
}
Output
Set<int>.from: {3, 1, 2}
Set.offactory
factory Set.of(Iterable<E> elements) = LinkedHashSet<E>.of

Creates a Set from elements.

The created Set is a LinkedHashSet. As such, it considers elements that are equal (using [operator ==]) to be indistinguishable, and requires them to have a compatible Object.hashCode implementation.

The set is equivalent to one created by LinkedHashSet<E>.of(elements).

final baseSet = <int>{1, 2, 3};
final setOf = Set<num>.of(baseSet);
print(setOf); // {1, 2, 3}
Example
void main() {
  final s = Set.of(['b', 'a', 'b']);
  print('Set.of: $s');
  s.add('c');
  print('a growable copy: $s');
}
Output
Set.of: {b, a}
a growable copy: {b, a, c}
factory Set.unmodifiable(Iterable<E> elements)

Creates an unmodifiable Set from elements.

The new set behaves like the result of Set.of, except that the set returned by this constructor is not modifiable.

final characters = <String>{'A', 'B', 'C'};
final unmodifiableSet = Set.unmodifiable(characters);
Example
void main() {
  final s = Set.unmodifiable([1, 2, 2, 3]);
  print('unmodifiable: $s');
  try {
    s.add(4);
  } on UnsupportedError {
    print('add throws UnsupportedError');
  }
}
Output
unmodifiable: {1, 2, 3}
add throws UnsupportedError

Static

castFromstaticmethod
static Set<T> castFrom<S, T>(Set<S> source, {Set<R> Function<R>()? newSet})

Adapts source to be a Set<T>.

If newSet is provided, it is used to create the new sets returned by toSet, union, and is also used for intersection and difference. If newSet is omitted, it defaults to creating a new set using the default Set constructor, and intersection and difference returns an adapted version of calling the same method on the source.

Any time the set would produce an element that is not a T, the element access will throw.

Any time a T value is attempted added into the adapted set, the store will throw unless the value is also an instance of S.

If all accessed elements of source are actually instances of T, and if all elements added to the returned set are actually instances of S, then the returned set can be used as a Set<T>.

Methods which accept one or more Object? as argument, like contains, remove and removeAll, will pass the argument directly to the this set's method without any checks.

Example
void main() {
  final Set<Object> raw = {1, 2, 3};
  final ints = Set.castFrom<Object, int>(raw);
  print('sum: ${ints.fold<int>(0, (a, b) => a + b)}');
  ints.add(4);
  print('view writes through: $raw');
}
Output
sum: 6
view writes through: {1, 2, 3, 4}

Properties

iteratorgetter
Iterator<E> get iterator

An iterator that iterates over the elements of this set.

The order of iteration is defined by the individual Set implementation, but must be consistent between changes to the set.

Methods

castmethod
Set<R> cast<R>()

Provides a view of this set as a set of R instances.

If this set contains only instances of R, all read operations will work correctly. If any operation tries to access an element that is not an instance of R, the access will throw instead.

Elements added to the set (e.g. by using add or addAll) must be instances of R to be valid arguments to the adding function, and they must be instances of E as well to be accepted by this set as well.

Methods which accept one or more Object? as argument, like contains, remove and removeAll, will pass the argument directly to the this set's method without any checks. That means that you can do setOfStrings.cast<int>.remove("a") successfully, even if it looks like it shouldn't have any effect.

Example
void main() {
  final Set<num> nums = {1, 2, 3};
  final Set<int> ints = nums.cast<int>();
  print('cast: $ints, max ${ints.reduce((a, b) => a > b ? a : b)}');
}
Output
cast: {1, 2, 3}, max 3
containsmethod
bool contains(Object? value)

Whether value is in the set.

final characters = <String>{'A', 'B', 'C'};
final containsB = characters.contains('B'); // true
final containsD = characters.contains('D'); // false
Example
void main() {
  final vowels = {'a', 'e', 'i', 'o', 'u'};
  final word = 'raya';
  print('vowels in $word: ${word.split('').where(vowels.contains).length}');
  print("contains 'y': ${vowels.contains('y')}");
}
Output
vowels in raya: 2
contains 'y': false
addmethod
bool add(E value)

Adds value to the set.

Returns true if value (or an equal value) was not yet in the set. Otherwise returns false and the set is not changed.

Example:

final dateTimes = <DateTime>{};
final time1 = DateTime.fromMillisecondsSinceEpoch(0);
final time2 = DateTime.fromMillisecondsSinceEpoch(0);
// time1 and time2 are equal, but not identical.
assert(time1 == time2);
assert(!identical(time1, time2));
final time1Added = dateTimes.add(time1);
print(time1Added); // true
// A value equal to time2 exists already in the set, and the call to
// add doesn't change the set.
final time2Added = dateTimes.add(time2);
print(time2Added); // false

print(dateTimes); // {1970-01-01 02:00:00.000}
assert(dateTimes.length == 1);
assert(identical(time1, dateTimes.first));
print(dateTimes.length);
Example
void main() {
  final s = <String>{};
  print('add x: ${s.add('x')}');
  print('add x again: ${s.add('x')}');
  print('set: $s, contains x: ${s.contains('x')}');
  print('containsAll: ${{1, 2, 3}.containsAll([1, 3])}');
}
Output
add x: true
add x again: false
set: {x}, contains x: true
containsAll: true
addAllmethod
void addAll(Iterable<E> elements)

Adds all elements to this set.

Equivalent to adding each element in elements using add, but some collections may be able to optimize it.

final characters = <String>{'A', 'B'};
characters.addAll({'A', 'B', 'C'});
print(characters); // {A, B, C}
Example
void main() {
  final s = {1, 2};
  s.addAll([2, 3, 4, 4]);
  print('after addAll: $s');
}
Output
after addAll: {1, 2, 3, 4}
removemethod
bool remove(Object? value)

Removes value from the set.

Returns true if value was in the set, and false if not. The method has no effect if value was not in the set.

final characters = <String>{'A', 'B', 'C'};
final didRemoveB = characters.remove('B'); // true
final didRemoveD = characters.remove('D'); // false
print(characters); // {A, C}
Example
void main() {
  final s = {'a', 'b'};
  print('remove a: ${s.remove('a')} -> $s');
  print('remove z: ${s.remove('z')} -> $s');
}
Output
remove a: true -> {b}
remove z: false -> {b}
lookupmethod
E? lookup(Object? object)

If an object equal to object is in the set, return it.

Checks whether object is in the set, like contains, and if so, returns the object in the set, otherwise returns null.

If the equality relation used by the set is not identity, then the returned object may not be identical to object. Some set implementations may not be able to implement this method. If the contains method is computed, rather than being based on an actual object instance, then there may not be a specific object instance representing the set element.

final characters = <String>{'A', 'B', 'C'};
final containsB = characters.lookup('B');
print(containsB); // B
final containsD = characters.lookup('D');
print(containsD); // null
Example
void main() {
  final s = {'apple', 'pear'};
  final found = s.lookup('ap' + 'ple');
  print('lookup apple: $found');
  print('lookup kiwi: ${s.lookup('kiwi')}');
}
Output
lookup apple: apple
lookup kiwi: null
removeAllmethod
void removeAll(Iterable<Object?> elements)

Removes each element of elements from this set.

final characters = <String>{'A', 'B', 'C'};
characters.removeAll({'A', 'B', 'X'});
print(characters); // {C}
Example
void main() {
  final s = {1, 2, 3, 4, 5};
  s.removeAll([2, 4, 9]);
  print('after removeAll [2, 4, 9]: $s');
}
Output
after removeAll [2, 4, 9]: {1, 3, 5}
retainAllmethod
void retainAll(Iterable<Object?> elements)

Removes all elements of this set that are not elements in elements.

Checks for each element of elements whether there is an element in this set that is equal to it (according to this.contains), and if so, the equal element in this set is retained, and elements that are not equal to any element in elements are removed.

final characters = <String>{'A', 'B', 'C'};
characters.retainAll({'A', 'B', 'X'});
print(characters); // {A, B}
Example
void main() {
  final s = {1, 2, 3, 4, 5};
  s.retainAll([2, 4, 9]);
  print('after retainAll [2, 4, 9]: $s');
}
Output
after retainAll [2, 4, 9]: {2, 4}
void removeWhere(bool test(E element))

Removes all elements of this set that satisfy test.

final characters = <String>{'A', 'B', 'C'};
characters.removeWhere((element) => element.startsWith('B'));
print(characters); // {A, C}
Example
void main() {
  final s = {1, 2, 3, 4, 5, 6};
  s.removeWhere((x) => x.isOdd);
  print('evens left: $s');
}
Output
evens left: {2, 4, 6}
void retainWhere(bool test(E element))

Removes all elements of this set that fail to satisfy test.

final characters = <String>{'A', 'B', 'C'};
characters.retainWhere(
    (element) => element.startsWith('B') || element.startsWith('C'));
print(characters); // {B, C}
Example
void main() {
  final s = {'a', 'bb', 'ccc', 'dd'};
  s.retainWhere((w) => w.length == 2);
  print('two-letter words: $s');
}
Output
two-letter words: {bb, dd}
bool containsAll(Iterable<Object?> other)

Whether this set contains all the elements of other.

final characters = <String>{'A', 'B', 'C'};
final containsAB = characters.containsAll({'A', 'B'});
print(containsAB); // true
final containsAD = characters.containsAll({'A', 'D'});
print(containsAD); // false
Example
void main() {
  final have = {'flour', 'eggs', 'milk', 'sugar'};
  print('can make pancakes: ${have.containsAll(['flour', 'eggs', 'milk'])}');
  print('can make bread:    ${have.containsAll(['flour', 'yeast'])}');
}
Output
can make pancakes: true
can make bread:    false
Set<E> intersection(Set<Object?> other)

Creates a new set which is the intersection between this set and other.

That is, the returned set contains all the elements of this Set that are also elements of other according to other.contains.

final characters1 = <String>{'A', 'B', 'C'};
final characters2 = <String>{'A', 'E', 'F'};
final intersectionSet = characters1.intersection(characters2);
print(intersectionSet); // {A}
Example
void main() {
  final likesTea = {'ada', 'alan', 'grace'};
  final likesCake = {'grace', 'ada', 'edsger'};
  print('both:      ${likesTea.intersection(likesCake)}');
  print('tea only:  ${likesTea.difference(likesCake)}');
}
Output
both:      {ada, grace}
tea only:  {alan}
unionmethod
Set<E> union(Set<E> other)

Creates a new set which contains all the elements of this set and other.

That is, the returned set contains all the elements of this Set and all the elements of other.

final characters1 = <String>{'A', 'B', 'C'};
final characters2 = <String>{'A', 'E', 'F'};
final unionSet1 = characters1.union(characters2);
print(unionSet1); // {A, B, C, E, F}
final unionSet2 = characters2.union(characters1);
print(unionSet2); // {A, E, F, B, C}
Example
void main() {
  final a = {1, 2, 3, 4}, b = {3, 4, 5};
  print('union:        ${a.union(b)}');
  print('intersection: ${a.intersection(b)}');
  print('difference:   ${a.difference(b)}');
  print('b - a:        ${b.difference(a)}');
}
Output
union:        {1, 2, 3, 4, 5}
intersection: {3, 4}
difference:   {1, 2}
b - a:        {5}
Set<E> difference(Set<Object?> other)

Creates a new set with the elements of this that are not in other.

That is, the returned set contains all the elements of this Set that are not elements of other according to other.contains.

final characters1 = <String>{'A', 'B', 'C'};
final characters2 = <String>{'A', 'E', 'F'};
final differenceSet1 = characters1.difference(characters2);
print(differenceSet1); // {B, C}
final differenceSet2 = characters2.difference(characters1);
print(differenceSet2); // {E, F}
Example
void main() {
  final before = {'a.ray', 'b.ray', 'c.ray'};
  final after = {'a.ray', 'c.ray', 'd.ray'};
  print('removed: ${before.difference(after)}');
  print('added:   ${after.difference(before)}');
}
Output
removed: {b.ray}
added:   {d.ray}
clearmethod
void clear()

Removes all elements from the set.

final characters = <String>{'A', 'B', 'C'};
characters.clear(); // {}
Example
void main() {
  final s = {1, 2, 3};
  s.clear();
  print('after clear: $s, length ${s.length}');
}
Output
after clear: {}, length 0
toSetmethod
Set<E> toSet()

Creates a Set with the same elements and behavior as this Set.

The returned set behaves the same as this set with regard to adding and removing elements. It initially contains the same elements. If this set specifies an ordering of the elements, the returned set will have the same order.

Example
void main() {
  final s = {1, 2};
  final copy = s.toSet()..add(3);
  print('copy: $copy, original: $s');
}
Output
copy: {1, 2, 3}, original: {1, 2}
class

Sink

abstract interface class Sink<T>

A generic destination for data.

Multiple data values can be put into a sink, and when no more data is available, the sink should be closed.

This is a generic interface that other data receivers can implement.

Methods

addmethod
void add(T data)

Adds data to the sink.

Must not be called after a call to close.

Example
class Totaller implements Sink<int> {
  int total = 0;
  @override
  void add(int data) => total += data;
  @override
  void close() => print('closed with total $total');
}

void main() {
  final Sink<int> sink = Totaller();
  for (final n in [3, 4, 5]) {
    sink.add(n);
  }
  print('running total: ${(sink as Totaller).total}');
  sink.close();
}
Output
running total: 12
closed with total 12
closemethod
void close()

Closes the sink.

The add method must not be called after this method.

Calling this method more than once is allowed, but does nothing.

Example
class LineCollector implements Sink<String> {
  final lines = <String>[];
  bool closed = false;
  @override
  void add(String data) {
    if (closed) throw StateError('sink is closed');
    lines.add(data);
  }
  @override
  void close() => closed = true;
}

void main() {
  final s = LineCollector()..add('one')..add('two');
  s.close();
  print('lines: ${s.lines}, closed: ${s.closed}');
  try {
    s.add('three');
  } on StateError catch (e) {
    print('add after close: ${e.message}');
  }
}
Output
lines: [one, two], closed: true
add after close: sink is closed
abstract interface class StackTrace

An interface implemented by all stack trace objects.

A StackTrace is intended to convey information to the user about the call sequence that triggered an exception.

These objects are created by the runtime, it is not possible to create them programmatically.

Constructors

StackTraceconstructor
StackTrace()
Example
// StackTrace is an interface: implement it to make your own traces.
class FixedTrace implements StackTrace {
  final List<String> frames;
  const FixedTrace(this.frames);
  @override
  String toString() => frames.map((f) => 'at $f').join('\n');
}

void main() {
  const StackTrace t = FixedTrace(['parse', 'load', 'main']);
  print(t);
  print('frames: ${t.toString().split('\n').length}');
}
Output
at parse
at load
at main
frames: 3
factory StackTrace.fromString(String stackTraceString) = _StringStackTrace

Create a StackTrace object from stackTraceString.

The created stack trace will have a toString method returning stackTraceString.

The stackTraceString can be a string returned by some other stack trace, or it can be any string at all. If the string doesn't look like a stack trace, code that interprets stack traces is likely to fail, so fake stack traces should be used with care.

Example
void main() {
  final t = StackTrace.fromString('#0 main (app.ray:3)\n#1 start (boot.ray:9)');
  print('lines: ${t.toString().split('\n').length}');
  print('first frame: ${t.toString().split('\n').first}');
}
Output
lines: 2
first frame: #0 main (app.ray:3)

Static

emptyconstant
static const empty = _StringStackTrace("")

A stack trace object with no information.

This stack trace is used as the default in situations where a stack trace is required, but the user has not supplied one.

currentstaticgetter
external static StackTrace get current

Returns a representation of the current stack trace.

This is similar to what can be achieved by doing:

try { throw 0; } catch (_, stack) { return stack; }

The getter achieves this without throwing if possible.

Methods

toStringmethod
String toString()

Returns a String representation of the stack trace.

The string represents the full stack trace starting from the point where a throw occurred to the top of the current call sequence.

The exact format of the string representation is not final.

Example
void main() {
  final t = StackTrace.fromString('#0 compute\n#1 main');
  print('toString returns the text: ${t.toString() == '#0 compute\n#1 main'}');
  print(t.toString());
}
Output
toString returns the text: true
#0 compute
#1 main
class Stopwatch

A stopwatch which measures time while it's running.

A stopwatch is either running or stopped. It measures the elapsed time that passes while the stopwatch is running.

When a stopwatch is initially created, it is stopped and has measured no elapsed time.

The elapsed time can be accessed in various formats using elapsed, elapsedMilliseconds, elapsedMicroseconds or elapsedTicks.

The stopwatch is started by calling start.

Example:

final stopwatch = Stopwatch();
print(stopwatch.elapsedMilliseconds); // 0
print(stopwatch.isRunning); // false
stopwatch.start();
print(stopwatch.isRunning); // true

To stop or pause the stopwatch, use stop. Use start to continue again when only pausing temporarily.

stopwatch.stop();
print(stopwatch.isRunning); // false
Duration elapsed = stopwatch.elapsed;
await Future.delayed(const Duration(seconds: 1));
assert(stopwatch.elapsed == elapsed); // No measured time elapsed.
stopwatch.start(); // Continue measuring.

The reset method sets the elapsed time back to zero. It can be called whether the stopwatch is running or not, and doesn't change whether it's running.

// Do some work.
stopwatch.stop();
print(stopwatch.elapsedMilliseconds); // Likely > 0.
stopwatch.reset();
print(stopwatch.elapsedMilliseconds); // 0

Constructors

Stopwatchconstructor
Stopwatch()

Creates a Stopwatch in stopped state with a zero elapsed count.

The following example shows how to start a Stopwatch immediately after allocation.

final stopwatch = Stopwatch()..start();
Example
void main() {
  final sw = Stopwatch();
  print('running at start: ${sw.isRunning}');
  print('elapsedTicks at start: ${sw.elapsedTicks}');
  print('ticks per second positive: ${sw.frequency > 0}');
}
Output
running at start: false
elapsedTicks at start: 0
ticks per second positive: true

Properties

frequencygetter
int get frequency

Frequency of the elapsed counter in Hz.

int get elapsedTicks

The elapsed number of clock ticks since calling start while the Stopwatch is running.

This is the elapsed number of clock ticks between calling start and calling stop.

Is 0 if the Stopwatch has never been started.

The elapsed number of clock ticks increases by frequency every second.

elapsedgetter
Duration get elapsed

The elapsedTicks counter converted to a Duration.

external int get elapsedMicroseconds

The elapsedTicks counter converted to microseconds.

external int get elapsedMilliseconds

The elapsedTicks counter converted to milliseconds.

isRunninggetter
bool get isRunning

Whether the Stopwatch is currently running.

Methods

startmethod
void start()

Starts the Stopwatch.

The elapsed count increases monotonically. If the Stopwatch has been stopped, then calling start again restarts it without resetting the elapsed count.

If the Stopwatch is currently running, then calling start does nothing.

Example
void main() {
  final sw = Stopwatch()..start();
  var sum = 0;
  for (var i = 0; i < 100000; i++) {
    sum += i;
  }
  print('sum: $sum');
  print('running: ${sw.isRunning}, time has passed: ${sw.elapsedTicks >= 0}');
}
Output
sum: 4999950000
running: true, time has passed: true
stopmethod
void stop()

Stops the Stopwatch.

The elapsedTicks count stops increasing after this call. If the Stopwatch is currently not running, then calling this method has no effect.

Example
void main() {
  final sw = Stopwatch()..start();
  sw.stop();
  final t1 = sw.elapsedTicks;
  var x = 0;
  for (var i = 0; i < 10000; i++) {
    x += i;
  }
  print('running after stop: ${sw.isRunning}');
  print('frozen while stopped: ${sw.elapsedTicks == t1} (work: $x)');
}
Output
running after stop: false
frozen while stopped: true (work: 49995000)
resetmethod
void reset()

Resets the elapsed count to zero.

This method does not stop or start the Stopwatch.

Example
void main() {
  final sw = Stopwatch()..start();
  for (var i = 0; i < 10000; i++) {}
  sw.stop();
  sw.reset();
  print('after stop + reset: ${sw.elapsedTicks} ticks, ${sw.elapsed}');
}
Output
after stop + reset: 0 ticks, 0:00:00.000000
class

String

abstract final class String implements Comparable<String>, Pattern

A sequence of UTF-16 code units.

Strings are mainly used to represent text. A character may be represented by multiple code points, each code point consisting of one or two code units. For example, the Papua New Guinea flag character requires four code units to represent two code points, but should be treated like a single character: "🇵🇬". Platforms that do not support the flag character may show the letters "PG" instead. If the code points are swapped, it instead becomes the Guadeloupe flag "🇬🇵" ("GP").

A string can be either single or multiline. Single line strings are written using matching single or double quotes, and multiline strings are written using triple quotes. The following are all valid Raya strings:

'Single quotes';
"Double quotes";
'Double quotes in "single" quotes';
"Single quotes in 'double' quotes";

'''A
multiline
string''';

"""
Another
multiline
string""";

Strings are immutable. Although you cannot change a string, you can perform an operation on a string which creates a new string:

const string = 'Raya is fun';
print(string.substring(0, 4)); // 'Raya'

You can use the plus (+) operator to concatenate strings:

const string = 'Raya ' + 'is ' + 'fun!';
print(string); // 'Raya is fun!'

Adjacent string literals are concatenated automatically:

const string = 'Raya ' 'is ' 'fun!';
print(string); // 'Raya is fun!'

You can use ${} to interpolate the value of Raya expressions within strings. The curly braces can be omitted when evaluating identifiers:

const string = 'rayalang';
print('$string has ${string.length} letters'); // rayalang has 8 letters

A string is represented by a sequence of Unicode UTF-16 code units accessible through the codeUnitAt or the codeUnits members:

const string = 'Raya';
final firstCodeUnit = string.codeUnitAt(0);
print(firstCodeUnit); // 68, aka U+0044, the code point for 'D'.
final allCodeUnits = string.codeUnits;
print(allCodeUnits); // [68, 97, 114, 116]

A string representation of the individual code units is accessible through the index operator:

const string = 'Raya';
final charAtIndex = string[0];
print(charAtIndex); // 'D'

The characters of a string are encoded in UTF-16. Decoding UTF-16, which combines surrogate pairs, yields Unicode code points. Following a similar terminology to Go, Raya uses the name 'rune' for an integer representing a Unicode code point. Use the runes property to get the runes of a string:

const string = 'Raya';
final runes = string.runes.toList();
print(runes); // [68, 97, 114, 116]

For a character outside the Basic Multilingual Plane (plane 0) that is composed of a surrogate pair, runes combines the pair and returns a single integer. For example, the Unicode character for a musical G-clef ('𝄞') with rune value 0x1D11E consists of a UTF-16 surrogate pair: 0xD834 and 0xDD1E. Using codeUnits returns the surrogate pair, and using runes returns their combined value:

const clef = '\u{1D11E}';
for (final item in clef.codeUnits) {
  print(item.toRadixString(16));
  // d834
  // dd1e
}
for (final item in clef.runes) {
  print(item.toRadixString(16)); // 1d11e
}

The String class cannot be extended or implemented. Attempting to do so yields a compile-time error.

Other resources
  • StringBuffer to efficiently build a string incrementally.
  • RegExp to work with regular expressions.
Example
void main() {
  const name = 'Raya';
  final greeting = 'Hello, $name! ${name.length} letters.';
  print(greeting);
  const multi = '''
line one
line two''';
  print(multi.split('\n'));
  print(r'raw: \n stays as written');
}
Output
Hello, Raya! 4 letters.
[line one, line two]
raw: \n stays as written

Constructors

external factory String.fromCharCodes(Iterable<int> charCodes, [int start = 0, int? end])

Allocates a new string containing the specified charCodes.

The charCodes can be both UTF-16 code units and runes. If a char-code value is 16-bit, it is used as a code unit:

final string = String.fromCharCodes([68]);
print(string); // D

If a char-code value is greater than 16-bits, it is decomposed into a surrogate pair:

final clef = String.fromCharCodes([0x1D11E]);
clef.codeUnitAt(0); // 0xD834
clef.codeUnitAt(1); // 0xDD1E

If start and end are provided, only the values of charCodes at positions from start to, but not including, end, are used. The start and end values must satisfy 0 <= start <= end. If start is omitted, it defaults to zero, the start of charCodes, and if end is omitted, all char-codes after start are included. If charCodes does not have end, or even start, elements, the specified char-codes may be shorter than end - start, or even empty.

Example
void main() {
  print(String.fromCharCodes([82, 97, 121, 97]));
  print(String.fromCharCodes([0x48, 0x69, 0x1F44B]));
  print(String.fromCharCode(0x03C0));
}
Output
Raya
Hi👋
π
external factory String.fromCharCode(int charCode)

Allocates a new string containing the specified charCode.

If the charCode can be represented by a single UTF-16 code unit, the new string contains a single code unit. Otherwise, the length is 2 and the code units form a surrogate pair. See documentation for fromCharCodes.

Creating a String with one half of a surrogate pair is allowed.

Example
void main() {
  print('65 -> ${String.fromCharCode(65)}');
  print('0x1F600 -> length ${String.fromCharCode(0x1F600).length} (a surrogate pair)');
  print('alphabet: ${[for (var c = 97; c < 102; c++) String.fromCharCode(c)].join()}');
}
Output
65 -> A
0x1F600 -> length 2 (a surrogate pair)
alphabet: abcde
external const factory String.fromEnvironment(String name, {String defaultValue = ""})

Value for name in the compilation configuration environment declaration.

The compilation configuration environment is provided by the surrounding tools which are compiling or running the Raya 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 result of invoking this constructor is the string associated with the key name. If no value is associated with name, the result is instead the defaultValue string, which defaults to the empty string.

Example of looking up a value:

const String.fromEnvironment("defaultFloo", defaultValue: "no floo")

In order to check whether a value is there at all, use bool.hasEnvironment. Example:

const maybeDeclared = bool.hasEnvironment("maybeDeclared")
    ? String.fromEnvironment("maybeDeclared")
    : null;

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 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.

The compilation configuration environment is not the same as the environment variables of a POSIX process. Those can be accessed on native platforms using Platform.environment from the raya:io library.

Example
void main() {
  // Set with -DGREETING=... at compile time; otherwise the default is used.
  const greeting = String.fromEnvironment('RAYA_EXAMPLE_GREETING', defaultValue: 'hello');
  print('greeting: $greeting');
  const unset = String.fromEnvironment('RAYA_EXAMPLE_UNSET');
  print("no default: '$unset' (empty string)");
}
Output
greeting: hello
no default: '' (empty string)

Properties

lengthgetter
int get length

The length of the string.

Returns the number of UTF-16 code units in this string. The number of runes might be fewer if the string contains characters outside the Basic Multilingual Plane (plane 0):

'Raya'.length;          // 4
'Raya'.runes.length;    // 4

var clef = '\u{1D11E}';
clef.length;            // 2
clef.runes.length;      // 1
Example
void main() {
  print('"Raya".length = ${'Raya'.length}');
  print('"".length     = ${''.length}');
  print('"é".length    = ${'é'.length}');
  print('"😀".length   = ${'😀'.length}');
}
Output
"Raya".length = 4
"".length     = 0
"é".length    = 1
"😀".length   = 2
hashCodegetter
int get hashCode

A hash code derived from the code units of the string.

This is compatible with [operator ==]. Strings with the same sequence of code units have the same hash code.

isEmptygetter
bool get isEmpty

Whether this string is empty.

Example
void main() {
  for (final s in ['', ' ', 'x']) {
    print('"$s": isEmpty ${s.isEmpty}, isNotEmpty ${s.isNotEmpty}, trimmed empty ${s.trim().isEmpty}');
  }
}
Output
"": isEmpty true, isNotEmpty false, trimmed empty true
" ": isEmpty false, isNotEmpty true, trimmed empty true
"x": isEmpty false, isNotEmpty true, trimmed empty false
bool get isNotEmpty

Whether this string is not empty.

codeUnitsgetter
List<int> get codeUnits

An unmodifiable list of the UTF-16 code units of this string.

Example
void main() {
  const s = 'Hi €';
  print('codeUnits: ${s.codeUnits}');
  print('length:    ${s.length}');
  print('hex:       ${s.codeUnits.map((c) => c.toRadixString(16)).join(' ')}');
}
Output
codeUnits: [72, 105, 32, 8364]
length:    4
hex:       48 69 20 20ac
runesgetter
Runes get runes

An Iterable of Unicode code-points of this string.

If the string contains surrogate pairs, they are combined and returned as one integer by this iterator. Unmatched surrogate halves are treated like valid 16-bit code-units.

Example
void main() {
  const s = 'a😀b';
  print('length (UTF-16 units): ${s.length}');
  print('runes (code points):   ${s.runes.toList()}');
  print('rune count:            ${s.runes.length}');
  print('back to text:          ${String.fromCharCodes(s.runes)}');
}
Output
length (UTF-16 units): 4
runes (code points):   [97, 128512, 98]
rune count:            3
back to text:          a😀b

Methods

int codeUnitAt(int index)

Returns the 16-bit UTF-16 code unit at the given index.

Example
void main() {
  const s = 'ABC';
  for (var i = 0; i < s.length; i++) {
    print('codeUnitAt($i) = ${s.codeUnitAt(i)}');
  }
}
Output
codeUnitAt(0) = 65
codeUnitAt(1) = 66
codeUnitAt(2) = 67
compareTomethod
int compareTo(String other)

Compares this string to other.

Returns a negative value if this is ordered before other, a positive value if this is ordered after other, or zero if this and other are equivalent.

The ordering is the same as the ordering of the code units at the first position where the two strings differ. If one string is a prefix of the other, then the shorter string is ordered before the longer string. If the strings have exactly the same content, they are equivalent with regard to the ordering. Ordering does not check for Unicode equivalence. The comparison is case sensitive.

var relation = 'Raya'.compareTo('Go');
print(relation); // < 0
relation = 'Go'.compareTo('Forward');
print(relation); // > 0
relation = 'Forward'.compareTo('Forward');
print(relation); // 0
Example
void main() {
  print('"apple".compareTo("banana") = ${'apple'.compareTo('banana')}');
  print('"pear".compareTo("pear")    = ${'pear'.compareTo('pear')}');
  print('"b".compareTo("a")          = ${'b'.compareTo('a')}');
  final names = ['Cleo', 'ada', 'Bob'];
  names.sort((a, b) => a.compareTo(b));
  print('sorted (upper case first): $names');
}
Output
"apple".compareTo("banana") = -1
"pear".compareTo("pear")    = 0
"b".compareTo("a")          = 1
sorted (upper case first): [Bob, Cleo, ada]
endsWithmethod
bool endsWith(String other)

Whether this string ends with other.

For example:

const string = 'Raya is open source';
print(string.endsWith('urce')); // true
Example
void main() {
  final files = ['a.ray', 'b.txt', 'c.ray'];
  print('Raya files: ${files.where((f) => f.endsWith('.ray')).toList()}');
}
Output
Raya files: [a.ray, c.ray]
bool startsWith(Pattern pattern, [int index = 0])

Whether this string starts with a match of pattern.

const string = 'Raya is open source';
print(string.startsWith('Dar')); // true
print(string.startsWith(RegExp(r'[A-Z][a-z]'))); // true

If index is provided, this method checks if the substring starting at that index starts with a match of pattern:

const string = 'Raya';
print(string.startsWith('art', 0)); // false
print(string.startsWith('art', 1)); // true
print(string.startsWith(RegExp(r'\w{3}'), 2)); // false

index must not be negative or greater than length.

A RegExp containing '^' does not match if the index is greater than zero and the regexp is not multi-line. The pattern works on the string as a whole, and does not extract a substring starting at index first:

const string = 'Raya';
print(string.startsWith(RegExp(r'^art'), 1)); // false
print(string.startsWith(RegExp(r'art'), 1)); // true
Example
void main() {
  const url = 'https://riptidecompute.com/raya';
  print('starts with https:   ${url.startsWith('https://')}');
  print('ends with /raya:     ${url.endsWith('/raya')}');
  print('starts with a word:  ${url.startsWith(RegExp(r'[a-z]+:'))}');
}
Output
starts with https:   true
ends with /raya:     true
starts with a word:  true
indexOfmethod
int indexOf(Pattern pattern, [int start = 0])

Returns the position of the first match of pattern in this string, starting at start, inclusive:

const string = 'Rayaisans';
print(string.indexOf('art')); // 1
print(string.indexOf(RegExp(r'[A-Z][a-z]'))); // 0

Returns -1 if no match is found:

const string = 'Rayaisans';
string.indexOf(RegExp(r'raya')); // -1

The start must be non-negative and not greater than length.

Example
void main() {
  const s = 'banana';
  print('indexOf("an"):        ${s.indexOf('an')}');
  print('indexOf("an", 2):     ${s.indexOf('an', 2)}');
  print('indexOf("x"):         ${s.indexOf('x')}');
  print('lastIndexOf("an"):    ${s.lastIndexOf('an')}');
  // Every position of "a".
  final at = <int>[];
  for (var i = s.indexOf('a'); i != -1; i = s.indexOf('a', i + 1)) at.add(i);
  print('every "a":            $at');
}
Output
indexOf("an"):        1
indexOf("an", 2):     3
indexOf("x"):         -1
lastIndexOf("an"):    3
every "a":            [1, 3, 5]
int lastIndexOf(Pattern pattern, [int? start])

The starting position of the last match pattern in this string.

Finds a match of pattern by searching backward starting at start:

const string = 'Rayaisans';
print(string.lastIndexOf('a')); // 6
print(string.lastIndexOf(RegExp(r'a(r|n)'))); // 6

Returns -1 if pattern could not be found in this string.

const string = 'Rayaisans';
print(string.lastIndexOf(RegExp(r'RAYA'))); // -1

If start is omitted, search starts from the end of the string. If supplied, start must be non-negative and not greater than length.

Example
void main() {
  const path = 'docs/guide/intro.md';
  final slash = path.lastIndexOf('/');
  final dot = path.lastIndexOf('.');
  print('folder:    ${path.substring(0, slash)}');
  print('file:      ${path.substring(slash + 1)}');
  print('extension: ${path.substring(dot + 1)}');
}
Output
folder:    docs/guide
file:      intro.md
extension: md
substringmethod
String substring(int start, [int? end])

The substring of this string from start, inclusive, to end, exclusive.

Example:

const string = 'rayalang';
var result = string.substring(1); // 'artlang'
result = string.substring(1, 4); // 'art'

Both start and end must be non-negative and no greater than length; end, if provided, must be greater than or equal to start.

Example
void main() {
  const s = 'Hello, Raya!';
  print('substring(7):     ${s.substring(7)}');
  print('substring(0, 5):  ${s.substring(0, 5)}');
  print('substring(7, 11): ${s.substring(7, 11)}');
  print('last 5:           ${s.substring(s.length - 5)}');
}
Output
substring(7):     Raya!
substring(0, 5):  Hello
substring(7, 11): Raya
last 5:           Raya!
trimmethod
String trim()

The string without any leading and trailing whitespace.

If the string contains leading or trailing whitespace, a new string with no leading and no trailing whitespace is returned:

final trimmed = '\tRaya is fun\n'.trim();
print(trimmed); // 'Raya is fun'

Otherwise, the original string itself is returned:

const string1 = 'Raya';
final string2 = string1.trim(); // 'Raya'
print(identical(string1, string2)); // true

Whitespace is defined by the Unicode White_Space property (as defined in version 6.2 or later) and the BOM character, 0xFEFF.

Here is the list of trimmed characters according to Unicode version 6.3:

0009..D    ; White_Space # Cc   <control-0009>..<control-D>
0020          ; White_Space # Zs   SPACE
0085          ; White_Space # Cc   <control-0085>
A0          ; White_Space # Zs   NO-BREAK SPACE
1680          ; White_Space # Zs   OGHAM SPACE MARK
2000..A    ; White_Space # Zs   EN QUAD..HAIR SPACE
2028          ; White_Space # Zl   LINE SEPARATOR
2029          ; White_Space # Zp   PARAGRAPH SEPARATOR
F          ; White_Space # Zs   NARROW NO-BREAK SPACE
F          ; White_Space # Zs   MEDIUM MATHEMATICAL SPACE
3000          ; White_Space # Zs   IDEOGRAPHIC SPACE

FEFF          ; BOM                ZERO WIDTH NO_BREAK SPACE

Some later versions of Unicode do not include U+0085 as a whitespace character. Whether it is trimmed depends on the Unicode version used by the system.

Example
void main() {
  const raw = '\t  padded text \n';
  print('trim:      [${raw.trim()}]');
  print('trimLeft:  [${raw.trimLeft().replaceAll('\n', r'\n')}]');
  print('trimRight: [${raw.trimRight().replaceAll('\t', r'\t')}]');
  print('length before ${raw.length}, after ${raw.trim().length}');
}
Output
trim:      [padded text]
trimLeft:  [padded text \n]
trimRight: [\t  padded text]
length before 16, after 11
trimLeftmethod
String trimLeft()

The string without any leading whitespace.

As trim, but only removes leading whitespace.

final string = ' Raya '.trimLeft();
print(string); // 'Raya '
Example
void main() {
  const s = '   indented text  ';
  print("trimLeft:  '${s.trimLeft()}'");
  print("trimRight: '${s.trimRight()}'");
  print("tabs too:  '${'\t\n x'.trimLeft()}'");
}
Output
trimLeft:  'indented text  '
trimRight: '   indented text'
tabs too:  'x'
trimRightmethod
String trimRight()

The string without any trailing whitespace.

As trim, but only removes trailing whitespace.

final string = ' Raya '.trimRight();
print(string); // ' Raya'
Example
void main() {
  final lines = ['total   ', 'items\t', 'done'];
  print(lines.map((l) => '[${l.trimRight()}]').join(' '));
  print("leading space kept: '${'  x  '.trimRight()}'");
}
Output
[total] [items] [done]
leading space kept: '  x'
padLeftmethod
String padLeft(int width, [String padding = ' '])

Pads this string on the left if it is shorter than width.

Returns a new string that prepends padding onto this string one time for each position the length is less than width.

const string = 'D';
print(string.padLeft(4)); // '   D'
print(string.padLeft(2, 'x')); // 'xD'
print(string.padLeft(4, 'y')); // 'yyyD'
print(string.padLeft(4, '>>')); // '>>>>>>D'

If width is already smaller than or equal to this.length, no padding is added. A negative width is treated as zero.

If padding has length different from 1, the result will not have length width. This may be useful for cases where the padding is a longer string representing a single character, like "&nbsp;" or "\u{10002}". In that case, the user should make sure that this.length is the correct measure of the string's length.

Example
void main() {
  print('zero-padded: ${'7'.padLeft(3, '0')}');
  print('already long: ${'12345'.padLeft(3, '0')}');
  // Right-align a column of numbers.
  for (final n in [5, 42, 1234]) {
    print('|${n.toString().padLeft(6)}|');
  }
}
Output
zero-padded: 007
already long: 12345
|     5|
|    42|
|  1234|
padRightmethod
String padRight(int width, [String padding = ' '])

Pads this string on the right if it is shorter than width.

Returns a new string that appends padding after this string one time for each position the length is less than width.

const string = 'D';
print(string.padRight(4)); // 'D    '
print(string.padRight(2, 'x')); // 'Dx'
print(string.padRight(4, 'y')); // 'Dyyy'
print(string.padRight(4, '>>')); // 'D>>>>>>'

If width is already smaller than or equal to this.length, no padding is added. A negative width is treated as zero.

If padding has length different from 1, the result will not have length width. This may be useful for cases where the padding is a longer string representing a single character, like "&nbsp;" or "\u{10002}". In that case, the user should make sure that this.length is the correct measure of the string's length.

Example
void main() {
  final rows = {'apples': 3, 'kiwis': 12, 'figs': 7};
  rows.forEach((name, n) {
    print('${name.padRight(8, '.')} $n');
  });
}
Output
apples.. 3
kiwis... 12
figs.... 7
containsmethod
bool contains(Pattern other, [int startIndex = 0])

Whether this string contains a match of other.

Example:

const string = 'Raya strings';
final containsD = string.contains('D'); // true
final containsUpperCase = string.contains(RegExp(r'[A-Z]')); // true

If startIndex is provided, this method matches only at or after that index:

const string = 'Raya strings';
final containsD = string.contains(RegExp('D'), 0); // true
final caseSensitive = string.contains(RegExp(r'[A-Z]'), 1); // false

The startIndex must not be negative or greater than length.

Example
void main() {
  const s = 'The quick brown fox';
  print('contains "quick":  ${s.contains('quick')}');
  print('contains "Quick":  ${s.contains('Quick')}');
  print('contains a digit:  ${s.contains(RegExp(r'\d'))}');
  print('"quick" after 10:  ${s.contains('quick', 10)}');
}
Output
contains "quick":  true
contains "Quick":  false
contains a digit:  false
"quick" after 10:  false
String replaceFirst(Pattern from, String to, [int startIndex = 0])

Creates a new string with the first occurrence of from replaced by to.

Finds the first match of from in this string, starting from startIndex, and creates a new string where that match is replaced with the to string.

Example:

'0.0001'.replaceFirst(RegExp(r'0'), ''); // '.0001'
'0.0001'.replaceFirst(RegExp(r'0'), '7', 1); // '0.7001'
Example
void main() {
  print('${'one one one'.replaceFirst('one', 'ONE')}');
  print('${'one one one'.replaceFirst('one', 'ONE', 2)}');
}
Output
ONE one one
one ONE one
String replaceFirstMapped(Pattern from, String replace(Match match), [int startIndex = 0])

Replace the first occurrence of from in this string.

const string = 'Raya is fun';
print(string.replaceFirstMapped(
    'fun', (m) => 'open source')); // Raya is open source

print(string.replaceFirstMapped(
    RegExp(r'\w(\w*)'), (m) => '<${m[0]}-${m[1]}>')); // <Raya-art> is fun

Returns a new string, which is this string except that the first match of from, starting from startIndex, is replaced by the result of calling replace with the match object.

The startIndex must be non-negative and no greater than length.

Example
void main() {
  const s = 'price 10, tax 2';
  print(s.replaceFirstMapped(RegExp(r'\d+'), (m) => '${int.parse(m[0]!) * 2}'));
  print(s.replaceFirstMapped(RegExp(r'\d+'), (m) => '<${m[0]}>', 8));
}
Output
price 20, tax 2
price 10, tax <2>
String replaceAll(Pattern from, String replace)

Replaces all substrings that match from with replace.

Creates a new string in which the non-overlapping substrings matching from (the ones iterated by from.allMatches(thisString)) are replaced by the literal string replace.

'resume'.replaceAll(RegExp(r'e'), 'é'); // 'résumé'

Notice that the replace string is not interpreted. If the replacement depends on the match (for example, on a RegExp's capture groups), use the replaceAllMapped method instead.

Example
void main() {
  print('plain:  ${'a-b-c'.replaceAll('-', ' + ')}');
  print('regexp: ${'x1y22z333'.replaceAll(RegExp(r'\d+'), '#')}');
  print('remove: ${'h e l l o'.replaceAll(' ', '')}');
}
Output
plain:  a + b + c
regexp: x#y#z#
remove: hello
String replaceAllMapped(Pattern from, String Function(Match match) replace)

Replace all substrings that match from by a computed string.

Creates a new string in which the non-overlapping substrings that match from (the ones iterated by from.allMatches(thisString)) are replaced by the result of calling replace on the corresponding Match object.

This can be used to replace matches with new content that depends on the match, unlike replaceAll where the replacement string is always the same.

The replace function is called with the Match generated by the pattern, and its result is used as replacement.

The function defined below converts each word in a string to simplified 'pig latin' using replaceAllMapped:

String pigLatin(String words) => words.replaceAllMapped(
    RegExp(r'\b(\w*?)([aeiou]\w*)', caseSensitive: false),
    (Match m) => "${m[2]}${m[1]}${m[1]!.isEmpty ? 'way' : 'ay'}");

final result = pigLatin('I have a secret now!');
print(result); // 'Iway avehay away ecretsay ownay!'
Example
void main() {
  final s = 'price: 3 apples, 10 pears';
  final doubled = s.replaceAllMapped(RegExp(r'\d+'), (m) => '${int.parse(m[0]!) * 2}');
  print('doubled: $doubled');
  final snake = 'parseHttpRequestLine'.replaceAllMapped(RegExp(r'[A-Z]'), (m) => '_${m[0]!.toLowerCase()}');
  print('snake_case: $snake');
}
Output
doubled: price: 6 apples, 20 pears
snake_case: parse_http_request_line
String replaceRange(int start, int? end, String replacement)

Replaces the substring from start to end with replacement.

Creates a new string equivalent to:

this.substring(0, start) + replacement + this.substring(end)

Example:

const string = 'Raya is fun';
final result = string.replaceRange(8, null, 'open source');
print(result); // Raya is open source

The start and end indices must specify a valid range of this string. That is 0 <= start <= end <= this.length. If end is null, it defaults to length.

Example
void main() {
  const s = 'Hello world';
  print(s.replaceRange(6, 11, 'Raya'));
  print(s.replaceRange(0, 0, '>> '));
}
Output
Hello Raya
>> Hello world
splitmethod
List<String> split(Pattern pattern)

Splits the string at matches of pattern and returns a list of substrings.

Finds all the matches of pattern in this string, as by using Pattern.allMatches, and returns the list of the substrings between the matches, before the first match, and after the last match.

const string = 'Hello world!';
final splitted = string.split(' ');
print(splitted); // [Hello, world!];

If the pattern doesn't match this string at all, the result is always a list containing only the original string.

If the pattern is a String, then it's always the case that:

string.split(pattern).join(pattern) == string

If the first match is an empty match at the start of the string, the empty substring before it is not included in the result. If the last match is an empty match at the end of the string, the empty substring after it is not included in the result. If a match is empty, and it immediately follows a previous match (it starts at the position where the previous match ended), then the empty substring between the two matches is not included in the result.

const string = 'abba';
final re = RegExp(r'b*');
// re.allMatches(string) will find four matches:
// * empty match before first "a".
// * match of "bb"
// * empty match after "bb", before second "a"
// * empty match after second "a".
print(string.split(re)); // [a, a]

A non-empty match at the start or end of the string, or after another match, is not treated specially, and will introduce empty substrings in the result:

const string = 'abbaa';
final splitted = string.split('a'); // ['', 'bb', '', '']

If this string is the empty string, the result is an empty list if pattern matches the empty string, since the empty string before and after the first-and-last empty match are not included. (It is still a list containing the original empty string [""] if the pattern doesn't match).

const string = '';
print(string.split('')); // []
print(string.split('a')); // []

Splitting with an empty pattern splits the string into single-code unit strings.

const string = 'Pub';
print(string.split('')); // [P, u, b]

// Same as:
var codeUnitStrings = [
  for (final unit in string.codeUnits) String.fromCharCode(unit)
];
print(codeUnitStrings); // [P, u, b]

Splitting happens at UTF-16 code unit boundaries, and not at rune (Unicode code point) boundaries:

// String made up of two code units, but one rune.
const string = '\u{1D11E}';
final splitted = string.split('');
print(splitted); // ['\ud834', '\udd1e'] - 2 unpaired surrogate values

To get a list of strings containing the individual runes of a string, you should not use split. You can instead get a string for each rune as follows:

const string = '\u{1F642}';
for (final rune in string.runes) {
  print(String.fromCharCode(rune));
}
Example
void main() {
  print('commas:   ${'red,green,,blue'.split(',')}');
  print('spaces:   ${'one two  three'.split(' ')}');
  print('regexp:   ${'one two  three'.split(RegExp(r'\s+'))}');
  print('chars:    ${'Raya'.split('')}');
  final csv = 'name=Ada;age=36';
  for (final pair in csv.split(';')) {
    final kv = pair.split('=');
    print('key ${kv[0]} -> value ${kv[1]}');
  }
}
Output
commas:   [red, green, , blue]
spaces:   [one, two, , three]
regexp:   [one, two, three]
chars:    [R, a, y, a]
key name -> value Ada
key age -> value 36
String splitMapJoin(Pattern pattern, {String Function(Match)? onMatch, String Function(String)? onNonMatch})

Splits the string, converts its parts, and combines them into a new string.

The pattern is used to split the string into parts and separating matches. Each match of Pattern.allMatches of pattern on this string is used as a match, and the substrings between the end of one match (or the start of the string) and the start of the next match (or the end of the string) is treated as a non-matched part. (There is no omission of leading or trailing empty matchs, like in split, all matches and parts between the are included.)

Each match is converted to a string by calling onMatch. If onMatch is omitted, the matched substring is used.

Each non-matched part is converted to a string by a call to onNonMatch. If onNonMatch is omitted, the non-matching substring itself is used.

Then all the converted parts are concatenated into the resulting string.

final result = 'Eats shoots leaves'.splitMapJoin(RegExp(r'shoots'),
    onMatch: (m) => '${m[0]}', // (or no onMatch at all)
    onNonMatch: (n) => '*');
print(result); // *shoots*
Example
void main() {
  final out = 'a1b22c'.splitMapJoin(RegExp(r'\d+'),
      onMatch: (m) => '<${m[0]}>', onNonMatch: (s) => s.toUpperCase());
  print(out);
}
Output
A<1>B<22>C
String toLowerCase()

Converts all characters in this string to lower case.

If the string is already in all lower case, this method returns this.

'ALPHABET'.toLowerCase(); // 'alphabet'
'abc'.toLowerCase(); // 'abc'

This function uses the language independent Unicode mapping and thus only works in some languages.

Example
void main() {
  final words = ['Apple', 'banana', 'Cherry', 'apple'];
  final unique = words.map((w) => w.toLowerCase()).toSet();
  print('lower-cased: $unique');
}
Output
lower-cased: {apple, banana, cherry}
String toUpperCase()

Converts all characters in this string to upper case.

If the string is already in all upper case, this method returns this.

'alphabet'.toUpperCase(); // 'ALPHABET'
'ABC'.toUpperCase(); // 'ABC'

This function uses the language independent Unicode mapping and thus only works in some languages.

Example
void main() {
  const s = 'Raya docs';
  print('upper: ${s.toUpperCase()}');
  print('lower: ${s.toLowerCase()}');
  print('same ignoring case: ${'HeLLo'.toLowerCase() == 'hello'}');
}
Output
upper: RAYA DOCS
lower: raya docs
same ignoring case: true

Operators

operator []operator
String operator [](int index)

The character (as a single-code-unit String) at the given index.

The returned string represents exactly one UTF-16 code unit, which may be half of a surrogate pair. A single member of a surrogate pair is an invalid UTF-16 string:

var clef = '\u{1D11E}';
// These represent invalid UTF-16 strings.
clef[0].codeUnits;      // [0xD834]
clef[1].codeUnits;      // [0xDD1E]

This method is equivalent to String.fromCharCode(this.codeUnitAt(index)).

Example
void main() {
  const s = 'Raya';
  print('s[0] = ${s[0]}');
  print('s[3] = ${s[s.length - 1]}');
}
Output
s[0] = R
s[3] = a
operator ==operator
bool operator ==(Object other)

Whether other is a String with the same sequence of code units.

This method compares each individual code unit of the strings. It does not check for Unicode equivalence. For example, both the following strings represent the string 'Amélie', but due to their different encoding, are not equal:

'Am\xe9lie' == 'Ame\u{301}lie'; // false

The first string encodes 'é' as a single unicode code unit (also a single rune), whereas the second string encodes it as 'e' with the combining accent character '◌́'.

Example
void main() {
  final a = 'ra' + 'ya';
  print("'raya' == a: ${'raya' == a}");
  print("case matters: ${'Raya' == 'raya'}");
  print("compare ignoring case: ${'Raya'.toLowerCase() == 'raya'}");
}
Output
'raya' == a: true
case matters: false
compare ignoring case: true
operator +operator
String operator +(String other)

Creates a new string by concatenating this string with other.

Example:

const string = 'raya' + 'lang'; // 'rayalang'
Example
void main() {
  const first = 'Ada', last = 'Lovelace';
  print(first + ' ' + last);
  print('length: ${(first + last).length}');
}
Output
Ada Lovelace
length: 11
operator *operator
String operator *(int times)

Creates a new string by concatenating this string with itself a number of times.

The result of str * n is equivalent to str + str +...(n times)... + str.

const string = 'Raya';
final multiplied = string * 3;
print(multiplied); // 'RayaRayaRaya'

Returns an empty string if times is zero or negative.

Example
void main() {
  print('${'ab' * 3}');
  print('${'-' * 20}');
  print('[${'x' * 0}]');
}
Output
ababab
--------------------
[]
class

Runes

final class Runes extends Iterable<int>

The runes (integer Unicode code points) of a String.

The characters of a string are encoded in UTF-16. Decoding UTF-16, which combines surrogate pairs, yields Unicode code points. Following a similar terminology to Go, Raya uses the name 'rune' for an integer representing a Unicode code point. Use the runes property to get the runes of a string.

Example:

const string = 'Raya';
final runes = string.runes.toList();
print(runes); // [68, 97, 114, 116]

For a character outside the Basic Multilingual Plane (plane 0) that is composed of a surrogate pair, runes combines the pair and returns a single integer.

For example, the Unicode character for "Man" emoji ('👨', U+1F468) is combined from the surrogates U+d83d and U+dc68.

Example:

const emojiMan = '👨';
print(emojiMan.runes); // (128104)

// Surrogate pairs:
for (final item in emojiMan.codeUnits) {
  print(item.toRadixString(16));
  // d83d
  // dc68
}

See also:

Example
void main() {
  final r = 'héllo 🌍'.runes;
  print('code points: ${r.length}');
  print('last: ${String.fromCharCode(r.last)}');
  print('hex: ${r.map((c) => c.toRadixString(16)).join(' ')}');
}
Output
code points: 7
last: 🌍
hex: 68 e9 6c 6c 6f 20 1f30d

Constructors

Runesconstructor
Runes(this.string)

Creates a Runes iterator for string.

Example
void main() {
  final r = Runes('a€😀');
  print('code points: ${r.toList()}');
  print('runes: ${r.length}, UTF-16 units: ${r.string.length}');
}
Output
code points: [97, 8364, 128512]
runes: 3, UTF-16 units: 4

Properties

stringfield
final String string

The string that this is the runes of.

iteratorgetter
RuneIterator get iterator
lastgetter
int get last
final class RuneIterator implements Iterator<int>

Iterator for reading runes (integer Unicode code points) of a Raya string.

Constructors

RuneIteratorconstructor
RuneIterator(String string)

Create an iterator positioned at the beginning of the string.

Example
void main() {
  final it = RuneIterator('h😀!');
  while (it.moveNext()) {
    print('rune ${it.current} at ${it.rawIndex}, ${it.currentSize} unit(s): ${it.currentAsString}');
  }
}
Output
rune 104 at 0, 1 unit(s): h
rune 128512 at 1, 2 unit(s): 😀
rune 33 at 3, 1 unit(s): !
RuneIterator.atconstructor
RuneIterator.at(String string, int index)

Create an iterator positioned before the indexth code unit of the string.

When created, there is no current value. A moveNext will use the rune starting at index the current value, and a movePrevious will use the rune ending just before index as the current value.

The index position must not be in the middle of a surrogate pair.

Example
void main() {
  final it = RuneIterator.at('abcd', 2);
  print('before moveNext, current: ${it.current}');
  it.moveNext();
  print('after moveNext: ${it.currentAsString} at ${it.rawIndex}');
}
Output
before moveNext, current: -1
after moveNext: c at 2

Properties

stringfield
final String string

String being iterated.

rawIndexgetter
int get rawIndex

The starting position of the current rune in the string.

Returns -1 if there is no current rune (current is -1).

rawIndexsetter
void set rawIndex(int rawIndex)

Resets the iterator to the rune at the specified index of the string.

Setting a negative rawIndex, or one greater than or equal to string.length, is an error. So is setting it in the middle of a surrogate pair.

Setting the position to the end of the string means that there is no current rune.

Example
void main() {
  final it = RuneIterator('raya');
  it.rawIndex = 2;
  print('rawIndex = 2 -> current ${it.currentAsString}');
  it.moveNext();
  print('moveNext -> ${it.currentAsString}');
}
Output
rawIndex = 2 -> current y
moveNext -> a
currentgetter
int get current

The rune (integer Unicode code point) starting at the current position in the string.

The value is -1 if there is no current code point.

int get currentSize

The number of code units comprising the current rune.

Returns zero if there is no current rune (current is -1).

String get currentAsString

A string containing the current rune.

For runes outside the basic multilingual plane, this will be a String of length 2, containing two code units.

Returns an empty string if there is no current value.

Methods

resetmethod
void reset([int rawIndex = 0])

Resets the iterator to the given index into the string.

After this the current value is unset. You must call moveNext make the rune at the position current, or movePrevious for the last rune before the position.

The rawIndex must be non-negative and no greater than string.length. It must also not be the index of the trailing surrogate of a surrogate pair.

Example
void main() {
  final it = RuneIterator('xyz');
  it.moveNext();
  it.moveNext();
  print('at ${it.currentAsString}');
  it.reset();
  it.moveNext();
  print('after reset + moveNext: ${it.currentAsString}');
  it.reset(2);
  print('reset(2) then moveNext: ${(it..moveNext()).currentAsString}');
}
Output
at y
after reset + moveNext: x
reset(2) then moveNext: z
moveNextmethod
bool moveNext()

Move to the next code point.

Returns true and updates current if there is a next code point. Returns false otherwise, and then there is no current code point.

Example
void main() {
  final it = RuneIterator('ab');
  print('moveNext: ${it.moveNext()} -> ${it.currentAsString}');
  print('moveNext: ${it.moveNext()} -> ${it.currentAsString}');
  print('moveNext: ${it.moveNext()} (past the end)');
}
Output
moveNext: true -> a
moveNext: true -> b
moveNext: false (past the end)
bool movePrevious()

Move back to the previous code point.

Returns true and updates current if there is a previous code point. Returns false otherwise, and then there is no current code point.

Example
void main() {
  final it = RuneIterator.at('a😀b', 3);
  final back = <String>[];
  while (it.movePrevious()) {
    back.add(it.currentAsString);
  }
  print('walking backwards: $back');
}
Output
walking backwards: [😀, a]
class StringBuffer implements StringSink

A class for concatenating strings efficiently.

Allows for the incremental building of a string using write* methods. The strings are concatenated to a single string only when toString is called.

Example:

final buffer = StringBuffer('RAYA');
print(buffer.length); // 4

To add the string representation of an object, as returned by Object.toString, to the buffer, use write. Is also used for adding a string directly.

buffer.write(' is open source');
print(buffer.length); // 19
print(buffer); // RAYA is open source

const int rayaYear = 2011;
buffer
  ..write(' since ') // Writes a string.
  ..write(rayaYear); // Writes an int.
print(buffer); // RAYA is open source since 2011
print(buffer.length); // 30

To add a newline after the object's string representation, use writeln. Calling writeln with no argument adds a single newline to the buffer.

buffer.writeln(); // Contains "RAYA is open source since 2011\n".
buffer.writeln('-' * (buffer.length - 1)); // 30 '-'s and a newline.
print(buffer.length); // 62

To write multiple objects to the buffer, use writeAll.

const separator = '-';
buffer.writeAll(['Raya', 'is', 'fun!'], separator);
print(buffer.length); // 74
print(buffer);
// RAYA is open source since 2011
// ------------------------------
// Raya-is-fun!

To add the string representation of a Unicode code point, charCode, to the buffer, use writeCharCode.

buffer.writeCharCode(0x0A); // LF (line feed)
buffer.writeCharCode(0x44); // 'D'
buffer.writeCharCode(0x61); // 'a'
buffer.writeCharCode(0x72); // 'r'
buffer.writeCharCode(0x74); // 't'
print(buffer.length); // 79

To convert the content to a single string, use toString.

final text = buffer.toString();
print(text);
// RAYA is open source since 2011
// ------------------------------
// Raya-is-fun!
// Raya

To clear the buffer, so that it can be reused, use clear.

buffer.clear();
print(buffer.isEmpty); // true
print(buffer.length); // 0
Example
void main() {
  final sb = StringBuffer('Table:');
  sb.writeln();
  for (var i = 1; i <= 3; i++) {
    sb.writeln('$i x 7 = ${i * 7}');
  }
  sb.writeAll(['a', 'b', 'c'], ', ');
  print(sb.toString());
  print('length: ${sb.length}');
}
Output
Table:
1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
a, b, c
length: 46

Constructors

StringBufferconstructor
external StringBuffer([Object content = ""])

Creates a string buffer containing the provided content.

Example
void main() {
  final sb = StringBuffer('start');
  sb.write(':');
  sb.writeAll([1, 2, 3], ',');
  print('buffer: $sb, length ${sb.length}');
}
Output
buffer: start:1,2,3, length 11

Properties

lengthgetter
external int get length

Returns the length of the content that has been accumulated so far. This is a constant-time operation.

isEmptygetter
bool get isEmpty

Returns whether the buffer is empty. This is a constant-time operation.

bool get isNotEmpty

Returns whether the buffer is not empty. This is a constant-time operation.

Methods

writemethod
external void write(Object? object)
Example
void main() {
  final sb = StringBuffer();
  sb.write('Hello');
  sb.write(', ');
  sb.write(42);
  sb.writeCharCode(0x21);
  print(sb);
}
Output
Hello, 42!
external void writeCharCode(int charCode)
Example
void main() {
  final sb = StringBuffer();
  for (final c in [82, 97, 121, 97]) {
    sb.writeCharCode(c);
  }
  sb.writeCharCode(0x2713);
  print(sb);
}
Output
Raya✓
writeAllmethod
external void writeAll(Iterable<dynamic> objects, [String separator = ""])
Example
void main() {
  final sb = StringBuffer()..writeAll([1, 2, 3], ' + ')..write(' = 6');
  print(sb);
}
Output
1 + 2 + 3 = 6
writelnmethod
external void writeln([Object? obj = ""])

Writes the string representation of object followed by a newline.

Equivalent to buffer.write(object) followed by buffer.write("\n").

The newline is always represented as "\n", and does not use a platform specific line ending, e.g. "\r\n" on Windows.

Notice that calling buffer.writeln(null) will write the "null" string before the newline. Omitting the argument, or explicitly passing an empty string, is the recommended way to emit just the newline.

Example
void main() {
  final sb = StringBuffer();
  sb.writeln('first');
  sb.writeln();
  sb.writeln(3.5);
  print('lines: ${sb.toString().split('\n')}');
}
Output
lines: [first, , 3.5, ]
clearmethod
external void clear()

Clears the string buffer.

Example
void main() {
  final sb = StringBuffer('draft');
  sb.clear();
  print("after clear: '$sb', isEmpty ${sb.isEmpty}");
  sb.write('final');
  print('reused: $sb');
}
Output
after clear: '', isEmpty true
reused: final
toStringmethod
external String toString()

Returns the contents of buffer as a single string.

Example
void main() {
  final sb = StringBuffer();
  for (var i = 1; i <= 5; i++) {
    sb
      ..write(i)
      ..write(i < 5 ? ' + ' : ' = ');
  }
  sb.write(15);
  final s = sb.toString();
  print(s);
  print('a String: ${s is String}, length ${s.length}');
}
Output
1 + 2 + 3 + 4 + 5 = 15
a String: true, length 22
abstract interface class StringSink

Methods

writemethod
void write(Object? object)

Writes the string representation of object.

Converts object to a string using object.toString.

Notice that calling sink.write(null) will will write the "null" string.

Example
void report(StringSink out) {
  out.write('items: ');
  out.write(3);
  out.write(', ok: ');
  out.write(true);
}

void main() {
  final sb = StringBuffer();
  report(sb);
  print(sb);
}
Output
items: 3, ok: true
writeAllmethod
void writeAll(Iterable<dynamic> objects, [String separator = ""])

Writes the elements of objects separated by separator.

Writes the string representation of every element of objects, in iteration order, and writes separator between any two elements.

sink.writeAll(["Hello", "World"], " Beautiful ");

Is equivalent to:

sink
  ..write("Hello");
  ..write(" Beautiful ");
  ..write("World");
Example
void main() {
  final StringSink out = StringBuffer();
  out.writeAll(['a', 'b', 'c'], ' | ');
  out.write(' / ');
  out.writeAll([1, 2, 3]);
  print(out);
}
Output
a | b | c / 123
writelnmethod
void writeln([Object? object = ""])

Writes the string representation of object followed by a newline.

Equivalent to buffer.write(object) followed by buffer.write("\n").

Notice that calling buffer.writeln(null) will write the "null" string before the newline. Omitting the argument, or explicitly passing an empty string, is the recommended way to emit just the newline.

Example
void main() {
  final StringSink out = StringBuffer();
  out.writeln('name: Ada');
  out.writeln('year: 1843');
  print(out.toString().trimRight());
}
Output
name: Ada
year: 1843
void writeCharCode(int charCode)

Writes a string containing the character with code point charCode.

Equivalent to write(String.fromCharCode(charCode)).

Example
void main() {
  final StringSink out = StringBuffer();
  for (var c = 0x41; c <= 0x45; c++) {
    out.writeCharCode(c);
  }
  print(out);
}
Output
ABCDE
class

Symbol

abstract class Symbol

Opaque name used by mirrors, invocations and Function.apply.

Constructors

Symbolfactory
const factory Symbol(String name) = internal.Symbol

Constructs a new Symbol representing the provided name.

Symbols created from equal name strings are themselves equal. If the symbols are created using const, symbols with the same name strings are canonicalized and identical.

Some name strings create symbols which can also be created using a symbol literal, or be implicitly created while running Raya programs, for example through Object.noSuchMethod.

That is #foo == Symbol("foo") and identical(#foo, const Symbol("foo")).

If name is a single identifier that does not start with an underscore followed by a =, then the symbol is a setter name, and can be equal to the Invocation.memberName in an Object.noSuchMethod invocation.

Private symbol literals, like #_foo, cannot be created using the symbol constructor. A symbol like const Symbol("_foo") is not equal to any symbol literal, or to any source name symbol introduced by noSuchMethod.

assert(Symbol("foo") == Symbol("foo"));
assert(Symbol("foo") == #foo);
assert(identical(const Symbol("foo"), const Symbol("foo")));
assert(identical(const Symbol("foo"), #foo));
assert(Symbol("[]=") == #[]=);
assert(identical(const Symbol("[]="), #[]=));
assert(Symbol("foo.bar") == #foo.bar);
assert(identical(const Symbol("foo.bar"), #foo.bar));

The created instance overrides [Object.==].

Example
void main() {
  const s = Symbol('greet');
  print('Symbol(greet) == #greet: ${s == #greet}');
  print('different names differ: ${#greet == #wave}');
}
Output
Symbol(greet) == #greet: true
different names differ: false

Static

unaryMinusconstant
static const Symbol unaryMinus = Symbol("unary-")

The symbol corresponding to the name of the unary minus operator.

emptyconstant
static const Symbol empty = Symbol("")

The empty symbol.

The empty symbol is the name of libraries with no library declaration, and the base-name of the unnamed constructor.

Properties

hashCodegetter
int get hashCode

Returns a hash code compatible with [operator==].

Equal symbols have the same hash code.

Operators

operator ==operator
bool operator ==(Object other)

Symbols are equal to other symbols with an equal (==) name string.

Symbols representing library private names also need to represent names from the same library.

Example
void main() {
  print('#a == #a: ${#a == #a}');
  print("const Symbol('a') == #a: ${const Symbol('a') == #a}");
  print('#a == #b: ${#a == #b}');
}
Output
#a == #a: true
const Symbol('a') == #a: true
#a == #b: false
class

Type

abstract interface class Type

Runtime representation of a type.

Type objects represent types. A type object can be created in several ways:

  • By a type literal, a type name occurring as an expression, like Type type = int;, or a type variable occurring as an expression, like Type type = T;.
  • By reading the run-time type of an object, like Type type = o.runtimeType;.
  • Through raya:mirrors.

A type object is intended as an entry point for using raya:mirrors. The only operations supported are comparing to other type objects for equality, and converting it to a string for debugging.

Properties

hashCodegetter
int get hashCode

A hash code for the type which is compatible with [operator==].

Methods

toStringmethod
String toString()

Returns a string which represents the underlying type.

The string is only intended for providing information to a reader while debugging. There is no guaranteed format, the string value returned for a Type instances is entirely implementation dependent.

The string should be consistent, so a Type object for the same type returns the same string throughout a program execution. The string may or may not contain parts corresponding to the source name of declaration of the type, if the type has a source name at all (some types reachable through raya:mirrors may not).

Example
class Engine {}

void main() {
  const Type t = int;
  print('int: ${t.toString()}');
  print('List<String>: ${<String>[].runtimeType == List<String>}');
  print('Engine: ${Engine().runtimeType}');
}
Output
int: int
List<String>: true
Engine: Engine

Operators

operator ==operator
bool operator ==(Object other)

Whether other is a Type instance representing an equivalent type.

The language specification dictates which types are considered to be the equivalent. If two types are equivalent, it's guaranteed that they are subtypes of each other, but there are also types which are subtypes of each other, and which are not equivalent (for example dynamic and void, or FutureOr<Object> and Object).

Example
void main() {
  print('1.runtimeType == int: ${1.runtimeType == int}');
  print("'x'.runtimeType == String: ${'x'.runtimeType == String}");
  print('int == double: ${int == double}');
}
Output
1.runtimeType == int: true
'x'.runtimeType == String: true
int == double: false
class

Uri

abstract interface class Uri

A parsed URI, such as a URL.

To create a URI with specific components, use Uri.new:

var httpsUri = Uri(
    scheme: 'https',
    host: 'example.com',
    path: 'language/built-in-types',
    fragment: 'numbers');
print(httpsUri); // https://example.com/language/built-in-types#numbers

httpsUri = Uri(
    scheme: 'https',
    host: 'example.com',
    path: '/page/',
    queryParameters: {'search': 'blue', 'limit': '10'});
print(httpsUri); // https://example.com/page/?search=blue&limit=10

final mailtoUri = Uri(
    scheme: 'mailto',
    path: 'John.Doe@example.com',
    queryParameters: {'subject': 'Example'});
print(mailtoUri); // mailto:John.Doe@example.com?subject=Example
HTTP and HTTPS URI

To create a URI with https scheme, use Uri.https or Uri.http:

final httpsUri = Uri.https('example.com', 'api/fetch', {'limit': '10'});
print(httpsUri); // https://example.com/api/fetch?limit=10
File URI

To create a URI from file path, use Uri.file:

final fileUriUnix =
    Uri.file(r'/home/myself/images/image.png', windows: false);
print(fileUriUnix); // file:///home/myself/images/image.png

final fileUriWindows =
    Uri.file(r'C:\Users\myself\Documents\image.png', windows: true);
print(fileUriWindows); // file:///C:/Users/myself/Documents/image.png

If the URI is not a file URI, calling this throws UnsupportedError.

Directory URI

Like Uri.file except that a non-empty URI path ends in a slash.

final fileDirectory =
    Uri.directory('/home/myself/data/image', windows: false);
print(fileDirectory); // file:///home/myself/data/image/

final fileDirectoryWindows = Uri.directory('/data/images', windows: true);
print(fileDirectoryWindows); //  file:///data/images/
URI from string

To create a URI from string, use Uri.parse or Uri.tryParse:

final uri = Uri.parse(
    'https://example.com/libraries/raya-core#utility-classes');
print(uri); // https://example.com
print(uri.isScheme('https')); // true
print(uri.origin); // https://example.com
print(uri.host); // example.com
print(uri.authority); // example.com
print(uri.port); // 443
print(uri.path); // libraries/raya-core
print(uri.pathSegments); // [libraries, raya-core]
print(uri.fragment); // utility-classes
print(uri.hasQuery); // false
print(uri.data); // null

See also:

Constructors

Urifactory
factory Uri({String? scheme, String? userInfo, String? host, int? port, String? path, Iterable<String>? pathSegments, String? query, Map<String, dynamic >? queryParameters, String? fragment}) = _Uri

Creates a new URI from its components.

Each component is set through a named argument. Any number of components can be provided. The path and query components can be set using either of two different named arguments.

The scheme component is set through scheme. The scheme is normalized to all lowercase letters. If the scheme is omitted or empty, the URI will not have a scheme part.

The user info part of the authority component is set through userInfo. It defaults to the empty string, which will be omitted from the string representation of the URI.

The host part of the authority component is set through host. The host can either be a hostname, an IPv4 address or an IPv6 address, contained in '[' and ']'. If the host contains a ':' character, the '[' and ']' are added if not already provided. The host is normalized to all lowercase letters.

The port part of the authority component is set through port. If port is omitted or null, it implies the default port for the URI's scheme, and is equivalent to passing that port explicitly. The recognized schemes, and their default ports, are "http" (80) and "https" (443). All other schemes are considered as having zero as the default port.

If any of userInfo, host or port are provided, the URI has an authority according to hasAuthority.

The path component is set through either path or pathSegments. When path is used, it should be a valid URI path, but invalid characters, except the general delimiters ':/@[]?#', will be escaped if necessary. A backslash, \, will be converted to a slash /. When pathSegments is used, each of the provided segments is first percent-encoded and then joined using the forward slash separator.

The percent-encoding of the path segments encodes all characters except for the unreserved characters and the following list of characters: !$&'*+;=:@. If the other components necessitate an absolute path, a leading slash / is prepended if not already there.

The query component is set through either query or queryParameters. When query is used, the provided string should be a valid URI query, but invalid characters, other than general delimiters, will be escaped if necessary. When queryParameters is used, the query is built from the provided map. Each key and value in the map is percent-encoded and joined using equal and ampersand characters. A value in the map must be either null, a string, or an Iterable of strings. An iterable corresponds to multiple values for the same key, and an empty iterable or null corresponds to no value for the key.

The percent-encoding of the keys and values encodes all characters except for the unreserved characters, and replaces spaces with +. If query is the empty string, it is equivalent to omitting it. To have an actual empty query part, use an empty map for queryParameters.

If both query and queryParameters are omitted or null, the URI has no query part.

The fragment component is set through fragment. It should be a valid URI fragment, but invalid characters other than general delimiters are escaped if necessary. If fragment is omitted or null, the URI has no fragment part.

Example:

final httpsUri = Uri(
    scheme: 'https',
    host: 'example.com',
    path: 'language/built-in-types',
    fragment: 'numbers');
print(httpsUri); // https://example.com/language/built-in-types#numbers

final mailtoUri = Uri(
    scheme: 'mailto',
    path: 'John.Doe@example.com',
    queryParameters: {'subject': 'Example'});
print(mailtoUri); // mailto:John.Doe@example.com?subject=Example
Example
void main() {
  final u = Uri(scheme: 'https', host: 'example.com', path: 'search', queryParameters: {'q': 'rational points', 'page': '2'});
  print(u);
  print('query: ${u.query}');
  print('q: ${u.queryParameters['q']}');
}
Output
https://example.com/search?q=rational+points&page=2
query: q=rational+points&page=2
q: rational points
Uri.httpfactory
factory Uri.http(String authority, [String unencodedPath, Map<String, dynamic >? queryParameters]) = _Uri.http

Creates a new http URI from authority, path and query.

Example:

var uri = Uri.http('example.org', '/path', { 'q' : 'raya' });
print(uri); // http://example.org/path?q=raya

uri = Uri.http('user:password@localhost:8080', '');
print(uri); // http://user:password@localhost:8080

uri = Uri.http('example.org', 'a b');
print(uri); // http://example.org/a%20b

uri = Uri.http('example.org', '/a%2F');
print(uri); // http://example.org/a%252F

The scheme is always set to http.

The userInfo, host and port components are set from the authority argument. If authority is null or empty, the created Uri has no authority, and isn't directly usable as an HTTP URL, which must have a non-empty host.

The path component is set from the unencodedPath argument. The path passed must not be encoded as this constructor encodes the path. Only / is recognized as path separator. If omitted, the path defaults to being empty.

The query component is set from the optional queryParameters argument.

Example
void main() {
  final u = Uri.http('example.com', '/api/items', {'limit': '10'});
  print(u);
  print('scheme ${u.scheme}, path ${u.path}, port ${u.port}');
}
Output
http://example.com/api/items?limit=10
scheme http, path /api/items, port 80
Uri.httpsfactory
factory Uri.https(String authority, [String unencodedPath, Map<String, dynamic>? queryParameters]) = _Uri.https

Creates a new https URI from authority, path and query.

This constructor is the same as Uri.http except for the scheme which is set to https.

Example:

var uri = Uri.https('example.org', '/path', {'q': 'raya'});
print(uri); // https://example.org/path?q=raya

uri = Uri.https('user:password@localhost:8080', '');
print(uri); // https://user:password@localhost:8080

uri = Uri.https('example.org', 'a b');
print(uri); // https://example.org/a%20b

uri = Uri.https('example.org', '/a%2F');
print(uri); // https://example.org/a%252F
Example
void main() {
  final u = Uri.https('example.org', '/search', {'q': 'quadrance & spread', 'page': '2'});
  print(u);
  print(u.queryParameters['q']);
}
Output
https://example.org/search?q=quadrance+%26+spread&page=2
quadrance & spread
Uri.filefactory
factory Uri.file(String path, {bool? windows}) = _Uri.file

Creates a new file URI from an absolute or relative file path.

The file path is passed in path.

This path is interpreted using either Windows or non-Windows semantics.

With non-Windows semantics, the slash (/) is used to separate path segments in the input path.

With Windows semantics, backslash (\) and forward-slash (/) are used to separate path segments in the input path, except if the path starts with \\?\ in which case only backslash (\) separates path segments in path.

If the path starts with a path separator, an absolute URI (with the file scheme and an empty authority) is created. Otherwise a relative URI reference with no scheme or authority is created. One exception to this rule is that when Windows semantics is used and the path starts with a drive letter followed by a colon (":") and a path separator, then an absolute URI is created.

The default for whether to use Windows or non-Windows semantics is determined from the platform Raya is running on. When running in the standalone VM, this is detected by the VM based on the operating system. When running in a browser, non-Windows semantics is always used.

To override the automatic detection of which semantics to use pass a value for windows. Passing true will use Windows semantics and passing false will use non-Windows semantics.

Examples using non-Windows semantics:

// xxx/yyy
Uri.file('xxx/yyy', windows: false);

// xxx/yyy/
Uri.file('xxx/yyy/', windows: false);

// file:///xxx/yyy
Uri.file('/xxx/yyy', windows: false);

// file:///xxx/yyy/
Uri.file('/xxx/yyy/', windows: false);

// C%3A
Uri.file('C:', windows: false);

Examples using Windows semantics:

// xxx/yyy
Uri.file(r'xxx\yyy', windows: true);

// xxx/yyy/
Uri.file(r'xxx\yyy\', windows: true);

file:///xxx/yyy
Uri.file(r'\xxx\yyy', windows: true);

file:///xxx/yyy/
Uri.file(r'\xxx\yyy/', windows: true);

// file:///C:/xxx/yyy
Uri.file(r'C:\xxx\yyy', windows: true);

// This throws an error. A path with a drive letter, but no following
// path, is not allowed.
Uri.file(r'C:', windows: true);

// This throws an error. A path with a drive letter is not absolute.
Uri.file(r'C:xxx\yyy', windows: true);

// file://server/share/file
Uri.file(r'\\server\share\file', windows: true);

If the path passed is not a valid file path, an error is thrown.

Example
void main() {
  final posix = Uri.file('/home/ada/notes.txt', windows: false);
  print('posix:   $posix');
  final win = Uri.file(r'C:\Users\ada\notes.txt', windows: true);
  print('windows: $win');
  print('relative: ${Uri.file('docs/a b.txt', windows: false)}');
}
Output
posix:   file:///home/ada/notes.txt
windows: file:///C:/Users/ada/notes.txt
relative: docs/a%20b.txt
factory Uri.directory(String path, {bool? windows}) = _Uri.directory

Like Uri.file except that a non-empty URI path ends in a slash.

If path is not empty, and it doesn't end in a directory separator, then a slash is added to the returned URI's path. In all other cases, the result is the same as returned by Uri.file.

Example:

final fileDirectory = Uri.directory('data/images', windows: false);
print(fileDirectory); // data/images/

final fileDirectoryWindows =
   Uri.directory(r'C:\data\images', windows: true);
print(fileDirectoryWindows); // file:///C:/data/images/
Example
void main() {
  final d = Uri.directory('/srv/www', windows: false);
  print('directory: $d (ends with /)');
  print('resolve child: ${d.resolve('index.html')}');
}
Output
directory: file:///srv/www/ (ends with /)
resolve child: file:///srv/www/index.html
factory Uri.dataFromString(String content, {String? mimeType, Encoding? encoding, Map<String, String>? parameters, bool base64 = false})

Creates a data: URI containing the content string.

Converts the content to bytes using encoding or the charset specified in parameters (defaulting to US-ASCII if not specified or unrecognized), then encodes the bytes into the resulting data URI.

Defaults to encoding using percent-encoding (any non-ASCII or non-URI-valid bytes is replaced by a percent encoding). If base64 is true, the bytes are instead encoded using base64.

If encoding is not provided and parameters has a charset entry, that name is looked up using Encoding.getByName, and if the lookup returns an encoding, that encoding is used to convert content to bytes. If providing both an encoding and a charset in parameters, they should agree, otherwise decoding won't be able to use the charset parameter to determine the encoding.

If mimeType and/or parameters are supplied, they are added to the created URI. If any of these contain characters that are not allowed in the data URI, the character is percent-escaped. If the character is non-ASCII, it is first UTF-8 encoded and then the bytes are percent encoded. An omitted mimeType in a data URI means text/plain, just as an omitted charset parameter defaults to meaning US-ASCII.

To read the content back, use UriData.contentAsString.

Example:

final uri = Uri.dataFromString(
  'example content',
  mimeType: 'text/plain',
  parameters: <String, String>{'search': 'file', 'max': '10'},
);
print(uri); // data:;search=name;max=10,example%20content
Example
void main() {
  final u = Uri.dataFromString('Hi, Raya!', mimeType: 'text/plain');
  print(u);
  print('back: ${u.data!.contentAsString()}');
}
Output
data:,Hi,%20Raya!
back: Hi, Raya!
factory Uri.dataFromBytes(List<int> bytes, {String mimeType = "application/octet-stream", Map<String, String>? parameters, bool percentEncoded = false})

Creates a data: URI containing an encoding of bytes.

Defaults to Base64 encoding the bytes, but if percentEncoded is true, the bytes will instead be percent encoded (any non-ASCII or non-valid-ASCII-character byte is replaced by a percent encoding).

To read the bytes back, use UriData.contentAsBytes.

It defaults to having the mime-type application/octet-stream. The mimeType and parameters are added to the created URI. If any of these contain characters that are not allowed in the data URI, the character is percent-escaped. If the character is non-ASCII, it is first UTF-8 encoded and then the bytes are percent encoded.

Example:

final uri = Uri.dataFromBytes([68, 97, 114, 116]);
print(uri); // data:application/octet-stream;base64,RGFydA==
Example
void main() {
  final u = Uri.dataFromBytes([0, 1, 2, 250, 255]);
  print(u);
  print('bytes back: ${u.data!.contentAsBytes()}');
}
Output
data:application/octet-stream;base64,AAEC+v8=
bytes back: [0, 1, 2, 250, 255]

Static

basestaticgetter
external static Uri get base

The natural base URI for the current platform.

When running in a browser, this is the current URL of the current page (from window.location.href).

When not running in a browser, this is the file URI referencing the current working directory.

parsestaticmethod
static Uri parse(String uri, [int start = 0, int? end])

Creates a new Uri object by parsing a URI string.

If start and end are provided, they must specify a valid substring of uri, and only the substring from start to end is parsed as a URI.

If the uri string is not valid as a URI or URI reference, a FormatException is thrown.

Example:

final uri =
    Uri.parse('https://example.com/api/fetch?limit=10,20,30&max=100');
print(uri); // https://example.com/api/fetch?limit=10,20,30&max=100

Uri.parse('::Not valid URI::'); // Throws FormatException.
Example
void main() {
  final u = Uri.parse('https://riptidecompute.com:8443/raya/docs?q=svd&lib=cpu#top');
  print('scheme: ${u.scheme}');
  print('host:   ${u.host}');
  print('port:   ${u.port}');
  print('path:   ${u.path}');
  print('segments: ${u.pathSegments}');
  print('query:  ${u.queryParameters}');
  print('fragment: ${u.fragment}');
}
Output
scheme: https
host:   riptidecompute.com
port:   8443
path:   /raya/docs
segments: [raya, docs]
query:  {q: svd, lib: cpu}
fragment: top
tryParsestaticmethod
static Uri? tryParse(String uri, [int start = 0, int? end])

Creates a new Uri object by parsing a URI string.

If start and end are provided, they must specify a valid substring of uri, and only the substring from start to end is parsed as a URI.

Returns null if the uri string is not valid as a URI or URI reference.

Example:

final uri = Uri.tryParse(
    'https://example.com/libraries/raya-core#utility-classes', 0, 16);
print(uri); // https://example.com

var notUri = Uri.tryParse('::Not valid URI::');
print(notUri); // null
Example
void main() {
  print('valid:   ${Uri.tryParse('https://example.com/a?b=1')?.host}');
  print('invalid: ${Uri.tryParse('http://[::1')}');
  print('substring: ${Uri.tryParse('see <https://x.org/p> here', 5, 20)}');
}
Output
valid:   example.com
invalid: null
substring: https://x.org/p
encodeComponentstaticmethod
static String encodeComponent(String component)

Encode the string component using percent-encoding to make it safe for literal use as a URI component.

All characters except uppercase and lowercase letters, digits and the characters -_.!~*' are percent-encoded. This is the set of characters specified in RFC 2396 and which is specified for the encodeUriComponent in ECMA-262 version 5.1.

When manually encoding path segments or query components, remember to encode each part separately before building the path or query string.

For encoding the query part consider using encodeQueryComponent.

To avoid the need for explicitly encoding, use the pathSegments and queryParameters optional named arguments when constructing a Uri.

Example:

const request = 'http://example.com/search=Raya';
final encoded = Uri.encodeComponent(request);
print(encoded); // http%3A%2F%2Fexample.com%2Fsearch%3DRaya
Example
void main() {
  const s = 'a b&c=d/é';
  final enc = Uri.encodeComponent(s);
  print('encoded: $enc');
  print('decoded: ${Uri.decodeComponent(enc)}');
  print('query:   ${Uri.encodeQueryComponent(s)}');
}
Output
encoded: a%20b%26c%3Dd%2F%C3%A9
decoded: a b&c=d/é
query:   a+b%26c%3Dd%2F%C3%A9
static String encodeQueryComponent(String component, {Encoding encoding = utf8})

Encodes the string component according to the HTML 4.01 rules for encoding the posting of a HTML form as a query string component.

The component is first encoded to bytes using encoding. The default is to use utf8 encoding, which preserves all the characters that don't need encoding.

Then the resulting bytes are "percent-encoded". This transforms spaces (U+0020) to a plus sign ('+') and all bytes that are not the ASCII decimal digits, letters or one of '-._~' are written as a percent sign '%' followed by the two-digit hexadecimal representation of the byte.

Note that the set of characters which are percent-encoded is a superset of what HTML 4.01 requires, since it refers to RFC 1738 for reserved characters.

When manually encoding query components remember to encode each part separately before building the query string.

To avoid the need for explicitly encoding the query use the queryParameters optional named arguments when constructing a Uri.

See https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 for more details.

Example
void main() {
  print(Uri.encodeQueryComponent('a&b = c/d'));
  print(Uri.encodeQueryComponent('café'));
}
Output
a%26b+%3D+c%2Fd
caf%C3%A9
decodeComponentstaticmethod
static String decodeComponent(String encodedComponent)

Decodes the percent-encoding in encodedComponent.

Note that decoding a URI component might change its meaning as some of the decoded characters could be characters which are delimiters for a given URI component type. Always split a URI component using the delimiters for the component before decoding the individual parts.

For handling the path and query components, consider using pathSegments and queryParameters to get the separated and decoded component.

Example:

final decoded =
    Uri.decodeComponent('http%3A%2F%2Fexample.com%2Fsearch%3DRaya');
print(decoded); // http://example.com/search=Raya
Example
void main() {
  print(Uri.decodeComponent('a%20b%2Fc%26d'));
  print(Uri.decodeComponent('caf%C3%A9'));
  print('round trip: ${Uri.decodeComponent(Uri.encodeComponent('x y/z?')) == 'x y/z?'}');
}
Output
a b/c&d
café
round trip: true
static String decodeQueryComponent(String encodedComponent, {Encoding encoding = utf8})

Decodes the percent-encoding in encodedComponent, converting pluses to spaces.

It will create a byte-list of the decoded characters, and then use encoding to decode the byte-list to a String. The default encoding is UTF-8.

Example
void main() {
  print(Uri.decodeQueryComponent('a+b%3Dc'));
  print('decodeComponent keeps +: ${Uri.decodeComponent('a+b')}');
}
Output
a b=c
decodeComponent keeps +: a+b
encodeFullstaticmethod
static String encodeFull(String uri)

Encodes the string uri using percent-encoding to make it safe for literal use as a full URI.

All characters except uppercase and lowercase letters, digits and the characters !#$&'*+,-./;=?@_~ are percent-encoded. This is the set of characters specified in ECMA-262 version 5.1 for the encodeURI function.

Example:

final encoded =
    Uri.encodeFull('https://example.com/api/query?search= raya is');
print(encoded); // https://example.com/api/query?search=%20raya%20is
Example
void main() {
  print(Uri.encodeFull('https://example.com/a path/?q=one two'));
  print('reserved / ? & kept, spaces encoded');
}
Output
https://example.com/a%20path/?q=one%20two
reserved / ? & kept, spaces encoded
decodeFullstaticmethod
static String decodeFull(String uri)

Decodes the percent-encoding in uri.

Note that decoding a full URI might change its meaning as some of the decoded characters could be reserved characters. In most cases, an encoded URI should be parsed into components using Uri.parse before decoding the separate components.

Example:

final decoded =
    Uri.decodeFull('https://example.com/api/query?search=%20raya%20is');
print(decoded); // https://example.com/api/query?search= raya is
Example
void main() {
  print(Uri.decodeFull('https://example.com/a%20path/?q=one%20two'));
}
Output
https://example.com/a path/?q=one two
splitQueryStringstaticmethod
static Map<String, String> splitQueryString(String query, {Encoding encoding = utf8})

Splits the query into a map according to the rules specified for FORM post in the [HTML 4.01 specification section 17.13.4](https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4 "HTML 4.01 section 17.13.4").

Each key and value in the returned map has been decoded. If the query is the empty string, an empty map is returned.

Keys in the query string that have no value are mapped to the empty string.

Each query component will be decoded using encoding. The default encoding is UTF-8.

Example:

final queryStringMap =
    Uri.splitQueryString('limit=10&max=100&search=Raya%20is%20fun');
print(jsonEncode(queryStringMap));
// {"limit":"10","max":"100","search":"Raya is fun"}
Example
void main() {
  print(Uri.splitQueryString('name=Ada%20Lovelace&born=1815'));
}
Output
{name: Ada Lovelace, born: 1815}
parseIPv4Addressstaticmethod
static List<int> parseIPv4Address(String host, [@Since('3.10') int start = 0, @Since('3.10') int? end])

Parses the host as an IP version 4 (IPv4) address, returning the address as a list of 4 bytes in network byte order (big endian).

If start and end are provided, only that range, which must be a valid range of host, is parsed. Defaults to all of host.

Throws a FormatException if (the range of) host is not a valid IPv4 address representation, meaning something of the form <octet>.<octet>.<octet>.<octet> where each octet is a decimal numeral in the range 0..255 with no leading zeros.

Example
void main() {
  print('192.168.1.20 -> ${Uri.parseIPv4Address('192.168.1.20')}');
  try {
    Uri.parseIPv4Address('300.1.1.1');
  } on FormatException catch (e) {
    print('300.1.1.1 -> FormatException: ${e.message}');
  }
}
Output
192.168.1.20 -> [192, 168, 1, 20]
300.1.1.1 -> FormatException: Illegal IPv4 address, each part must be in the range 0..255
parseIPv6Addressstaticmethod
static List<int> parseIPv6Address(String host, [int start = 0, int? end])

Parses the host as an IP version 6 (IPv6) address.

Returns the address as a list of 16 bytes in network byte order (big endian).

Throws a FormatException if host is not a valid IPv6 address representation.

Acts on the substring from start to end. If end is omitted, it defaults to the end of the string.

Some examples of IPv6 addresses:

  • :1
  • FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
  • 3ffe:2a00:100:7031:1
  • :FFFF:129.144.52.38
  • 2010:836B:4179:836B:4179

The grammar for IPv6 addresses are:

IPv6address ::=                           (h16 ":"){6} ls32
              |                      "::" (h16 ":"){5} ls32
              | (               h16) "::" (h16 ":"){4} ls32
              | ((h16 ":"){0,1} h16) "::" (h16 ":"){3} ls32
              | ((h16 ":"){0,2} h16) "::" (h16 ":"){2} ls32
              | ((h16 ":"){0,3} h16) "::"  h16 ":"     ls32
              | ((h16 ":"){0,4} h16) "::"              ls32
              | ((h16 ":"){0,5} h16) "::"              h16
              | ((h16 ":"){0,6} h16) "::"
ls32        ::= (h16 ":" h16) | IPv4address
                ;; least-significant 32 bits of address
h16         ::= HEXDIG{1,4}
                ;; 16 bits of address represented in hexadecimal

That is

  • Eight 1-to-4-digit hexadecimal numerals separated by :, or
  • One to seven such :-separated numerals, with either one pair is separated by :, or a leading or trailing :.
  • Either of the above with a trailing two :-separated numerals replaced by an IPv4 address.

An IPv6 address with a zone ID (from RFC 6874) is an IPv6 address followed by %25 (an escaped %) and valid zone characters.

IPv6addrz ::= IPv6address "%25" ZoneID
ZoneID    ::= (unreserved | pct-encoded)+
Example
void main() {
  final bytes = Uri.parseIPv6Address('::1');
  print('::1 -> ${bytes.length} bytes, last ${bytes.last}');
  print('2001:db8::ff -> ${Uri.parseIPv6Address('2001:db8::ff')}');
}
Output
::1 -> 16 bytes, last 1
2001:db8::ff -> [32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255]

Properties

schemegetter
String get scheme

The scheme component of the URI.

The value is the empty string if there is no scheme component.

A URI scheme is case insensitive. The returned scheme is canonicalized to lowercase letters.

authoritygetter
String get authority

The authority component.

The authority is formatted from the userInfo, host and port parts.

The value is the empty string if there is no authority component.

userInfogetter
String get userInfo

The user info part of the authority component.

The value is the empty string if there is no user info in the authority component.

hostgetter
String get host

The host part of the authority component.

The value is the empty string if there is no authority component and hence no host.

If the host is an IP version 6 address, the surrounding [ and ] is removed.

The host string is case-insensitive. The returned host name is canonicalized to lower-case with upper-case percent-escapes.

portgetter
int get port

The port part of the authority component.

The value is the default port if there is no port number in the authority component. That's 80 for http, 443 for https, and 0 for everything else.

pathgetter
String get path

The path component.

The path is the actual substring of the URI representing the path, and it is encoded where necessary. To get direct access to the decoded path, use pathSegments.

The path value is the empty string if there is no path component.

querygetter
String get query

The query component.

The value is the actual substring of the URI representing the query part, and it is encoded where necessary. To get direct access to the decoded query, use queryParameters.

The value is the empty string if there is no query component.

fragmentgetter
String get fragment

The fragment identifier component.

The value is the empty string if there is no fragment identifier component.

List<String> get pathSegments

The URI path split into its segments.

Each of the segments in the list has been decoded. If the path is empty, the empty list will be returned. A leading slash / does not affect the segments returned.

The list is unmodifiable and will throw UnsupportedError on any calls that would mutate it.

Map<String, String> get queryParameters

The URI query split into a map according to the rules specified for FORM post in the [HTML 4.01 specification section 17.13.4](https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4 "HTML 4.01 section 17.13.4").

Each key and value in the resulting map has been decoded. If there is no query, the empty map is returned.

Keys in the query string that have no value are mapped to the empty string. If a key occurs more than once in the query string, it is mapped to an arbitrary choice of possible value. The queryParametersAll getter can provide a map that maps keys to all of their values.

Example:

final uri =
    Uri.parse('https://example.com/api/fetch?limit=10,20,30&max=100');
print(jsonEncode(uri.queryParameters));
// {"limit":"10,20,30","max":"100"}

The map is unmodifiable.

Map<String, List<String>> get queryParametersAll

Returns the URI query split into a map according to the rules specified for FORM post in the [HTML 4.01 specification section 17.13.4](https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4 "HTML 4.01 section 17.13.4").

Each key and value in the resulting map has been decoded. If there is no query, the map is empty.

Keys are mapped to lists of their values. If a key occurs only once, its value is a singleton list. If a key occurs with no value, the empty string is used as the value for that occurrence.

Example:

final uri =
    Uri.parse('https://example.com/api/fetch?limit=10&limit=20&limit=30&max=100');
print(jsonEncode(uri.queryParametersAll)); // {"limit":["10","20","30"],"max":["100"]}

The map and the lists it contains are unmodifiable.

bool get isAbsolute

Whether the URI is absolute.

A URI is an absolute URI in the sense of RFC 3986 if it has a scheme and no fragment.

hasSchemegetter
bool get hasScheme

Whether the URI has a scheme component.

bool get hasAuthority

Whether the URI has an authority component.

hasPortgetter
bool get hasPort

Whether the URI has an explicit port.

If the port number is the default port number (zero for unrecognized schemes, with http (80) and https (443) being recognized), then the port is made implicit and omitted from the URI.

hasQuerygetter
bool get hasQuery

Whether the URI has a query part.

bool get hasFragment

Whether the URI has a fragment part.

bool get hasEmptyPath

Whether the URI has an empty path.

bool get hasAbsolutePath

Whether the URI has an absolute path (starting with '/').

origingetter
String get origin

Returns the origin of the URI in the form scheme://host:port for the schemes http and https.

It is an error if the scheme is not "http" or "https", or if the host name is missing or empty.

See: https://www.w3.org/TR/2011/WD-html5-20110405/origin-0.html#origin

datagetter
UriData? get data

Access the structure of a data: URI.

Returns a UriData object for data: URIs and null for all other URIs. The UriData object can be used to access the media type and data of a data: URI.

hashCodegetter
int get hashCode

Returns a hash code computed as toString.hashCode.

This guarantees that URIs with the same normalized string representation have the same hash code.

Methods

isSchememethod
bool isScheme(String scheme)

Whether the scheme of this Uri is scheme.

The scheme should be the same as the one returned by Uri.scheme, but doesn't have to be case-normalized to lower-case characters.

Example:

var uri = Uri.parse('http://example.com');
print(uri.isScheme('HTTP')); // true

final uriNoScheme = Uri(host: 'example.com');
print(uriNoScheme.isScheme('HTTP')); // false

An empty scheme string matches a URI with no scheme (one where hasScheme returns false).

Example
void main() {
  final u = Uri.parse('HTTPS://example.com');
  print("isScheme('https'): ${u.isScheme('https')}");
  print("isScheme('http'):  ${u.isScheme('http')}");
}
Output
isScheme('https'): true
isScheme('http'):  false
String toFilePath({bool? windows})

Creates a file path from a file URI.

The returned path has either Windows or non-Windows semantics.

For non-Windows semantics, the slash ("/") is used to separate path segments.

For Windows semantics, the backslash ("\\") separator is used to separate path segments.

If the URI is absolute, the path starts with a path separator unless Windows semantics is used and the first path segment is a drive letter. When Windows semantics is used, a host component in the uri in interpreted as a file server and a UNC path is returned.

The default for whether to use Windows or non-Windows semantics is determined from the platform Raya is running on. When running in the standalone VM, this is detected by the VM based on the operating system. When running in a browser, non-Windows semantics is always used.

To override the automatic detection of which semantics to use pass a value for windows. Passing true will use Windows semantics and passing false will use non-Windows semantics.

If the URI ends with a slash (i.e. the last path component is empty), the returned file path will also end with a slash.

With Windows semantics, URIs starting with a drive letter cannot be relative to the current drive on the designated drive. That is, for the URI file:///c:abc calling toFilePath will throw as a path segment cannot contain colon on Windows.

Examples using non-Windows semantics (resulting of calling toFilePath in comment):

Uri.parse("xxx/yyy");  // xxx/yyy
Uri.parse("xxx/yyy/");  // xxx/yyy/
Uri.parse("file:///xxx/yyy");  // /xxx/yyy
Uri.parse("file:///xxx/yyy/");  // /xxx/yyy/
Uri.parse("file:///C:");  // /C:
Uri.parse("file:///C:a");  // /C:a

Examples using Windows semantics (resulting URI in comment):

Uri.parse("xxx/yyy");  // xxx\yyy
Uri.parse("xxx/yyy/");  // xxx\yyy\
Uri.parse("file:///xxx/yyy");  // \xxx\yyy
Uri.parse("file:///xxx/yyy/");  // \xxx\yyy\
Uri.parse("file:///C:/xxx/yyy");  // C:\xxx\yyy
Uri.parse("file:C:xxx/yyy");  // Throws as a path segment
                              // cannot contain colon on Windows.
Uri.parse("file://server/share/file");  // \\server\share\file

If the URI is not a file URI, calling this throws UnsupportedError.

If the URI cannot be converted to a file path, calling this throws UnsupportedError.

Example
void main() {
  final u = Uri.parse('file:///home/ada/my%20notes.txt');
  print('posix:   ${u.toFilePath(windows: false)}');
  print('windows: ${Uri.parse('file:///C:/Users/ada/a.txt').toFilePath(windows: true)}');
}
Output
posix:   /home/ada/my notes.txt
windows: C:\Users\ada\a.txt
toStringmethod
String toString()

The normalized string representation of the URI.

Example
void main() {
  final u = Uri(scheme: 'mailto', path: 'ada@example.com', query: 'subject=Hello');
  print(u.toString());
  print(Uri.https('example.com', '/a b').toString());
}
Output
mailto:ada@example.com?subject=Hello
https://example.com/a%20b
replacemethod
Uri replace({String? scheme, String? userInfo, String? host, int? port, String? path, Iterable<String>? pathSegments, String? query, Map<String, dynamic >? queryParameters, String? fragment})

Creates a new Uri based on this one, but with some parts replaced.

This method takes the same parameters as the Uri constructor, and they have the same meaning.

At most one of path and pathSegments must be provided. Likewise, at most one of query and queryParameters must be provided.

Each part that is not provided will default to the corresponding value from this Uri instead.

This method is different from Uri.resolve, which overrides in a hierarchical manner, and can instead replace each part of a Uri individually.

Example:

final uri1 = Uri.parse(
    'https://example.com/libraries/raya-core#utility-classes');

final uri2 = uri1.replace(
    scheme: 'https',
    path: 'libraries/raya-core',
    fragment: 'uris');
print(uri2); // https://example.com/libraries/raya-core#uris

This method acts similarly to using the Uri constructor with some of the arguments taken from this Uri. Example:

final Uri uri3 = Uri(
    scheme: 'https',
    userInfo: uri1.userInfo,
    host: uri1.host,
    port: uri2.port,
    path: 'language/built-in-types',
    query: uri1.query,
    fragment: null);
print(uri3); // https://example.com/language/built-in-types

Using this method can be seen as shorthand for the Uri constructor call above, but may also be slightly faster because the parts taken from this Uri need not be checked for validity again.

Example
void main() {
  final u = Uri.parse('https://example.org/a?x=1');
  print(u.replace(path: '/b', queryParameters: {'y': '2'}));
  print(u.replace(scheme: 'http', port: 8080));
}
Output
https://example.org/b?y=2
http://example.org:8080/a?x=1
Uri removeFragment()

Creates a Uri that differs from this only in not having a fragment.

If this Uri does not have a fragment, it is itself returned.

Example:

final uri =
    Uri.parse('https://example.org:8080/foo/bar#frag').removeFragment();
print(uri); // https://example.org:8080/foo/bar
Example
void main() {
  final u = Uri.parse('https://example.com/docs#install');
  print('fragment: ${u.fragment}');
  print('without: ${u.removeFragment()}');
}
Output
fragment: install
without: https://example.com/docs
resolvemethod
Uri resolve(String reference)

Resolve reference as an URI relative to this.

First turn reference into a URI using Uri.parse. Then resolve the resulting URI relative to this.

Returns the resolved URI.

See resolveUri for details.

Example
void main() {
  final base = Uri.parse('https://example.org/docs/guide/intro.html');
  print(base.resolve('setup.html'));
  print(base.resolve('../api/index.html'));
  print(base.resolve('/about'));
}
Output
https://example.org/docs/guide/setup.html
https://example.org/docs/api/index.html
https://example.org/about
Uri resolveUri(Uri reference)

Resolve reference as a URI relative to this.

Returns the resolved URI.

The algorithm "Transform Reference" for resolving a reference is described in [RFC-3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5 "RFC-1123").

Updated to handle the case where the base URI is just a relative path - that is: when it has no scheme and no authority and the path does not start with a slash. In that case, the paths are combined without removing leading "..", and an empty path is not converted to "/".

Example
void main() {
  final base = Uri.parse('https://example.com/docs/guide/intro.html');
  print(base.resolveUri(Uri.parse('setup.html')));
  print(base.resolveUri(Uri.parse('../api/')));
  print(base.resolveUri(Uri.parse('/top')));
}
Output
https://example.com/docs/guide/setup.html
https://example.com/docs/api/
https://example.com/top
Uri normalizePath()

Returns a URI where the path has been normalized.

A normalized path does not contain . segments or non-leading .. segments. Only a relative path with no scheme or authority may contain leading .. segments; a path that starts with / will also drop any leading .. segments.

This uses the same normalization strategy as Uri.resolve(this).

Does not change any part of the URI except the path.

The default implementation of Uri always normalizes paths, so calling this function has no effect.

Example
void main() {
  final u = Uri.parse('https://example.com/a/./b/../c/');
  print(u.normalizePath());
}
Output
https://example.com/a/c/

Operators

operator ==operator
bool operator ==(Object other)

A URI is equal to another URI with the same normalized representation.

Example
void main() {
  final a = Uri.parse('https://example.com/x');
  final b = Uri(scheme: 'https', host: 'example.com', path: '/x');
  print('a == b: ${a == b}');
  print('case of host ignored: ${Uri.parse('https://EXAMPLE.com/x') == a}');
}
Output
a == b: true
case of host ignored: true
class

UriData

final class UriData

A way to access the structure of a data: URI.

Data URIs are non-hierarchical URIs that can contain any binary data. They are defined by RFC 2397.

This class allows parsing the URI text, extracting individual parts of the URI, as well as building the URI text from structured parts.

Constructors

factory UriData.fromString(String content, {String? mimeType, Encoding? encoding, Map<String, String>? parameters, bool base64 = false})

Creates a data: URI containing the content string.

Equivalent to Uri.dataFromString(...).data, but may be more efficient if the uri itself isn't used.

Example
void main() {
  final d = UriData.fromString('<b>hi</b>', mimeType: 'text/html');
  print(d);
  print('mime: ${d.mimeType}, content: ${d.contentAsString()}');
}
Output
data:text/html,%3Cb%3Ehi%3C/b%3E
mime: text/html, content: <b>hi</b>
factory UriData.fromBytes(List<int> bytes, {String mimeType = "application/octet-stream", Map<String, String>? parameters, bool percentEncoded = false})

Creates a data: URI containing an encoding of bytes.

Equivalent to Uri.dataFromBytes(...).data, but may be more efficient if the uri itself isn't used.

Example
void main() {
  final d = UriData.fromBytes([72, 105], mimeType: 'application/octet-stream');
  print(d);
  print('bytes: ${d.contentAsBytes()}');
}
Output
data:application/octet-stream;base64,SGk=
bytes: [72, 105]
factory UriData.fromUri(Uri uri)

Creates a DataUri from a Uri which must have data as Uri.scheme.

The uri must have scheme data and no authority or fragment, and the path (concatenated with the query, if there is one) must be valid as data URI content with the same rules as parse.

Example
void main() {
  final u = Uri.parse('data:text/plain;charset=utf-8,hello%20world');
  final d = UriData.fromUri(u);
  print('mime: ${d.mimeType}, charset: ${d.charset}');
  print('content: ${d.contentAsString()}');
}
Output
mime: text/plain, charset: utf-8
content: hello world

Static

parsestaticmethod
static UriData parse(String uri)

Parses a string as a data URI.

The string must have the format:

'data:' (type '/' subtype)? (';' attribute '=' value)* (';base64')? ',' data

Where type, subtype, attribute and value are specified in RFC-2045, and data is a sequence of URI-characters (RFC-2396 uric).

This means that all the characters must be ASCII, but the URI may contain percent-escapes for non-ASCII byte values that need an interpretation to be converted to the corresponding string.

Parsing checks that Base64 encoded data is valid, and it normalizes it to use the default Base64 alphabet and to use padding. Non-Base64 data is escaped using percent-escapes as necessary to make it valid, and existing escapes are case normalized.

Accessing the individual parts may fail later if they turn out to have content that cannot be decoded successfully as a string, for example if existing percent escapes represent bytes that cannot be decoded by the chosen Encoding (see contentAsString).

A FormatException is thrown if uri is not a valid data URI.

Example
void main() {
  final d = UriData.parse('data:;base64,SGVsbG8=');
  print('base64: ${d.isBase64}, mime: ${d.mimeType}');
  print('content: ${d.contentAsString()}');
}
Output
base64: true, mime: text/plain
content: Hello

Properties

urigetter
Uri get uri

The Uri that this UriData is giving access to.

Returns a Uri with scheme data and the remainder of the data URI as path.

mimeTypegetter
String get mimeType

The MIME type of the data URI.

A data URI consists of a "media type" followed by data. The media type starts with a MIME type and can be followed by extra parameters. If the MIME type representation in the URI text contains URI escapes, they are unescaped in the returned string. If the value contain non-ASCII percent escapes, they are decoded as UTF-8.

Example:

data:text/plain;charset=utf-8,Hello%World!

This data URI has the media type text/plain;charset=utf-8, which is the MIME type text/plain with the parameter charset with value utf-8. See RFC 2045 for more detail.

If the first part of the data URI is empty, it defaults to text/plain.

charsetgetter
String get charset

The charset parameter of the media type.

If the parameters of the media type contains a charset parameter then this returns its value, otherwise it returns US-ASCII, which is the default charset for data URIs. If the values contain non-ASCII percent escapes, they are decoded as UTF-8.

If the MIME type representation in the URI text contains URI escapes, they are unescaped in the returned string.

isBase64getter
bool get isBase64

Whether the data is Base64 encoded or not.

String get contentText

The content part of the data URI, as its actual representation.

This string may contain percent escapes.

Map<String, String> get parameters

A map representing the parameters of the media type.

A data URI may contain parameters between the MIME type and the data. This converts these parameters to a map from parameter name to parameter value. The map only contains parameters that actually occur in the URI. The charset parameter has a default value even if it doesn't occur in the URI, which is reflected by the charset getter. This means that charset may return a value even if parameters["charset"] is null.

If the values contain non-ASCII values or percent escapes, they are decoded as UTF-8.

Methods

bool isMimeType(String mimeType)

Whether the UriData.mimeType is equal to mimeType.

Compares the data: URI's MIME type to mimeType with a case- insensitive comparison which ignores the case of ASCII letters.

An empty mimeType is considered equivalent to text/plain, both in the mimeType argument and in the data: URI itself.

Example
void main() {
  final d = UriData.parse('data:Text/Plain,hi');
  print("isMimeType('text/plain'): ${d.isMimeType('text/plain')}");
  print("isMimeType('text/html'):  ${d.isMimeType('text/html')}");
}
Output
isMimeType('text/plain'): true
isMimeType('text/html'):  false
isCharsetmethod
bool isCharset(String charset)

Checks whether the charset parameter of the mime type is charset.

If this URI has no "charset" parameter, it is assumed to have a default of charset=US-ASCII. If charset is empty, it's treated like "US-ASCII".

Returns true if charset and the "charset" parameter value are equal strings, ignoring the case of ASCII letters, or both correspond to the same Encoding, as given by Encoding.getByName.

Example
void main() {
  final d = UriData.parse('data:text/plain;charset=UTF-8,hi');
  print("isCharset('utf-8'): ${d.isCharset('utf-8')}");
  print("isCharset('latin1'): ${d.isCharset('latin1')}");
}
Output
isCharset('utf-8'): true
isCharset('latin1'): false
bool isEncoding(Encoding encoding)

Whether the charset parameter represents encoding.

If the "charset" parameter is not present in the URI, it defaults to "US-ASCII", which is the ascii encoding. If present, it's converted to an Encoding using Encoding.getByName, and compared to encoding.

Example
import 'raya:convert';

void main() {
  final d = UriData.parse('data:text/plain;charset=iso-8859-1,caf%E9');
  print('isEncoding(latin1): ${d.isEncoding(latin1)}');
  print('isEncoding(utf8):   ${d.isEncoding(utf8)}');
  print('content: ${d.contentAsString()}');
}
Output
isEncoding(latin1): true
isEncoding(utf8):   false
content: café
Uint8List contentAsBytes()

The content part of the data URI as bytes.

If the data is Base64 encoded, it will be decoded to bytes.

If the data is not Base64 encoded, it will be decoded by unescaping percent-escaped characters and returning byte values of each unescaped character. The bytes will not be, e.g. UTF-8 decoded.

Example
void main() {
  final d = UriData.parse('data:application/octet-stream;base64,AAEC/w==');
  print('bytes: ${d.contentAsBytes()}');
}
Output
bytes: [0, 1, 2, 255]
String contentAsString({Encoding? encoding})

Creates a string from the content of the data URI.

If the content is Base64 encoded, it will be decoded to bytes and then decoded to a string using encoding. If encoding is omitted, the value of a charset parameter is used if it is recognized by Encoding.getByName; otherwise it defaults to the ascii encoding, which is the default encoding for data URIs that do not specify an encoding.

If the content is not Base64 encoded, it will first have percent-escapes converted to bytes and then the character codes and byte values are decoded using encoding.

Example
import 'raya:convert';

void main() {
  final d = UriData.fromString('naïve', encoding: utf8);
  print(d);
  print('decoded: ${d.contentAsString()}');
}
Output
data:;charset=utf-8,na%C3%AFve
decoded: naïve
toStringmethod
String toString()
Example
void main() {
  final d = UriData.fromString('a,b', mimeType: 'text/csv', base64: true);
  print(d.toString());
  print('as Uri: ${d.uri.scheme}');
}
Output
data:text/csv;base64,YSxi
as Uri: data
class

Expando

final class Expando<T extends Object>

An Expando allows adding new properties to objects.

Does not work on numbers, strings, booleans, records, null, raya:ffi pointers, raya:ffi structs, or raya:ffi unions.

An Expando does not hold on to the added property value after an object becomes inaccessible.

Since you can always create a new number that is identical to an existing number, it means that an expando property on a number could never be released. To avoid this, expando properties cannot be added to numbers. The same argument applies to strings, booleans and null, which also have literals that evaluate to identical values when they occur more than once. In addition, expando properties can not be added to records because records do not have a well-defined persistent identity.

There is no restriction on other classes, even for compile time constant objects. Be careful if adding expando properties to compile time constants, since they will stay alive forever.

Constructors

Expandoconstructor
external Expando([String? name])

Creates a new Expando. The optional name is only used for debugging purposes and creating two different Expandos with the same name yields two Expandos that work on different properties of the objects they are used on.

Example
class Node {
  final String id;
  Node(this.id);
}

void main() {
  // Attach extra data to objects without changing their class.
  final visited = Expando<bool>('visited');
  final a = Node('a'), b = Node('b');
  visited[a] = true;
  print('a visited: ${visited[a]}, b visited: ${visited[b]}');
}
Output
a visited: true, b visited: null

Properties

namefield
final String? name

The name of the this Expando as passed to the constructor.

If no name was passed to the constructor, the value is the null value.

Methods

toStringmethod
String toString()

Expando toString method override.

Example
void main() {
  print(Expando<int>('depth').toString());
  print(Expando<int>().toString());
}
Output
Expando:depth
Expando:null

Operators

operator []operator
external T? operator [](Object object)

Gets the value of this Expando's property on the given object.

If the object hasn't been expanded, the result is the null value.

The object must not be a number, a string, a boolean, a record, null, a raya:ffi pointer, a raya:ffi struct, or a raya:ffi union.

Example
void main() {
  final colour = Expando<String>();
  final key = Object();
  print('before: ${colour[key]}');
  colour[key] = 'red';
  print('after:  ${colour[key]}');
}
Output
before: null
after:  red
operator []=operator
external void operator []=(Object object, T? value)

Sets this Expando's property value on the given object to value.

Properties can effectively be removed again by setting their value to null.

The object must not be a number, a string, a boolean, a record, null, a raya:ffi pointer, a raya:ffi struct, or a raya:ffi union.

Example
void main() {
  final count = Expando<int>();
  final o = Object();
  for (var i = 0; i < 3; i++) {
    count[o] = (count[o] ?? 0) + 1;
  }
  print('count: ${count[o]}');
  count[o] = null;
  print('cleared: ${count[o]}');
}
Output
count: 3
cleared: null