dart.core


Functions
identical(Object a, Object b): bool
print(Object object): void
Typedefs
Comparator<T>(T a, T b): int
Classes
AbstractClassInstantiationError
ArgumentError
AssertionError
BidirectionalIterator
CastError
Comparable
ConcurrentModificationError
CyclicInitializationError
DateTime
Duration
Error
Exception
Expando
FallThroughError
FormatException
Function
IntegerDivisionByZeroException
Invocation
Iterable
Iterator
List
Map
Match
NoSuchMethodError
Null
NullThrownError
Object
OutOfMemoryError
Pattern
RangeError
RegExp
RuneIterator
Runes
Set
StackOverflowError
StackTrace
StateError
Stopwatch
String
StringBuffer
StringSink
Symbol
Type
TypeError
UnimplementedError
UnsupportedError
Uri
bool
double
int
num

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

This library is automatically imported.

Some classes in this library, such as String and num, support Dart'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 Dart'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.

StringBuffer moreShakespeare = new StringBuffer();
moreShakespeare.write('And all the men and women ');
moreShakespeare.write('merely players; ...');
The String and StringBuffer classes implement string concatenation, interpolation, and other string manipulation features.

String philosophy = 'Live on ';
String get palindrome => philosophy + philosophy.split('').reversed.join();
RegExp implements Dart regular expressions, which provide a grammar for matching patterns within text. For example, here's a regular expression that matches a string of one or more digits:

var numbers = new RegExp(r'\d+');
Dart 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 dart: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.

List superheroes = [ 'Batman', 'Superman', 'Harry Potter' ];
A Set is an unordered collection of unique objects. You cannot get an item by index (position). Adding a duplicate item has no effect.

Set villians = new Set();
villians.add('Joker');
villians.addAll( ['Lex Luther', 'Voldemort'] );
A Map is an unordered collection of key-value pairs. Maps are sometimes called associative arrays because maps associate a key to some value for easy retrieval. Keys are unique. Use a Map when you need to access objects by a unique identifier.

Map sidekicks = { 'Batman': 'Robin',
                  'Superman': 'Lois Lane',
                  'Harry Potter': 'Ron and Hermione' };
In addition to these classes, dart: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 length.

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

For other kinds of collections, check out the dart:collection(#dart-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.

DateTime now = new DateTime.now();
DateTime berlinWallFell = new DateTime(1989, 11, 9);
DateTime moonLanding = DateTime.parse("1969-07-20");
Create a Duration object specifying the individual time units.

Duration timeRemaining = new Duration(hours:56, minutes:14);
In addition to DateTime and Duration, dart:core contains the Stopwatch class for measuring elapsed time.
Uri

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

Uri dartlang = Uri.parse('http://dartlang.org/');
Errors

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

Other documentation

For more information about how to use the built-in types, refer to Built-in Types(http://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#built-in-types) in Chapter 2 of Dart: Up and Running(http://www.dartlang.org/docs/dart-up-and-running/).

Also, see dart:core - Numbers, Collections, Strings, and More(http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-dartcore---strings-collections-and-more) for more coverage of classes in this package.

The Dart Language Specification(http://www.dartlang.org/docs/spec/) provides technical details.

Functions

static bool identical(Object a, Object b)

Check whether two references are to the same object.

static void print(Object object)

Typedefs

typedef int Comparator<T>(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.

Class AbstractClassInstantiationError extends Error

Constructors
AbstractClassInstantiationError(String _className)
Methods
toString(): String

Constructors

AbstractClassInstantiationError(String _className)

Methods

String toString()

Returns a string representation of this object.


Class ArgumentError extends Error

Fields
message: dynamic
Constructors
ArgumentError(dynamic message)
Methods
toString(): String

Error thrown when a function is passed an unacceptable argument.

Fields

final dynamic message

Constructors

ArgumentError(dynamic message)

The message describes the erroneous argument.

Methods

String toString()

Returns a string representation of this object.


Class AssertionError extends Error

Constructors
AssertionError()

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

Constructors

AssertionError()

Abstract class BidirectionalIterator implements Iterator<E>

Constructors
BidirectionalIterator()
Methods
movePrevious(): bool

An Iterator that allows moving backwards as well as forwards.

Constructors

BidirectionalIterator()

Methods

bool movePrevious()

Move back to the previous element.

Returns true and updates current if successful. Returns false and sets current to null if there is no previous element.


Class CastError extends Error

Constructors
CastError()

Error thrown by the runtime system when a cast operation fails.

Constructors

CastError()

Abstract class Comparable

Constructors
Comparable()
Methods
compare(Comparable<dynamic> a, Comparable<dynamic> b): int
compareTo(T other): int

Interface used by types that have an intrinsic ordering.

Constructors

Comparable()

Methods

static int compare(Comparable<dynamic> a, Comparable<dynamic> b)

Compare one comparable to another.

This utility function is used as the default comparator for the List sort function.

int compareTo(T other)

Compares this object to another Comparable

Returns a value like a Comparator when comparing this to other.

May throw an ArgumentError if other is of a type that is not comparable to this.


Class ConcurrentModificationError extends Error

Fields
modifiedObject: Object
Constructors
ConcurrentModificationError(Object modifiedObject)
Methods
toString(): String

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.

Fields

final Object modifiedObject

The object that was modified in an incompatible way.

Constructors

ConcurrentModificationError(Object modifiedObject)

Methods

String toString()

Returns a string representation of this object.


Class CyclicInitializationError extends Error

Fields
variableName: String
Constructors
CyclicInitializationError(String variableName)
Methods
toString(): String

Error thrown when a lazily initialized variable cannot be initialized.

A static/library variable with an initializer expression is initialized the first time it is read. If evaluating the initializer expression causes another read of the variable, this error is thrown.

Fields

final String variableName

Constructors

CyclicInitializationError(String variableName)

Methods

String toString()

Returns a string representation of this object.


Class DateTime implements Comparable<dynamic>

Static Fields
APRIL: int
AUGUST: int
DAYS_PER_WEEK: int
DECEMBER: int
FEBRUARY: int
FRIDAY: int
JANUARY: int
JULY: int
JUNE: int
MARCH: int
MAY: int
MONDAY: int
MONTHS_PER_YEAR: int
NOVEMBER: int
OCTOBER: int
SATURDAY: int
SEPTEMBER: int
SUNDAY: int
THURSDAY: int
TUESDAY: int
WEDNESDAY: int
Fields
day: int
hashCode: int
hour: int
isUtc: bool
millisecond: int
millisecondsSinceEpoch: int
minute: int
month: int
second: int
timeZoneName: String
timeZoneOffset: Duration
weekday: int
year: int
Getters and Setters
day: int
hashCode: int
hour: int
millisecond: int
minute: int
month: int
second: int
timeZoneName: String
timeZoneOffset: Duration
weekday: int
year: int
Constructors
DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
DateTime.fromMillisecondsSinceEpoch(int millisecondsSinceEpoch, bool isUtc)
DateTime.now()
DateTime.utc(int year, int month, int day, int hour, int minute, int second, int millisecond)
Methods
==(dynamic other): bool
add(Duration duration): DateTime
compareTo(DateTime other): int
difference(DateTime other): Duration
isAfter(DateTime other): bool
isAtSameMomentAs(DateTime other): bool
isBefore(DateTime other): bool
parse(String formattedString): DateTime
subtract(Duration duration): DateTime
toLocal(): DateTime
toString(): String
toUtc(): DateTime

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

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 that hours are specified between 0 and 23, as in a 24-hour clock. For example:

DateTime now = new DateTime.now();
DateTime berlinWallFell = new DateTime(1989, 11, 9);
DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");  // 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.

assert(berlinWallFell.month == 11);
assert(moonLanding.hour == 20);
For convenience and readability, the DateTime class provides a constant for each day and month name&mdash;for example, AUGUST and FRIDAY. You can use these constants to improve code readibility:

DateTime berlinWallFell = new DateTime(1989, DateTime.NOVEMBER, 9);
assert(berlinWallFell.month == DateTime.SATURDAY);
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.

DateTime dDay = new DateTime.utc(1944, 6, 6);
   
Use isUtc to determine whether a DateTime object is based in UTC. Use the methods toLocal() and toUtc() to get the equivalent date/time value specified in the other time zone. Use timeZoneName to get an abbreviated name of the time zone for the DateTime object. To find the difference between UTC and the time zone of a DateTime object call timeZoneOffset.

Comparing DateTime objects

The DateTime class contains several handy methods, such as isAfter(), isBefore(), and isAtSameMomentAs(), for comparing DateTime objects.

assert(berlinWallFell.isAfter(moonLanding) == true);
assert(berlinWallFell.isBefore(moonLanding) == false);
Using DateTime with Duration

Use the add() and subtract() methods with a Duration object to create a new DateTime object based on another. For example, to find the date that is sixty days after today, write:

DateTime today = new DateTime.now();
DateTime sixtyDaysFromNow = today.add(new Duration(days: 60));
To find out how much time is between two DateTime objects use difference(), which returns a Duration object:

Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);
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(http://pub.dartlang.org/packages/intl) package.

Static Fields

static const int APRIL = 4
static const int AUGUST = 8
static const int DAYS_PER_WEEK = 7
static const int DECEMBER = 12
static const int FEBRUARY = 2
static const int FRIDAY = 5
static const int JANUARY = 1
static const int JULY = 7
static const int JUNE = 6
static const int MARCH = 3
static const int MAY = 5
static const int MONDAY = 1
static const int MONTHS_PER_YEAR = 12
static const int NOVEMBER = 11
static const int OCTOBER = 10
static const int SATURDAY = 6
static const int SEPTEMBER = 9
static const int SUNDAY = 7
static const int THURSDAY = 4
static const int TUESDAY = 2
static const int WEDNESDAY = 3

Fields

final int day
final int hashCode
final int hour
final bool isUtc

True if this DateTime is set to UTC time.

DateTime dDay = new DateTime.utc(1944, 6, 6);
assert(dDay.isUtc);

final int millisecond
final int 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.

final int minute
final int month
final int second
final String timeZoneName
final Duration timeZoneOffset
final int weekday
final int year

Getters and Setters

int get day

The day of the month 1..31.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.day == 20);

int get hashCode
int get hour

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

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.hour == 20);

int get millisecond

The millisecond 0...999.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.millisecond == 0);

int get minute

The minute 0...59.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.minute == 18);

int get month

The month 1..12.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.month == 7);
assert(moonLanding.month == DateTime.JULY);

int get second

The second 0...59.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.second == 0);

String get timeZoneName

The abbreviated time zone name&mdash;for example, "CET" or "CEST".

Duration get timeZoneOffset

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

The offset is positive for time zones west 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.

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.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.weekday == 7);
assert(moonLanding.weekday == DateTime.SUNDAY);

int get year

The year.

DateTime moonLanding = DateTime.parse("1969-07-20 20:18:00");
assert(moonLanding.year == 1969);

Constructors

factory DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)

Constructs a DateTime instance specified in the local time zone.

For example, to create a new DateTime object representing April 29, 2014, 6:04am:

DateTime annularEclipse = new DateTime(2014, DateTime.APRIL, 29, 6, 4);

DateTime.fromMillisecondsSinceEpoch(int millisecondsSinceEpoch, bool isUtc)

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

factory DateTime.now()

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

DateTime thisInstant = new DateTime.now();

factory DateTime.utc(int year, int month, int day, int hour, int minute, int second, int millisecond)

Constructs a DateTime instance specified in the UTC time zone.

DateTime dDay = new DateTime.utc(1944, DateTime.JUNE, 6);

Methods

bool ==(dynamic other)

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

DateTime dDayUtc   = new DateTime.utc(1944, DateTime.JUNE, 6);
DateTime dDayLocal = new DateTime(1944, DateTime.JUNE, 6);

assert(dDayUtc.isAtSameMomentAs(dDayLocal) == false);
See isAtSameMomentAs for a comparison that adjusts for time zone.

DateTime add(Duration duration)

Returns a new DateTime instance with duration added to this.

DateTime today = new DateTime.now();
DateTime sixtyDaysFromNow = today.add(new Duration(days: 60));

int compareTo(DateTime other)

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

This function returns a negative integer if this DateTime is smaller (earlier) than other, or a positive integer if it is greater (later).

Duration difference(DateTime other)

Returns a Duration with the difference between this and other.

DateTime berlinWallFell = new DateTime(1989, DateTime.NOVEMBER, 9);
DateTime dDay = new DateTime(1944, DateTime.JUNE, 6);

Duration difference = berlinWallFell.difference(dDay);
assert(difference.inDays == 16592);

bool isAfter(DateTime other)

Returns true if this occurs after other.

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

DateTime berlinWallFell = new DateTime(1989, 11, 9);
DateTime moonLanding    = DateTime.parse("1969-07-20 20:18:00");

assert(berlinWallFell.isAfter(moonLanding) == true);

bool isAtSameMomentAs(DateTime other)

Returns true if this occurs at the same moment as other.

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

DateTime berlinWallFell = new DateTime(1989, 11, 9);
DateTime moonLanding    = DateTime.parse("1969-07-20 20:18:00");

assert(berlinWallFell.isAtSameMomentAs(moonLanding) == false);

bool isBefore(DateTime other)

Returns true if this occurs before other.

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

DateTime berlinWallFell = new DateTime(1989, 11, 9);
DateTime moonLanding    = DateTime.parse("1969-07-20 20:18:00");

assert(berlinWallFell.isBefore(moonLanding) == false);

static DateTime parse(String formattedString)

Constructs a new DateTime instance based on formattedString.

The function parses a subset of ISO 8601. Examples of accepted strings:

  • "2012-02-27 13:27:00"
  • "2012-02-27 13:27:00.123456z"
  • "20120227 13:27:00"
  • "20120227T132700"
  • "20120227"
  • "+20120227"
  • "2012-02-27T14Z"
  • "-123450101 00:00:00 Z": in the year -12345.
DateTime subtract(Duration duration)

Returns a new DateTime instance with duration subtracted from this.

DateTime today = new DateTime.now();
DateTime sixtyDaysAgo = today.subtract(new Duration(days: 60));

DateTime toLocal()

Returns this DateTime value in the local time zone.

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

new DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch,
                                        isUtc: false)

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(http://pub.dartlang.org/packages/intl) package at the pub shared packages repo.

DateTime toUtc()

Returns this DateTime value in the UTC time zone.

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

new DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch,
                                        isUtc: true)


Class Duration implements Comparable<Duration>

Static Fields
HOURS_PER_DAY: int
MICROSECONDS_PER_DAY: int
MICROSECONDS_PER_HOUR: int
MICROSECONDS_PER_MILLISECOND: int
MICROSECONDS_PER_MINUTE: int
MICROSECONDS_PER_SECOND: int
MILLISECONDS_PER_DAY: int
MILLISECONDS_PER_HOUR: int
MILLISECONDS_PER_MINUTE: int
MILLISECONDS_PER_SECOND: int
MINUTES_PER_DAY: int
MINUTES_PER_HOUR: int
SECONDS_PER_DAY: int
SECONDS_PER_HOUR: int
SECONDS_PER_MINUTE: int
ZERO: Duration
Fields
hashCode: int
inDays: int
inHours: int
inMicroseconds: int
inMilliseconds: int
inMinutes: int
inSeconds: int
Getters and Setters
hashCode: int
inDays: int
inHours: int
inMicroseconds: int
inMilliseconds: int
inMinutes: int
inSeconds: int
Constructors
Duration(int days, int hours, int minutes, int seconds, int milliseconds, int microseconds)
Methods
*(num factor): Duration
+(Duration other): Duration
-(Duration other): Duration
<(Duration other): bool
<=(Duration other): bool
==(dynamic other): bool
>(Duration other): bool
>=(Duration other): bool
compareTo(Duration other): int
toString(): String
~/(int quotient): Duration

A span of time, such as 27 days, 4 hours, 12 minutes, and 3 seconds.

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

Duration fastestMarathon = new Duration(hours:2, minutes:3, seconds:2);
The Duration is the sum of all individual parts. This means that individual parts can be larger than the next-bigger unit. For example, minutes can be greater than 59.

assert(fastestMarathon.inMinutes == 123);
All individual parts are allowed to be negative.

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 down. For example,

Duration aLongWeekend = new Duration(hours:88);
assert(aLongWeekend.inDays == 3);
This class provides a collection of arithmetic and comparison operators, plus a set of constants useful for converting time units.

See DateTime to represent a point in time. See Stopwatch to measure time-spans.

Static Fields

static const int HOURS_PER_DAY = 24
static const int MICROSECONDS_PER_DAY = 86400000000
static const int MICROSECONDS_PER_HOUR = 3600000000
static const int MICROSECONDS_PER_MILLISECOND = 1000
static const int MICROSECONDS_PER_MINUTE = 60000000
static const int MICROSECONDS_PER_SECOND = 1000000
static const int MILLISECONDS_PER_DAY = 86400000
static const int MILLISECONDS_PER_HOUR = 3600000
static const int MILLISECONDS_PER_MINUTE = 60000
static const int MILLISECONDS_PER_SECOND = 1000
static const int MINUTES_PER_DAY = 1440
static const int MINUTES_PER_HOUR = 60
static const int SECONDS_PER_DAY = 86400
static const int SECONDS_PER_HOUR = 3600
static const int SECONDS_PER_MINUTE = 60
static const Duration ZERO

Fields

final int hashCode
final int inDays
final int inHours
final int inMicroseconds
final int inMilliseconds
final int inMinutes
final int inSeconds

Getters and Setters

int get hashCode
int get inDays

Returns the number of whole days spanned by this Duration.

int get inHours

Returns the number of whole hours spanned by this Duration.

The returned value can be greater than 23.

int get inMicroseconds

Returns number of whole microseconds spanned by this Duration.

int get inMilliseconds

Returns number of whole milliseconds spanned by this Duration.

The returned value can be greater than 999.

int get inMinutes

Returns the number of whole minutes spanned by this Duration.

The returned value can be greater than 59.

int get inSeconds

Returns the number of whole seconds spanned by this Duration.

The returned value can be greater than 59.

Constructors

Duration(int days, int hours, int minutes, int seconds, int milliseconds, int microseconds)

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

Individual parts can be larger than the next-bigger unit. For example, hours can be greater than 23.

All individual parts are allowed to be negative. All arguments are 0 by default.

Methods

Duration *(num factor)

Multiplies this Duration by the given factor and returns the result as a new Duration object.

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

Duration +(Duration other)

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

Duration -(Duration other)

Subtracts other from this Duration and returns the difference as a new Duration object.

bool <(Duration other)

Returns true if the value of this Duration is less than the value of other.

bool <=(Duration other)

Returns true if the value of this Duration is less than or equal to the value of other.

bool ==(dynamic other)

Returns true if this Duration is the same object as other.

bool >(Duration other)

Returns true if the value of this Duration is greater than the value of other.

bool >=(Duration other)

Returns true if the value of this Duration is greater than or equal to the value of other.

int compareTo(Duration other)

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

This function returns a negative integer if this Duration is smaller than other, or a positive integer if it is greater.

String toString()

Returns a string representation of this object.

Duration ~/(int quotient)

Divides this Duration by the given quotient and returns the truncated result as a new Duration object.

Throws an IntegerDivisionByZeroException if quotient is 0.


Class Error

Fields
stackTrace: StackTrace
Getters and Setters
stackTrace: StackTrace
Constructors
Error()
Methods
safeToString(Object object): String

Fields

final StackTrace stackTrace

Getters and Setters

StackTrace get stackTrace

Constructors

Error()

Methods

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.


Abstract class Exception

Constructors
Exception(dynamic message)

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 new Exception("message") is discouraged, and only included as a temporary measure during development, until the actual exceptions used by a library are done.

Constructors

factory Exception(dynamic message)

Class Expando

Fields
name: String
Constructors
Expando(String name)
Methods
[](Object object): T
[]=(Object object, T value): void
toString(): String

An Expando allows adding new properties to objects.

Fields

final String name

The name of the this Expando as passed to the constructor. If no name was passed to the constructor, the name is null.

Constructors

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.

Methods

T [](Object object)

Gets the value of this Expando's property on the given object. If the object hasn't been expanded, the method returns null.

void []=(Object object, T value)

Sets the value of this Expando's property on the given object. Properties can effectively be removed again by setting their value to null.

String toString()

Expando toString method override.


Class FallThroughError extends Error

Constructors
FallThroughError()

Error thrown when control reaches the end of a switch case.

The Dart specification requires this error to be thrown when control reaches the end of a switch case (except the last case of a switch) without meeting a break or similar end of the control flow.

Constructors

FallThroughError()

Class FormatException implements Exception

Fields
message: String
Constructors
FormatException(String message)
Methods
toString(): String

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

Fields

final String message

A message describing the format error.

Constructors

FormatException(String message)

Creates a new FormatException with an optional error message.

Methods

String toString()

Returns a string representation of this object.


Abstract class Function

Constructors
Function()
Methods
apply(Function function, List<dynamic> positionalArguments, Map<Symbol, dynamic> namedArguments): dynamic

The base class for all function types.

A function value, or an instance of a class with a "call" method, is a subtype of a function type, and as such, a subtype of Function.

Constructors

Function()

Methods

static dynamic apply(Function function, List<dynamic> positionalArguments, Map<Symbol, dynamic> namedArguments)

Dynamically call function with the specified arguments.

Acts the same as 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 isn't callable or if it expects different parameters.

Example: [: Map<Symbol, dynamic> namedArguments = new Map<Symbol, dynamic>(); namedArgumentsconst Symbol("f") = 4; namedArgumentsconst Symbol("g") = 5; Function.apply(foo, 1,2,3, namedArguments); :] gives exactly the same result as foo(1, 2, 3, f: 4, g: 5) .

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


Class IntegerDivisionByZeroException implements Exception

Constructors
IntegerDivisionByZeroException()
Methods
toString(): String

Constructors

IntegerDivisionByZeroException()

Methods

String toString()

Returns a string representation of this object.


Abstract class Invocation

Fields
isAccessor: bool
isGetter: bool
isMethod: bool
isSetter: bool
memberName: Symbol
namedArguments: Map
positionalArguments: List
Getters and Setters
isAccessor: bool
isGetter: bool
isMethod: bool
isSetter: bool
memberName: Symbol
namedArguments: Map<Symbol, dynamic>
positionalArguments: List<dynamic>
Constructors
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.

Fields

final bool isAccessor
final bool isGetter
final bool isMethod
final bool isSetter
final Symbol memberName
final Map namedArguments
final List positionalArguments

Getters and Setters

bool get isAccessor

Whether the invocation was a getter or a setter call.

bool get isGetter

Whether the invocation was a getter call. If so, both types of arguments is empty.

bool get isMethod

Whether the invocation was a method call.

bool get isSetter

Whether the invocation was a setter call.

If so, arguments has exactly one positonal argument, and namedArguments is empty.

Symbol get memberName

The name of the invoked member.

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

List<dynamic> get positionalArguments

An unmodifiable view of the positional arguments of the call.

If the member is a getter, the positional arguments is empty.

Constructors

Invocation()

Abstract class Iterable

Fields
first: E
isEmpty: bool
isNotEmpty: bool
iterator: Iterator
last: E
length: int
single: E
Getters and Setters
first: E
isEmpty: bool
isNotEmpty: bool
iterator: Iterator<E>
last: E
length: int
single: E
Constructors
Iterable()
Iterable.generate(int count, <E> generator)
Methods
any(<E> test): bool
contains(Object element): bool
elementAt(int index): E
every(<E> test): bool
expand(<E> f): Iterable<dynamic>
firstWhere(<E> test, <E> orElse): E
fold(dynamic initialValue, <E> combine): dynamic
forEach(<E> f): void
join(String separator): String
lastWhere(<E> test, <E> orElse): E
map(<E> f): Iterable<dynamic>
reduce(<E> combine): E
singleWhere(<E> test): E
skip(int n): Iterable<E>
skipWhile(<E> test): Iterable<E>
take(int n): Iterable<E>
takeWhile(<E> test): Iterable<E>
toList(bool growable): List<E>
toSet(): Set<E>
where(<E> test): Iterable<E>

An object that uses an Iterator to serve objects one at a time.

You can iterate over all objects served by an Iterable object using the for-in loop construct. For example, you can iterate over all of the keys in a Map, because Map keys are iterable.

Map 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 class and the Set class implement this interface, as do classes in the dart:collection(#dart-collection) library.

You can implement Iterable in your own class. If you do, then an instance of your Iterable class can be the right-hand side of a for-in construct.

Fields

final E first
final bool isEmpty
final bool isNotEmpty
final Iterator iterator
final E last
final int length
final E single

Getters and Setters

E get first

Returns the first element.

If this is empty throws a StateError. Otherwise this method is equivalent to this.elementAt(0)

bool get isEmpty

Returns true if there is no element in this collection.

bool get isNotEmpty

Returns true if there is at least one element in this collection.

Iterator<E> get iterator

Returns an Iterator that iterates over this Iterable object.

E get last

Returns the last element.

If this is empty throws a StateError.

int get length

Returns the number of elements in this.

Counting all elements may be involve running through all elements and can therefore be slow.

E get single

Returns the single element in this.

If this is empty or has more than one element throws a StateError.

Constructors

Iterable()
factory Iterable.generate(int count, <E> generator)

Creates an Iterable that generates its elements dynamically.

The Iterators created by the Iterable count from zero to count - 1 while iterating, and call generator with that index to create the next value.

As an Iterable, new Iterable.generate(n, generator)) is equivalent to const 0, ..., n - 1.map(generator)

Methods

bool any(<E> test)

Returns true if one element of this collection satisfies the predicate test. Returns false otherwise.

bool contains(Object element)

Returns true if the collection contains an element equal to element.

E elementAt(int index)

Returns the indexth element.

If this has fewer than index elements throws a RangeError.

Note: if this does not have a deterministic iteration order then the function may simply return any element without any iteration if there are at least index elements in this.

bool every(<E> test)

Returns true if every elements of this collection satisify the predicate test. Returns false otherwise.

Iterable<dynamic> expand(<E> f)

Expands each element of this Iterable into zero or more elements.

The resulting Iterable runs through the elements returned by f for each element of this, in order.

The returned Iterable is lazy, and calls f for each element of this every time it's iterated.

E firstWhere(<E> test, <E> orElse)

Returns the first element that satisfies the given predicate test.

If none matches, the result of invoking the orElse function is returned. By default, when orElse is null, a StateError is thrown.

dynamic fold(dynamic initialValue, <E> combine)

Reduces a collection to a single value by iteratively combining each element of the collection with an existing value using the provided function.

Use initialValue as the initial value, and the function combine to create a new value from the previous one and an element.

Example of calculating the sum of an iterable:

iterable.fold(0, (prev, element) => prev + element);

void forEach(<E> f)

Applies the function f to each element of this collection.

String join(String separator)

Converts each element to a String and concatenates the strings.

Converts each element to a String by calling Object.toString on it. Then concatenates the strings, optionally separated by the separator string.

E lastWhere(<E> test, <E> orElse)

Returns the last element that satisfies the given predicate test.

If none matches, the result of invoking the orElse function is returned. By default, when orElse is null, a StateError is thrown.

Iterable<dynamic> map(<E> f)

Returns a lazy Iterable where each element e of this is replaced by the result of f(e).

This method returns a view of the mapped elements. As long as the returned Iterable is not iterated over, the supplied function f will not be invoked. The transformed elements will not be cached. Iterating multiple times over the the returned Iterable will invoke the supplied function f multiple times on the same element.

E reduce(<E> combine)

Reduces a collection to a single value by iteratively combining elements of the collection using the provided function.

Example of calculating the sum of an iterable:

iterable.reduce((value, element) => value + element);

E singleWhere(<E> test)

Returns the single element that satisfies test. If no or more than one element match then a StateError is thrown.

Iterable<E> skip(int n)

Returns an Iterable that skips the first n elements.

If this has fewer than n elements, then the resulting Iterable is empty.

It is an error if n is negative.

Iterable<E> skipWhile(<E> test)

Returns an Iterable that skips elements while test is satisfied.

The filtering happens lazily. Every new Iterator of the returned Iterable iterates over all elements of this.

As long as the iterator's elements satisfy test they are discarded. Once an element does not satisfy the test the iterator stops testing and uses every later element unconditionally. That is, the elements of the returned Iterable are the elements of this starting from the first element that does not satisfy test.

Iterable<E> take(int n)

Returns an Iterable with at most n elements.

The returned Iterable may contain fewer than n elements, if this contains fewer than n elements.

It is an error if n is negative.

Iterable<E> takeWhile(<E> test)

Returns an Iterable that stops once test is not satisfied anymore.

The filtering happens lazily. Every new Iterator of the returned Iterable starts iterating over the elements of this.

When the iterator encounters an element e that does not satisfy test, it discards e and moves into the finished state. That is, it does not get or provide any more elements.

List<E> toList(bool growable)

Creates a List containing the elements of this Iterable.

The elements are in iteration order. The list is fixed-length if growable is false.

Set<E> toSet()

Creates a Set containing the elements of this Iterable.

Iterable<E> where(<E> test)

Returns a lazy Iterable with all elements that satisfy the predicate test.

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 will invoke the supplied function test multiple times on the same element.


Abstract class Iterator

Fields
current: E
Getters and Setters
current: E
Constructors
Iterator()
Methods
moveNext(): bool

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 (moveNext()) to point to the first element. If no element is left, then moveNext() returns false.

A typical usage of an Iterator looks as follows:

var it = obj.iterator;
while (it.moveNext()) {
  use(it.current);
}
See also: Iteration (http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-iteration) in the library tour (http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html)

Fields

final E current

Getters and Setters

E get current

Returns the current element.

Return null if the iterator has not yet been moved to the first element, or if the iterator has been moved after the last element of the Iterable.

Constructors

Iterator()

Methods

bool moveNext()

Moves to the next element. Returns true if current contains the next element. Returns false, if no element was left.

It is safe to invoke moveNext even when the iterator is already positioned after the last element. In this case moveNext has no effect.


Abstract class List implements Iterable<E>

Fields
length: int
reversed: Iterable
Getters and Setters
length: int
length=(int newLength)
reversed: Iterable<E>
Constructors
List(int length)
List.filled(int length, E fill)
List.from(Iterable<dynamic> other, bool growable)
List.generate(int length, <E> generator, bool growable)
Methods
[](int index): E
[]=(int index, E value): void
add(E value): void
addAll(Iterable<E> iterable): void
asMap(): Map<int, E>
clear(): void
fillRange(int start, int end, E fillValue): void
getRange(int start, int end): Iterable<E>
indexOf(E element, int start): int
insert(int index, E element): void
insertAll(int index, Iterable<E> iterable): void
lastIndexOf(E element, int start): int
remove(Object value): bool
removeAt(int index): E
removeLast(): E
removeRange(int start, int end): void
removeWhere(<E> test): void
replaceRange(int start, int end, Iterable<E> iterable): void
retainWhere(<E> test): void
setAll(int index, Iterable<E> iterable): void
setRange(int start, int end, Iterable<E> iterable, int skipCount): void
sort(<E> compare): void
sublist(int start, int end): List<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 following code illustrates that some List implementations support only a subset of the API.

var fixedLengthList = new List(5);
fixedLengthList.length = 0;  // Error.
fixedLengthList.add(499);    // Error.
fixedLengthList[0] = 87;

var growableList = [1, 2];
growableList.length = 0;
growableList.add(499);
growableList[0] = 87;
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 does not detect it.

Fields

int length
final Iterable reversed

Getters and Setters

int get length

Returns the number of objects in this list.

The valid indices for a list are 0 through length - 1.

set length=(int newLength)

Changes the length of this list.

If newLength is greater than the current length, entries are initialized to null.

Throws an UnsupportedError if the list is fixed-length.

Iterable<E> get reversed

Returns an Iterable of the objects in this list in reverse order.

Constructors

factory List(int length)

Creates a list of the given _length_.

The created list is fixed-length if _length_ is provided. The list has length 0 and is growable if _length_ is omitted.

An error occurs if _length_ is negative.

factory List.filled(int length, E fill)

Creates a fixed-length list of the given _length_ and initializes the value at each position with fill.

factory List.from(Iterable<dynamic> other, bool growable)

Creates a list and initializes it using the contents of other.

The Iterator of other provides the order of the objects.

This constructor returns a growable list if growable is true; otherwise, it returns a fixed-length list.

factory List.generate(int length, <E> generator, bool growable)

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.

The created list is fixed-length unless growable is true.

Methods

E [](int index)

Returns the object at the given index in the list or throws a RangeError if index is out of bounds.

void []=(int index, E value)

Sets the value at the given index in the list to value or throws a RangeError if index is out of bounds.

void add(E value)

Adds value to the end of this list, extending the length by one.

Throws an UnsupportedError if the list is fixed-length.

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. Throws an UnsupportedError if this list is fixed-length.

Map<int, E> asMap()

Returns an unmodifiable Map view of this.

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.

void clear()

Removes all objects from this list; the length of the list becomes zero.

Throws an UnsupportedError, and retains all objects, if this is a fixed-length list.

void fillRange(int start, int end, E fillValue)

Sets the objects in the range start inclusive to end exclusive to the given fillValue.

An error occurs if start..end is not a valid range for this.

Iterable<E> getRange(int start, int end)

Returns an Iterable that iterates over the objects in the range start inclusive to end exclusive.

An error occurs if end is before start.

An error occurs if the start and end are not valid ranges at the time of the call to this method. The returned Iterable behaves like skip(start).take(end - start). That is, it does not throw exceptions if this changes size.

Example:

var list = [1, 2, 3, 4, 5];
var range = list.getRange(1, 4);
print(range.join(', '));  // => 2, 3, 4
list.length = 3;
print(range.join(', '));  // => 2, 3

int indexOf(E element, int start)

Returns the first index of element in this list.

Searches the list from index start to the length of the list. The first time an object o is encountered so that o == element, the index of o is returned. Returns -1 if element is not found.

void insert(int index, E element)

Inserts the object 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.

An error occurs if the index is less than 0 or greater than length. An UnsupportedError occurs if the list is fixed-length.

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.

An error occurs if the index is less than 0 or greater than length. An UnsupportedError occurs if the list is fixed-length.

int lastIndexOf(E element, int start)

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

If start is not provided, it defaults to this.length - 1.

Returns -1 if element is not found.

bool remove(Object value)

Removes the first occurence of value from this list.

Returns true if value was in the list. Returns false otherwise.

The method has no effect if value was not in the list.

An UnsupportedError occurs if the list is fixed-length.

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

  • Throws an ArgumentError if index is not an int.
  • Throws a RangeError if the index is out of range for this list.
  • Throws an UnsupportedError, and doesn't remove the object,
if this is a fixed-length list.

E removeLast()

Pops and returns the last object in this list.

Throws an UnsupportedError if this is a fixed-length list.

void removeRange(int start, int end)

Removes the objects in the range start inclusive to end exclusive.

An error occurs if start..end is not a valid range for this. Throws an UnsupportedError if this is a fixed-length list.

void removeWhere(<E> test)

Removes all objects from this list that satisfy test.

An object o satisfies test if test(o) is true.

Throws an UnsupportedError if this is a fixed-length list.

void replaceRange(int start, int end, Iterable<E> iterable)

Removes the objects in the range start inclusive to end exclusive and replaces them with the contents of the iterable.

An error occurs if start..end is not a valid range for this.

Example:

var list = [1, 2, 3, 4, 5];
list.replaceRange(1, 3, [6, 7, 8, 9]);
print(list);  // [1, 6, 7, 8, 9, 4, 5]

void retainWhere(<E> test)

Removes all objects from this list that fail to satisfy test.

An object o satisfies test if test(o) is true.

Throws an UnsupportedError if this is a fixed-length list.

void setAll(int index, Iterable<E> iterable)

Overwrites objects of this with the objects of iterable, starting at position index in this list.

This operation does not increase the length of this.

An error occurs if the index is less than 0 or greater than length. An error occurs if the iterable is longer than length - index.

void setRange(int start, int end, Iterable<E> iterable, int skipCount)

Copies the objects of iterable, skipping skipCount objects first, into the range start inclusive to end exclusive of this.

If start equals end and start..end represents a legal range, this method has no effect.

An error occurs if start..end is not a valid range for this. An error occurs if the iterable does not have enough objects after skipping skipCount objects.

Example:

var list = [1, 2, 3, 4];
var list2 = [5, 6, 7, 8, 9];
list.setRange(1, 3, list2, 3);
print(list);  // => [1, 8, 9, 4]

void sort(<E> compare)

Sorts this list according to the order specified by the compare function.

The compare function must act as a Comparator.

The default List implementations use Comparable.compare if compare is omitted.

List<E> sublist(int start, int end)

Returns a new list containing the objects from start inclusive to end exclusive.

If end is omitted, the length of this is used.

An error occurs if start is outside the range 0 .. length or if end is outside the range start .. length.


Abstract class Map

Fields
isEmpty: bool
isNotEmpty: bool
keys: Iterable
length: int
values: Iterable
Getters and Setters
isEmpty: bool
isNotEmpty: bool
keys: Iterable<K>
length: int
values: Iterable<V>
Constructors
Map()
Map.from(Map<K, V> other)
Map.fromIterable(Iterable<dynamic> iterable, <K, V> key, <K, V> value)
Map.fromIterables(Iterable<K> keys, Iterable<V> values)
Methods
[](Object key): V
[]=(K key, V value): void
addAll(Map<K, V> other): void
clear(): void
containsKey(Object key): bool
containsValue(Object value): bool
forEach(<K, V> f): void
putIfAbsent(K key, <K, V> ifAbsent): V
remove(Object key): V

An unordered collection of key-value pairs, from which you retrieve a value by using its associated key.

Each key can occur at most once in a map.

Fields

final bool isEmpty
final bool isNotEmpty
final Iterable keys
final int length
final Iterable values

Getters and Setters

bool get isEmpty

Returns true if there is no {key, value} pair in the map.

bool get isNotEmpty

Returns true if there is at least one {key, value} pair in the map.

Iterable<K> get keys

The keys of this.

int get length

The number of {key, value} pairs in the map.

Iterable<V> get values

The values of this.

Constructors

factory Map()

Creates a Map instance with the default implementation.

factory Map.from(Map<K, V> other)

Creates a Map instance that contains all key-value pairs of other.

factory Map.fromIterable(Iterable<dynamic> iterable, <K, V> key, <K, V> value)

Creates a Map instance where the keys and values are computed from the iterable.

For each element of the iterable this constructor computes a key-value pair, by applying key and value respectively.

The keys computed by the source iterable do not need to be unique. The last occurrence of a key will simply overwrite any previous value.

If no values are specified for key and value the default is the identity function.

factory Map.fromIterables(Iterable<K> keys, Iterable<V> values)

Creates a Map instance associating the given keys to values.

This constructor iterates over keys and values and maps each element of keys to the corresponding element of values.

If keys contains the same object multiple times, the last occurrence overwrites the previous value.

It is an error if the two Iterables don't have the same length.

Methods

V [](Object key)

Returns the value for the given key or null if key is not in the map. Because null values are supported, one should either use containsKey to distinguish between an absent key and a null value, or use the putIfAbsent method.

void []=(K key, V value)

Associates the key with the given value.

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 thiskey = value for each key and associated value in other. It iterates over other, which must therefore not change during the iteration.

void clear()

Removes all pairs from the map.

bool containsKey(Object key)

Returns true if this map contains the given key.

bool containsValue(Object value)

Returns true if this map contains the given value.

void forEach(<K, V> f)

Applies f to each {key, value} pair of the map.

It is an error to add or remove keys from the map during iteration.

V putIfAbsent(K key, <K, V> ifAbsent)

If key is not associated to a value, calls ifAbsent and updates the map by mapping key to the value returned by ifAbsent. Returns the value in the map.

It is an error to add or remove keys from the map during the call to ifAbsent.

V remove(Object key)

Removes the association for the given key. Returns the value for key in the map or null if key is not in the map. Note that values can be null and a returned null value does not always imply that the key is absent.


Abstract class Match

Fields
end: int
groupCount: int
input: String
pattern: Pattern
start: int
str: String
Getters and Setters
end: int
groupCount: int
input: String
pattern: Pattern
start: int
str: String
Constructors
Match()
Methods
[](int group): String
group(int group): String
groups(List<int> groupIndices): List<String>

A result from searching within a string.

A Match or an Iterable of Match objects is returned from Pattern matching methods.

The following example finds all matches of a RegExp in a String and iterates through the returned iterable of Match objects.

RegExp exp = new RegExp(r"(\w+)");
String str = "Parse my string";
Iterable<Match> matches = exp.allMatches(str);
for (Match m in matches) {
  String match = m.group(0);
  print(match);
}
The output of the example is:

Parse
my
string
Some patterns, regular expressions in particular, may record subtrings 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.

Fields

final int end
final int groupCount
final String input
final Pattern pattern
final int start
final String str

Getters and Setters

int get end

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

String get input

The string on which this match was computed.

Pattern get pattern

The pattern used to search in input.

int get start

Returns the index in the string where the match starts.

@deprecated
String get str

Deprecated alias for input.

Will be removed soon.

Constructors

Match()

Methods

String [](int group)

Returns the string matched by the given group.

If group is 0, returns the match of the pattern.

Short alias for Match.group.

String group(int group)

Returns the string matched by the given group.

If group is 0, returns the match of the pattern.

The result may be null if the pattern didn't assign a value to it as part of this match.

List<String> groups(List<int> groupIndices)

Returns a list of the groups with the given indices.

The list contains the strings returned by group for each index in groupIndices.


Class NoSuchMethodError extends Error

Constructors
NoSuchMethodError(Object receiver, Symbol memberName, List<dynamic> positionalArguments, Map<Symbol, dynamic> namedArguments, List<dynamic> existingArgumentNames)
Methods
toString(): String

Error thrown by the default implementation of noSuchMethod on Object.

Constructors

NoSuchMethodError(Object receiver, Symbol memberName, List<dynamic> positionalArguments, Map<Symbol, dynamic> namedArguments, List<dynamic> existingArgumentNames)

Create 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. If the receiver is null, it is interpreted as a call to a top-level function of a library.

The memberName is a Symbol representing the name of the called method or accessor. It should not be null.

The positionalArguments is a list of the positional arguments that the method was called with. If null, it is considered equivalent to the empty list.

The namedArguments is a map from Symbols to the values of named arguments that the method was called with.

The optional exisitingArgumentNames is the expected parameters of a method with the same name on the receiver, if available. This is the signature of the method that would have been called if the parameters had matched.

Methods

String toString()

Returns a string representation of this object.


Class Null

Methods
toString(): String

The reserved word null denotes an object that is the sole instance of this class.

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

Methods

String toString()

Returns the string "null".


Class NullThrownError extends Error

Constructors
NullThrownError()
Methods
toString(): String

Error thrown when attempting to throw null.

Constructors

NullThrownError()

Methods

String toString()

Returns a string representation of this object.


Class Object

Fields
hashCode: int
runtimeType: Type
Getters and Setters
hashCode: int
runtimeType: Type
Constructors
Object()
Methods
==(dynamic other): bool
noSuchMethod(Invocation invocation): dynamic
toString(): String

The base class for all Dart objects.

Because Object is the root of the Dart class hierarchy, every other Dart class is a subclass of Object.

When you define a class, you should override toString() to return a string describing an instance of that class. You might also need to define hashCode and ==(), as described in the Implementing map keys (http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-implementing-map-keys) section of the library tour (http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html).

Fields

final int hashCode
final Type runtimeType

Getters and Setters

int get hashCode

Get a hash code for this object.

All objects have hash codes. Hash codes are guaranteed to be the same for objects that are equal when compared using the equality operator ==. Other than that there are no guarantees about the hash codes. They will not be consistent between runs and there are no distribution guarantees.

If a subclass overrides hashCode it should override the equality operator as well to maintain consistency.

Type get runtimeType

A representation of the runtime type of the object.

Constructors

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.

Methods

bool ==(dynamic other)

The equality operator.

The default behavior for all Objects is to return true if and only if this 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
or return null.

  • 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 equality of two objects should not change over time, or at least only change if one of the objects was modified.

If a subclass overrides the equality operator it should override the hashCode method as well to maintain consistency.

dynamic noSuchMethod(Invocation invocation)

noSuchMethod is invoked when users invoke a non-existant method on an object. The name of the method and the arguments of the invocation are passed to noSuchMethod in an Invocation. If noSuchMethod returns a value, that value becomes the result of the original invocation.

The default behavior of noSuchMethod is to throw a noSuchMethodError.

String toString()

Returns a string representation of this object.


Class OutOfMemoryError implements Error

Fields
stackTrace: StackTrace
Getters and Setters
stackTrace: StackTrace
Constructors
OutOfMemoryError()
Methods
toString(): String

Fields

final StackTrace stackTrace

Getters and Setters

StackTrace get stackTrace

Constructors

OutOfMemoryError()

Methods

String toString()

Returns a string representation of this object.


Abstract class Pattern

Constructors
Pattern()
Methods
allMatches(String str): Iterable<Match>
matchAsPrefix(String string, int start): Match

An interface for basic searches within strings.

Constructors

Pattern()

Methods

Iterable<Match> allMatches(String str)

Match this pattern against the string repeatedly.

The iterable will contain all the non-overlapping matches of the pattern on the string, ordered by start index.

The matches are found by repeatedly finding the first match of the pattern on the string, starting from the end of the previous match, and initially starting from index zero.

If the pattern matches the empty string at some point, the next match is found by starting at the previous match's end plus one.

Match matchAsPrefix(String string, int start)

Match this pattern against the start of string.

If start is provided, it must be an integer in the range 0 .. string.length. In that case, this patten is tested against the string at the start position. That is, a match is returned if the pattern can match a part of the string starting from position start.


Class RangeError extends ArgumentError

Constructors
RangeError(dynamic message)
RangeError.range(num value, num start, num end)
RangeError.value(num value)
Methods
toString(): String

Error thrown because of an index outside of the valid range.

Constructors

RangeError(dynamic message)

Create a new RangeError with the given message.

Temporarily made const for backwards compatibilty.

RangeError.range(num value, num start, num end)

Create a new RangeError with a message for a value and a range.

RangeError.value(num value)

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

Methods

String toString()

Returns a string representation of this object.


Abstract class RegExp implements Pattern

Fields
isCaseSensitive: bool
isMultiLine: bool
pattern: String
Getters and Setters
isCaseSensitive: bool
isMultiLine: bool
pattern: String
Constructors
RegExp(String source, bool multiLine, bool caseSensitive)
Methods
allMatches(String input): Iterable<Match>
firstMatch(String input): Match
hasMatch(String input): bool
stringMatch(String input): String

A regular expression pattern.

Regular expressions are Patterns, and can as such be used to match strings or parts of strings.

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

firstMatch() is the main implementation method that applies a regular expression to a string and returns the first Match. All other methods in RegExp can build on it.

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 = new RegExp(r"(\w+)");
String str = "Parse my string";
Iterable<Match> matches = exp.allMatches(str);

Fields

final bool isCaseSensitive
final bool isMultiLine
final String pattern

Getters and Setters

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.

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 character match the beginning and end of the input.

String get pattern

The pattern of this regular expression.

Constructors

factory RegExp(String source, bool multiLine, bool caseSensitive)

Constructs a regular expression.

Throws a FormatException if source is not valid regular expression syntax.

Methods

Iterable<Match> allMatches(String input)

Returns an iterable of the matches of the regular expression on input.

Match firstMatch(String input)

Searches for the first match of the regular expression in the string input. Returns null if there is no match.

bool hasMatch(String input)

Returns whether the regular expression has a match in the string input.

String stringMatch(String input)

Returns the first substring match of this regular expression in input.


Class RuneIterator implements BidirectionalIterator<int>

Fields
current: int
currentAsString: String
currentSize: int
rawIndex: int
string: String
Getters and Setters
current: int
currentAsString: String
currentSize: int
rawIndex: int
rawIndex=(int rawIndex)
Constructors
RuneIterator(String string)
RuneIterator.at(String string, int index)
Methods
moveNext(): bool
movePrevious(): bool
reset(int rawIndex): void

Iterator for reading runes (integer Unicode code points) out of a Dart string.

Fields

final int current
final String currentAsString
final int currentSize
int rawIndex
final String string

String being iterated.

Getters and Setters

int get current

The rune (integer Unicode code point) starting at the current position in the string.

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 null if current is null.

int get currentSize

The number of code units comprising the current rune.

Returns zero if there is no current rune (current is null).

int get rawIndex

Returns the starting position of the current rune in the string.

Returns null if the current rune is null.

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 then string will set current to null.

Constructors

RuneIterator(String string)

Create an iterator positioned at the beginning of the string.

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 the current value.

It is an error if the index position is in the middle of a surrogate pair.

Methods

bool moveNext()

Moves to the next element. Returns true if current contains the next element. Returns false, if no element was left.

It is safe to invoke moveNext even when the iterator is already positioned after the last element. In this case moveNext has no effect.

bool movePrevious()

Move back to the previous element.

Returns true and updates current if successful. Returns false and sets current to null if there is no previous element.

void reset(int rawIndex)

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.

Setting a negative rawIndex, or one greater than string.length, is an error. So is setting it in the middle of a surrogate pair.


Class Runes extends IterableBase<int>

Fields
iterator: RuneIterator
last: int
string: String
Getters and Setters
iterator: RuneIterator
last: int
Constructors
Runes(String string)

The runes (integer Unicode code points) of a String.

Fields

final RuneIterator iterator
final int last
final String string

Getters and Setters

RuneIterator get iterator
int get last

Constructors

Runes(String string)

Abstract class Set extends IterableBase<E>

Constructors
Set()
Set.from(Iterable<E> other)
Methods
add(E value): void
addAll(Iterable<E> elements): void
clear(): void
contains(Object value): bool
containsAll(Iterable<Object> other): bool
difference(Set<E> other): Set<E>
intersection(Set<Object> other): Set<E>
remove(Object value): bool
removeAll(Iterable<Object> elements): void
removeWhere(<E> test): void
retainAll(Iterable<Object> elements): void
retainWhere(<E> test): void
union(Set<E> other): Set<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, HashSet, considers objects indistinguishable if they are equal with regard to Object.operator==.

Sets may be either ordered or unordered. HashSet is unordered and doesn't guarantee anything about the order that elements are accessed in by iteration. LinkedHashSet iterates in the insertion order of its elements.

Constructors

factory Set()

Creates an empty Set.

The created Set is a HashSet. As such, it considers elements that are equal (using ==) to be undistinguishable, and requires them to have a compatible Object.hashCode implementation.

factory Set.from(Iterable<E> other)

Creates a Set that contains all elements of other.

The created Set is a HashSet. As such, it considers elements that are equal (using ==) to be undistinguishable, and requires them to have a compatible Object.hashCode implementation.

Methods

void add(E value)

Adds value into the set.

The method has no effect if value is already in the set.

void addAll(Iterable<E> elements)

Adds all of elements to this Set.

Equivalent to adding each element in elements using add, but some collections may be able to optimize it.

void clear()

Removes all elements in the set.

bool contains(Object value)

Returns true if value is in the set.

bool containsAll(Iterable<Object> other)

Returns whether this Set contains all the elements of other.

Set<E> difference(Set<E> other)

Returns a new set with the 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.

Set<E> intersection(Set<Object> other)

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

bool remove(Object value)

Removes value from the set. Returns true if value was in the set. Returns false otherwise. The method has no effect if value value was not in the set.

void removeAll(Iterable<Object> elements)

Removes each element of elements from this set.

void removeWhere(<E> test)

Removes all elements of this set that satisfy test.

void retainAll(Iterable<Object> elements)

Removes all elements of this set that are not elements in elements.

void retainWhere(<E> test)

Removes all elements of this set that fail to satisfy test.

Set<E> union(Set<E> other)

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


Class StackOverflowError implements Error

Fields
stackTrace: StackTrace
Getters and Setters
stackTrace: StackTrace
Constructors
StackOverflowError()
Methods
toString(): String

Fields

final StackTrace stackTrace

Getters and Setters

StackTrace get stackTrace

Constructors

StackOverflowError()

Methods

String toString()

Returns a string representation of this object.


Abstract class StackTrace

Constructors
StackTrace()
Methods
toString(): String

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

StackTrace()

Methods

String toString()

Returns a String representation of the stack trace.

The string represents the full stack trace starting from the point where a throw ocurred to the top of the current call sequence.

The exact format of the string representation is not final.


Class StateError extends Error

Fields
message: String
Constructors
StateError(String message)
Methods
toString(): String

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

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

Fields

final String message

Constructors

StateError(String message)

Methods

String toString()

Returns a string representation of this object.


Class Stopwatch

Fields
elapsed: Duration
elapsedMicroseconds: int
elapsedMilliseconds: int
elapsedTicks: int
frequency: int
isRunning: bool
Getters and Setters
elapsed: Duration
elapsedMicroseconds: int
elapsedMilliseconds: int
elapsedTicks: int
frequency: int
isRunning: bool
Constructors
Stopwatch()
Methods
reset(): void
start(): void
stop(): void

A simple stopwatch interface to measure elapsed time.

Fields

final Duration elapsed
final int elapsedMicroseconds
final int elapsedMilliseconds
final int elapsedTicks
final int frequency
final bool isRunning

Getters and Setters

Duration get elapsed

Returns the elapsedTicks counter converted to a Duration.

int get elapsedMicroseconds

Returns the elapsedTicks counter converted to microseconds.

int get elapsedMilliseconds

Returns the elapsedTicks counter converted to milliseconds.

int get elapsedTicks

Returns the elapsed number of clock ticks since calling start while the Stopwatch is running.

Returns the elapsed number of clock ticks between calling start and calling stop.

Returns 0 if the Stopwatch has never been started.

The elapsed number of clock ticks increases by frequency every second.

int get frequency

Returns the frequency of the elapsed counter in Hz.

bool get isRunning

Returns wether the StopWatch is currently running.

Constructors

Stopwatch()

Creates a Stopwatch in stopped state with a zero elapsed count.

The following example shows how to start a Stopwatch immediately after allocation.

Stopwatch stopwatch = new Stopwatch()..start();

Methods

void reset()

Resets the elapsed count to zero.

This method does not stop or start the Stopwatch.

void start()

Starts the Stopwatch.

The elapsed count is increasing 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.

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.


Abstract class String implements Comparable<String>, Pattern

Fields
codeUnits: List
isEmpty: bool
isNotEmpty: bool
length: int
runes: Runes
Getters and Setters
codeUnits: List<int>
isEmpty: bool
isNotEmpty: bool
length: int
runes: Runes
Constructors
String.fromCharCode(int charCode)
String.fromCharCodes(Iterable<int> charCodes)
Methods
+(String other): String
==(dynamic other): bool
[](int index): String
codeUnitAt(int index): int
contains(Pattern other, int startIndex): bool
endsWith(String other): bool
indexOf(Pattern pattern, int start): int
lastIndexOf(Pattern pattern, int start): int
replaceAll(Pattern from, String replace): String
replaceAllMapped(Pattern from, replace): String
replaceFirst(Pattern from, String to): String
split(Pattern pattern): List<String>
splitMapJoin(Pattern pattern, onMatch, onNonMatch): String
startsWith(Pattern pattern, int index): bool
substring(int startIndex, int endIndex): String
toLowerCase(): String
toUpperCase(): String
trim(): String

A class for working with a sequence of characters.

A string is represented by a sequence of Unicode UTF-16 code units accessible through the codeUnitAt() or the codeUnits members. Their string representation is accessible through the index-operator.

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 we use the name "rune" for an integer representing a Unicode code point. The runes of a string are accessible through the runes getter.

Strings are immutable.

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

For concatenating strings efficiently, use the StringBuffer class. For working with regular expressions, use the RegExp class.

Fields

final List codeUnits
final bool isEmpty
final bool isNotEmpty
final int length
final Runes runes

Getters and Setters

List<int> get codeUnits

Returns an unmodifiable list of the UTF-16 code units of this string.

bool get isEmpty

Returns whether this string is empty.

bool get isNotEmpty

Returns whether this string is not empty.

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 less, if the string contains characters outside the basic multilingual plane (plane 0).

Runes get runes

Returns an iterable of Unicode code-points of this string.

If the string contains surrogate pairs, they will be combined and returned as one integer by this iterator. Unmatched surrogate halves are treated like valid 16-bit code-units.

Constructors

factory String.fromCharCode(int charCode)

Allocates a new String for the specified charCode.

The new string contains a single code unit if the charCode can be represented by a single UTF-16 code unit. Otherwise the length is 2 and the code units form a surrogate pair.

It is allowed (though generally discouraged) to create a String with only one half of a surrogate pair.

factory String.fromCharCodes(Iterable<int> charCodes)

Allocates a new String for the specified charCodes.

The charCodes can be UTF-16 code units or runes. If a char-code value is 16-bit it is copied verbatim. If it is greater than 16 bits it is decomposed into a surrogate pair.

Methods

String +(String other)

Creates a new string by concatenating this string with other.

A sequence of strings can be concatenated by using Iterable.join:

var strings = ['foo', 'bar', 'geez'];
var concatenated = strings.join();

bool ==(dynamic other)

Returns whether the two strings are equal.

This method compares each individual code unit of the strings. Equivalently (for strings that are well-formed UTF-16) it compares each individual rune (code point). It does not check for Unicode equivalence. For example the two following strings both represent the string "Amélie" but, due to their different encoding will not return equal.

"Am\xe9lie"
"Ame\u{301}lie"
In the first string the "é" is encoded as a single unicode code unit (also a single rune), whereas the second string encodes it as "e" with the combining accent character "◌́".

String [](int index)

Gets 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. 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 the index-operator on this string yields a String with half of a surrogate pair:

var clef = "\u{1D11E}";
clef.length;  // => 2
clef.runes.first == 0x1D11E;  // => true
clef.runes.length;  // => 1
clef.codeUnitAt(0);  // => 0xD834
clef.codeUnitAt(1);  // => 0xDD1E
// The following strings are halves of a UTF-16 surrogate pair and
// thus invalid UTF-16 strings:
clef[0];  // => a string of length 1 with code-unit value 0xD834.
clef[1];  // => a string of length 1 with code-unit value 0xDD1E.
This method is equivalent to new String.fromCharCode(this.codeUnitAt(index)).

int codeUnitAt(int index)

Returns the 16-bit UTF-16 code unit at the given index.

bool contains(Pattern other, int startIndex)

Returns whether this string contains a match of other.

If startIndex is provided, only matches at or after that index are considered.

It is an error if startIndex is negative or greater than length.

bool endsWith(String other)

Returns whether this string ends with other.

int indexOf(Pattern pattern, int start)

Returns the first position of a match of pattern in this string, starting at start (inclusive).

Returns -1 if a match could not be found.

It is an error if start is negative or greater than length.

int lastIndexOf(Pattern pattern, int start)

Returns the last position of a match pattern in this string, searching backward starting at start (inclusive).

Returns -1 if other could not be found.

It is an error if start is negative or greater than length.

String replaceAll(Pattern from, String replace)

Replaces all substrings matching from with replace.

Returns a new string where the non-overlapping substrings that match from (the ones iterated by from.allMatches(thisString)) are replaced by the literal string replace.

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.

String replaceAllMapped(Pattern from, replace)

Replace all substrings matching from by a string computed from the match.

Returns a new string where 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.

Example (simplified pig latin):

pigLatin(String words) => words.replaceAllMapped(
    new RegExp(r"\b(\w*?)([aeiou]\w*)", caseSensitive: false),
    (Match m) => "${m[2]}${m[1]}${m[1].isEmpty ? 'way' : 'ay'}");
This would convert each word of a text to "pig-latin", so for example pigLatin("I have a secret now!") returns "Iway avehay away ecretsay ownay!"

String replaceFirst(Pattern from, String to)

Returns a new string where the first occurence of from in this string is replaced with to.

List<String> split(Pattern pattern)

Splits the string around matches of pattern. Returns a list of substrings.

Splitting with an empty string pattern ("") splits at UTF-16 code unit boundaries and not at rune boundaries. The following two expressions are hence equivalent:

string.split("")
string.codeUnits.map((unit) => new String.fromCharCode(unit))
Unless it guaranteed that the string is in the basic multilingual plane (meaning that each code unit represents a rune) it is often better to map the runes instead:

string.runes.map((rune) => new String.fromCharCode(rune))

String splitMapJoin(Pattern pattern, onMatch, onNonMatch)

Splits the string on the pattern, then converts each part and each match.

The pattern is used to split the string into parts and separating matches.

Each match is converted to a string by calling onMatch. If onMatch is omitted, the matched string is used.

Each non-matched part is converted by a call to onNonMatch. If onNonMatch is omitted, the non-matching part is used.

Then all the converted parts are combined into the resulting string.

bool startsWith(Pattern pattern, int index)

Returns whether this string starts with a match of pattern.

If index is provided, instead check if the substring starting at that index starts with a match of pattern.

It is an error if index is negative or greater than length.

A RegExp containing "^" will not match if the index is greater than zero. The pattern works on the string as a whole, and does not extract a substring starting at index first. That is.

"abc".startsWith(new RegExp("^.", 1)) == false

String substring(int startIndex, int endIndex)

Returns a substring of this string in the given range. startIndex is inclusive and endIndex is exclusive.

String toLowerCase()

If this string is not already all lower case, returns a new string where all characters are made lower case. Returns this otherwise.

String toUpperCase()

If this string is not already all upper case, returns a new string where all characters are made upper case. Returns this otherwise.

String trim()

Removes leading and trailing whitespace from a string.

If the string contains leading or trailing whitespace a new string with no leading and no trailing whitespace is returned. Otherwise, the string itself is returned.

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 (following version 6.2):

0009..000D    ; White_Space # Cc   <control-0009>..<control-000D>
0020          ; White_Space # Zs   SPACE
0085          ; White_Space # Cc   <control-0085>
00A0          ; White_Space # Zs   NO-BREAK SPACE
1680          ; White_Space # Zs   OGHAM SPACE MARK
180E          ; White_Space # Zs   MONGOLIAN VOWEL SEPARATOR
2000..200A    ; White_Space # Zs   EN QUAD..HAIR SPACE
2028          ; White_Space # Zl   LINE SEPARATOR
2029          ; White_Space # Zp   PARAGRAPH SEPARATOR
202F          ; White_Space # Zs   NARROW NO-BREAK SPACE
205F          ; White_Space # Zs   MEDIUM MATHEMATICAL SPACE
3000          ; White_Space # Zs   IDEOGRAPHIC SPACE

FEFF          ; BOM                ZERO WIDTH NO_BREAK SPACE


Class StringBuffer implements StringSink

Fields
isEmpty: bool
isNotEmpty: bool
length: int
Getters and Setters
isEmpty: bool
isNotEmpty: bool
length: int
Constructors
StringBuffer(Object content)
Methods
clear(): void
toString(): String
write(Object obj): void
writeAll(Iterable<dynamic> objects, String separator): void
writeCharCode(int charCode): void
writeln(Object obj): void

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.

Fields

final bool isEmpty
final bool isNotEmpty
final int length

Getters and Setters

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.

int get length

Returns the length of the content that has been accumulated so far. This is a constant-time operation.

Constructors

StringBuffer(Object content)

Creates the string buffer with an initial content.

Methods

void clear()

Clears the string buffer.

String toString()

Returns the contents of buffer as a concatenated string.

void write(Object obj)

Adds the contents of obj, converted to a string, to the buffer.

void writeAll(Iterable<dynamic> objects, String separator)

Iterates over the given objects and writes them in sequence.

void writeCharCode(int charCode)

Adds the string representation of charCode to the buffer.

void writeln(Object obj)

Converts obj to a String by invoking toString and adds the result to this. Then adds a new line.


Abstract class StringSink

Constructors
StringSink()
Methods
write(Object obj): void
writeAll(Iterable<dynamic> objects, String separator): void
writeCharCode(int charCode): void
writeln(Object obj): void

Constructors

StringSink()

Methods

void write(Object obj)

Converts obj to a String by invoking toString and adds the result to this.

void writeAll(Iterable<dynamic> objects, String separator)

Iterates over the given objects and writes them in sequence.

void writeCharCode(int charCode)

Writes the charCode to this.

This method is equivalent to write(new String.fromCharCode(charCode)).

void writeln(Object obj)

Converts obj to a String by invoking toString and adds the result to this. Then adds a new line.


Class Symbol

Constructors
Symbol(String name)

Opaque name used by mirrors, invocations and Function.apply.

Constructors

factory Symbol(String name)

Constructs a new Symbol.

An ArgumentError is thrown if name starts with an underscore, or if name is not a String. An ArgumentError is thrown if name is not an empty string and is not a valid qualified identifier optionally followed by '='.

The following text is non-normative:

Creating non-const Symbol instances may result in larger output. If possible, use MirrorsUsed in "dart:mirrors" to specify which names might be passed to this constructor.


Abstract class Type

Constructors
Type()

Runtime representation of a type.

Constructors

Type()

Class TypeError extends AssertionError

Constructors
TypeError()

Error thrown by the runtime system when a type assertion fails.

Constructors

TypeError()

Class UnimplementedError extends Error implements UnsupportedError

Fields
message: String
Constructors
UnimplementedError(String message)
Methods
toString(): String

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 a class is not intending to implement the feature, it should throw an UnsupportedError instead. This error is only intended for use during development.

Fields

final String message

Constructors

UnimplementedError(String message)

Methods

String toString()

Returns a string representation of this object.


Class UnsupportedError extends Error

Fields
message: String
Constructors
UnsupportedError(String message)
Methods
toString(): String

The operation was not allowed by the object.

This Error is thrown when an instance cannot implement one of the methods in its signature.

Fields

final String message

Constructors

UnsupportedError(String message)

Methods

String toString()

Returns a string representation of this object.


Class Uri

Fields
authority: String
fragment: String
hasAuthority: bool
hashCode: int
host: String
isAbsolute: bool
origin: String
path: String
pathSegments: List
port: int
query: String
queryParameters: Map
scheme: String
userInfo: String
Getters and Setters
authority: String
hasAuthority: bool
hashCode: int
host: String
isAbsolute: bool
origin: String
path: String
pathSegments: List<String>
port: int
queryParameters: Map<String, String>
Constructors
Uri(String scheme, String userInfo, String host, dynamic port, String path, Iterable<String> pathSegments, String query, Map<String, String> queryParameters, dynamic fragment)
Uri.file(String path, bool windows)
Uri.http(String authority, String unencodedPath, Map<String, String> queryParameters)
Uri.https(String authority, String unencodedPath, Map<String, String> queryParameters)
Methods
==(dynamic other): bool
decodeComponent(String encodedComponent): String
decodeFull(String uri): String
decodeQueryComponent(String encodedComponent, Encoding encoding): String
encodeComponent(String component): String
encodeFull(String uri): String
encodeQueryComponent(String component): String
parse(String uri): Uri
parseIPv4Address(String host): List<int>
parseIPv6Address(String host): List<int>
resolve(String reference): Uri
resolveUri(Uri reference): Uri
splitQueryString(String query, Encoding encoding): Map<String, String>
toFilePath(bool windows): String
toString(): String

A parsed URI, such as a URL.

See also:

  • URIsuris in the library tourlibtour
  • RFC-3986(http://tools.ietf.org/html/rfc3986)

uris: http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri libtour: http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html

Fields

final String authority
final String fragment

Returns the fragment identifier component.

Returns the empty string if there is no fragment identifier component.

final bool hasAuthority
final int hashCode
final String host
final bool isAbsolute
final String origin
final String path
final List pathSegments
final int port
final String query

Returns the query component. The returned query is encoded. To get direct access to the decoded query use queryParameters.

Returns the empty string if there is no query component.

final Map queryParameters
final String scheme

Returns the scheme component.

Returns the empty string if there is no scheme component.

final String userInfo

Returns the user info part of the authority component.

Returns the empty string if there is no user info in the authority component.

Getters and Setters

String get authority

Returns the authority component.

The authority is formatted from the userInfo, host and port parts.

Returns the empty string if there is no authority component.

bool get hasAuthority

Returns whether the URI has an authority component.

int get hashCode
String get host

Returns the host part of the authority component.

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

bool get isAbsolute

Returns whether the URI is absolute.

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

See: http://www.w3.org/TR/2011/WD-html5-20110405/origin-0.html#origin

String get path

Returns the path component.

The returned path is encoded. To get direct access to the decoded path use pathSegments.

Returns the empty string if there is no path component.

List<String> get pathSegments

Returns the URI path split into its segments. Each of the segments in the returned list have been decoded. If the path is empty the empty list will be returned. A leading slash / does not affect the segments returned.

The returned list is unmodifiable and will throw UnsupportedError on any calls that would mutate it.

int get port

Returns the port part of the authority component.

Returns 0 if there is no port in the authority component.

Map<String, String> get queryParameters

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 (http://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 there is no query the empty map is returned.

Keys in the query string that have no value are mapped to the empty string.

The returned map is unmodifiable and will throw UnsupportedError on any calls that would mutate it.

Constructors

Uri(String scheme, String userInfo, String host, dynamic port, String path, Iterable<String> pathSegments, String query, Map<String, String> queryParameters, dynamic fragment)

Creates a new URI from its components.

Each component is set through a named argument. Any number of components can be provided. The default value for the components not provided is the empry string, except for port which has a default value of 0. The path and query components can be set using two different named arguments.

The scheme component is set through scheme. The scheme is normalized to all lowercase letters.

The user info part of the authority component is set through userInfo.

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 port part of the authority component is set through port. The port is normalized for scheme http and https where port 80 and port 443 respectively is set.

The path component is set through either path or pathSegments. When path is used, the provided string is expected to be fully percent-encoded, and is used in its literal form. When pathSegments is used, each of the provided segments is percent-encoded and 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 calls for 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 is expected to be fully percent-encoded and is used in its literal form. 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. The percent-encoding of the keys and values encodes all characters except for the unreserved characters.

The fragment component is set through fragment.

factory Uri.file(String path, bool windows)

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.

With Windows semantics, backslash ("\") and forward-slash ("/") are used to separate path segments, except if the path starts with "\\?\" in which case, only backslash ("\") separates path segments.

If the path starts with a path separator an absolute URI is created. Otherwise a relative URI is created. One exception from 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 determined from the platform Dart 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 (resulting URI in comment):

new Uri.file("xxx/yyy");  // xxx/yyy
new Uri.file("xxx/yyy/");  // xxx/yyy/
new Uri.file("/xxx/yyy");  // file:///xxx/yyy
new Uri.file("/xxx/yyy/");  // file:///xxx/yyy/
new Uri.file("C:");  // C:
Examples using Windows semantics (resulting URI in comment):

new Uri.file(r"xxx\yyy");  // xxx/yyy
new Uri.file(r"xxx\yyy\");  // xxx/yyy/
new Uri.file(r"\xxx\yyy");  // file:///xxx/yyy
new Uri.file(r"\xxx\yyy/");  // file:///xxx/yyy/
new Uri.file(r"C:\xxx\yyy");  // file:///C:/xxx/yyy
new Uri.file(r"C:xxx\yyy");  // Throws as path with drive letter
                             // is not absolute.
new Uri.file(r"\\server\share\file");  // file://server/share/file
new Uri.file(r"C:");  // Throws as path with drive letter
                      // is not absolute.
If the path passed is not a legal file path ArgumentError is thrown.

factory Uri.http(String authority, String unencodedPath, Map<String, String> queryParameters)

Creates a new http URI from authority, path and query.

Examples:

// Create the URI http://example.org/path?q=abc.
new Uri.http("google.com", "/search", { "q" : "dart" });http://example.org/path?q=abc.
new Uri.http("user:pass@localhost:8080, "");  // http://user:pass@localhost:8080/
new Uri.http("example.org, "a b");  // http://example.org/a%20b
new Uri.http("example.org, "/a%2F");  // http://example.org/a%25%2F
The scheme is always set to http.

The userInfo, host and port components are set from the authority argument.

The path component is set from the unencodedPath argument. The path passed must not be encoded as this constructor encodes the path.

The query component is set from the optional queryParameters argument.

factory Uri.https(String authority, String unencodedPath, Map<String, String> queryParameters)

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.

Methods

bool ==(dynamic other)

The equality operator.

The default behavior for all Objects is to return true if and only if this 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
or return null.

  • 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 equality of two objects should not change over time, or at least only change if one of the objects was modified.

If a subclass overrides the equality operator it should override the hashCode method as well to maintain consistency.

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 with are delimiters for a given URI componene 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.

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.

static String decodeQueryComponent(String encodedComponent, Encoding encoding)

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.

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

static String encodeFull(String uri)

Encode 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 in ECMA-262 version 5.1 for the encodeURI function .

static String encodeQueryComponent(String component)

Encode the string component according to the HTML 4.01 rules for encoding the posting of a HTML form as a query string component.

Spaces will be replaced with plus and all characters except for uppercase and lowercase letters, decimal digits and the characters -._~. Note that the set of characters encoded is a superset of what HTML 4.01 says as 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 http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 for more details.

static Uri parse(String uri)

Creates a new URI object by parsing a URI string.

static List<int> parseIPv4Address(String host)

Parse the host as an IP version 4 (IPv4) address, returning the address as a list of 4 bytes in network byte order (big endian).

Throws a FormatException if host is not a valid IPv4 address representation.

static List<int> parseIPv6Address(String host)

Parse the host as an IP version 6 (IPv6) address, returning 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.

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

Uri resolveUri(Uri reference)

Resolve reference as an URI relative to this.

Returns the resolved URI.

The algorithm for resolving a reference is described in RFC-3986 Section 5 (http://tools.ietf.org/html/rfc3986#section-5 "RFC-1123").

static Map<String, String> splitQueryString(String query, Encoding encoding)

Returns the query split into a map according to the rules specified for FORM post in the HTML 4.01 specification section 17.13.4 (http://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.

String toFilePath(bool windows)

Returns the 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 determined from the platform Dart 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.

String toString()

Returns a string representation of this object.


Class bool

Methods
toString(): String

The reserved words true and false denote objects that are the only instances of this class.

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

Methods

String toString()

Returns "true" if the receiver is true, or "false" if the receiver is false.


Abstract class double extends num

Static Fields
INFINITY: double
MAX_FINITE: double
MIN_POSITIVE: double
NAN: double
NEGATIVE_INFINITY: double
Constructors
double()
Methods
%(num other): double
*(num other): double
+(num other): double
-(num other): double
/(num other): double
abs(): double
ceil(): int
ceilToDouble(): double
floor(): int
floorToDouble(): double
parse(String source, onError): double
remainder(num other): double
round(): int
roundToDouble(): double
toString(): String
truncate(): int
truncateToDouble(): double
unary-(): double
~/(num other): int

A double-precision floating point number.

Representation of Dart doubles containing double specific constants and operations and specializations of operations inherited from num. Dart 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.

Static Fields

static const double INFINITY = Infinity
static const double MAX_FINITE = 1.7976931348623157e+308
static const double MIN_POSITIVE = 5e-324
static const double NAN = NaN
static const double NEGATIVE_INFINITY = -Infinity

Constructors

double()

Methods

double %(num 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 < a.abs().

The euclidean division is only defined for integers, but can be easily extended to work with doubles. In that case r may have a non-integer value, but it still verifies 0 <= r < |a|.

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

double *(num other)

Multiplication operator.

double +(num other)

Addition operator.

double -(num other)

Subtraction operator.

double /(num other)

Division operator.

double abs()

Returns the absolute value of this double.

int ceil()

Returns the least integer no smaller than this.

If this is not finite (NaN or infinity), throws an UnsupportedError.

double ceilToDouble()

Returns the least integer value no smaller than this.

The result is a double.

int floor()

Returns the greatest integer no greater than this.

If this is not finite (NaN or infinity), throws an UnsupportedError.

double floorToDouble()

Returns the greatest integer value no greater than this.

The result is a double.

static double parse(String source, onError)

Parse source as an 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.

Leading and trailing whitespace is ignored.

If the source is not a valid double literal, the onError is called with the source as argument, and its return value is used instead. If no onError is provided, a FormatException is thrown instead.

The onError function is only invoked if source is a String with an invalid format. It is not invoked if the source is invalid for some other reason, for example by being null.

Examples of accepted strings:

"3.14"
"  3.14 \xA0"
"0."
".0"
"-1.e3"
"1234E+7"
"+.12e-9"
"-NaN"

double remainder(num other)

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

The result r of this operation satisfies: this == this ~/ other + r. As a consequence the remainder r has the same sign as the dividend this.

int round()

Returns the integer closest to this.

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

If this is not finite (NaN or infinity), throws an UnsupportedError.

double roundToDouble()

Returns the integer value, as a double, closest to this.

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

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.

It should always be the case that if d is a double, then d == double.parse(d.toString()).

int truncate()

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

If this is not finite (NaN or infinity), throws an UnsupportedError.

double truncateToDouble()

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

The result is a double.

double unary-()

Negate operator.

int ~/(num other)

Truncating division operator.

The result of the truncating division a ~/ b is equivalent to (a / b).truncate().


Abstract class int extends num

Fields
bitLength: int
isEven: bool
isOdd: bool
Getters and Setters
bitLength: int
isEven: bool
isOdd: bool
Constructors
int()
Methods
&(int other): int
<<(int shiftAmount): int
>>(int shiftAmount): int
^(int other): int
abs(): int
ceil(): int
ceilToDouble(): double
floor(): int
floorToDouble(): double
parse(String source, int radix, onError): int
round(): int
roundToDouble(): double
toRadixString(int radix): String
toSigned(int width): int
toString(): String
toUnsigned(int width): int
truncate(): int
truncateToDouble(): double
unary-(): int
|(int other): int
~(): int

An arbitrarily large integer.

Note: When compiling to JavaScript, integers are implemented as JavaScript numbers. When compiling to JavaScript, integers are therefore restricted to 53 significant bits because all JavaScript numbers are double-precision floating point values. The behavior of the operators and methods in the int class therefore sometimes differs between the Dart VM and Dart code compiled to JavaScript.

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

Fields

final int bitLength
final bool isEven
final bool isOdd

Getters and Setters

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

bool get isEven

Returns true if and only if this integer is even.

bool get isOdd

Returns true if and only if this integer is odd.

Constructors

int()

Methods

int &(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

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

int <<(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 of shiftAmount is negative.

int >>(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 of shiftAmount is negative.

int ^(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.

int abs()

Returns the absolute value of this integer.

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

int ceil()

Returns this.

double ceilToDouble()

Returns this.toDouble().

int floor()

Returns this.

double floorToDouble()

Returns this.toDouble().

static int parse(String source, int radix, onError)

Parse source as an integer literal and return its value.

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'. Accepts capital letters as well.

If no radix is given then it defaults to 16 if the string starts with "0x", "-0x" or "+0x" and 10 otherwise.

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

It must always be the case for an int n and radix r that n == parseRadix(n.toRadixString(r), r).

If the source is not a valid integer literal, optionally prefixed by a sign, the onError is called with the source as argument, and its return value is used instead. If no onError is provided, a FormatException is thrown.

The onError function is only invoked if source is a String. It is not invoked if the source is, for example, null.

int round()

Returns this.

double roundToDouble()

Returns this.toDouble().

String toRadixString(int radix)

Converts this to a string representation in the given radix.

In the string representation, lower-case letters are used for digits above '9'.

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

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);

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

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) == 32   // 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);

int truncate()

Returns this.

double truncateToDouble()

Returns this.toDouble().

int unary-()

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.

int |(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 us negative.

int ~()

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.


Abstract class num implements Comparable<num>

Fields
isInfinite: bool
isNaN: bool
isNegative: bool
Getters and Setters
isInfinite: bool
isNaN: bool
isNegative: bool
Constructors
num()
Methods
%(num other): num
*(num other): num
+(num other): num
-(num other): num
/(num other): double
<(num other): bool
<=(num other): bool
>(num other): bool
>=(num other): bool
abs(): num
ceil(): int
ceilToDouble(): double
clamp(num lowerLimit, num upperLimit): num
floor(): int
floorToDouble(): double
remainder(num other): num
round(): int
roundToDouble(): double
toDouble(): double
toInt(): int
toString(): String
toStringAsExponential(int fractionDigits): String
toStringAsFixed(int fractionDigits): String
toStringAsPrecision(int precision): String
truncate(): int
truncateToDouble(): double
unary-(): num
~/(num other): int

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.

Fields

final bool isInfinite
final bool isNaN
final bool isNegative

Getters and Setters

bool get isInfinite
bool get isNaN
bool get isNegative

Constructors

num()

Methods

num %(num 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 < a.abs().

The euclidean division is only defined for integers, but can be easily extended to work with doubles. In that case r may have a non-integer value, but it still verifies 0 <= r < |a|.

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

num *(num other)

Multiplication operator.

num +(num other)

Addition operator.

num -(num other)

Subtraction operator.

double /(num other)

Division operator.

bool <(num other)

Relational less than operator.

bool <=(num other)

Relational less than or equal operator.

bool >(num other)

Relational greater than operator.

bool >=(num other)

Relational greater than or equal operator.

num abs()

Returns the absolute value of this num.

int ceil()

Returns the least integer no smaller than this.

If this is not finite (NaN or infinity), throws an UnsupportedError.

double ceilToDouble()

Returns the least integer value no smaller than this.

The result is a double.

num clamp(num lowerLimit, num upperLimit)

Clamps this to be in the range lowerLimit-upperLimit. The comparison is done using compareTo and therefore takes -0.0 into account. It also implies that double.NAN is treated as the maximal double value.

int floor()

Returns the greatest integer no greater than this.

If this is not finite (NaN or infinity), throws an UnsupportedError.

double floorToDouble()

Returns the greatest integer value no greater than this.

The result is a double.

num remainder(num other)

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

The result r of this operation satisfies: this == this ~/ other + r. As a consequence the remainder r has the same sign as the dividend this.

int round()

Returns the integer closest to this.

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

If this is not finite (NaN or infinity), throws an UnsupportedError.

double roundToDouble()

Returns the integer value closest to this.

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

The result is a double.

double toDouble()

Return this num 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.

int toInt()

Truncates this num to an integer and returns the result as an int.

String toString()

Returns the shortest string that correctly represent the input 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.MINUS_INFINITY.

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

String toStringAsExponential(int fractionDigits)

Returns an exponential string-representation of this.

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

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

String toStringAsFixed(int fractionDigits)

Returns a decimal-point string-representation of this.

Converts this to a double before computing the string representation.

If the absolute value of this is greater 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
123456789012345678901.toStringAsFixed(3);  // 123456789012345683968.000
1000000000000000000000.toStringAsFixed(3); // 1e+21
5.25.toStringAsFixed(0); // 5

String toStringAsPrecision(int precision)

Converts this to a double and returns a string representation 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.00+15
1234567.toStringAsPrecision(3); // 1.23e+6
1234567.toStringAsPrecision(9); // 1234567.00
12345678901234567890.toStringAsPrecision(20); // 12345678901234567168
12345678901234567890.toStringAsPrecision(14); // 1.2345678901235e+19
0.00000012345.toPrecision(15); // 1.23450000000000e-7
0.0000012345.toPrecision(15);  // 0.00000123450000000000

int truncate()

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

If this is not finite (NaN or infinity), throws an UnsupportedError.

double truncateToDouble()

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

The result is a double.

num unary-()

Negate operator.

int ~/(num other)

Truncating division operator.

If either operand is a double then the result of the truncating division a ~/ b is equivalent to (a / b).truncate().toInt().

If both operands are ints then a ~/ b performs the truncating integer division.