ElementList<T extends Element>
LogoDart

ElementList<T extends Element> abstract#

abstract class ElementList<T extends Element> extends ListBase<T>

An immutable list containing HTML elements. This list contains some additional methods when compared to regular lists for ease of CSS manipulation on a group of elements.

Inheritance

Object → ListBase<E>ElementList<T extends Element>

Constructors#

ElementList()#

ElementList()

Properties#

borderEdge no setter#

CssRect get borderEdge

Access dimensions and position of the first Element's content + padding + border box in this list.

This returns a rectangle with the dimensions actually available for content in this element, in pixels, regardless of this element's box-sizing property. Unlike Element.getBoundingClientRect, the dimensions of this rectangle will return the same numerical height if the element is hidden or not. This can be used to retrieve jQuery's outerHeight value for an element.

Implementation
CssRect get borderEdge;

classes read / write#

CssClassSet get classes

getter:

The union of all CSS classes applied to the elements in this list.

This set makes it easy to add, remove or toggle (add if not present, remove if present) the classes applied to a collection of elements.

htmlList.classes.add('selected');
htmlList.classes.toggle('isOnline');
htmlList.classes.remove('selected');

setter:

Replace the classes with value for every element in this list.

Implementation
CssClassSet get classes;

set classes(Iterable<String> value);

contentEdge no setter#

CssRect get contentEdge

Access dimensions and position of the Elements in this list.

Setting the height or width properties will set the height or width property for all elements in the list. This returns a rectangle with the dimensions actually available for content in this element, in pixels, regardless of this element's box-sizing property. Getting the height or width returns the height or width of the first Element in this list.

Unlike Element.getBoundingClientRect, the dimensions of this rectangle will return the same numerical height if the element is hidden or not.

Implementation
CssRect get contentEdge;

first read / write inherited#

T get first

getter:

The first element.

Throws a StateError if this is empty. Otherwise returns the first element in the iteration order, equivalent to this.elementAt(0).

setter:

The first element of the list.

The list must be non-empty when accessing its first element.

The first element of a list can be modified, unlike an Iterable. A list.first is equivalent to list[0], both for getting and setting the value.

final numbers = <int>[1, 2, 3];
print(numbers.first); // 1
numbers.first = 10;
print(numbers.first); // 10
numbers.clear();
numbers.first; // Throws.

Inherited from ListBase.

Implementation
E get first {
  if (length == 0) throw IterableElementError.noElement();
  return this[0];
}

void set first(E value) {
  if (length == 0) throw IterableElementError.noElement();
  this[0] = value;
}

hashCode no setter inherited#

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

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

Inherited from Object.

Implementation
external int get hashCode;

isEmpty no setter inherited#

bool get isEmpty

Whether this collection has no elements.

May be computed by checking if iterator.moveNext() returns false.

Example:

final emptyList = <int>[];
print(emptyList.isEmpty); // true;
print(emptyList.iterator.moveNext()); // false

Inherited from ListBase.

Implementation
@pragma("vm:prefer-inline")
bool get isEmpty => length == 0;

isNotEmpty no setter inherited#

bool get isNotEmpty

Whether this collection has at least one element.

May be computed by checking if iterator.moveNext() returns true.

Example:

final numbers = <int>{1, 2, 3};
print(numbers.isNotEmpty); // true;
print(numbers.iterator.moveNext()); // true

Inherited from ListBase.

Implementation
bool get isNotEmpty => !isEmpty;

iterator no setter inherited#

Iterator<T> get iterator

A new Iterator that allows iterating the elements of this Iterable.

Iterable classes may specify the iteration order of their elements (for example List always iterate in index order), or they may leave it unspecified (for example a hash-based Set may iterate in any order).

Each time iterator is read, it returns a new iterator, which can be used to iterate through all the elements again. The iterators of the same iterable can be stepped through independently, but should return the same elements in the same order, as long as the underlying collection isn't changed.

Modifying the collection may cause new iterators to produce different elements, and may change the order of existing elements. A List specifies its iteration order precisely, so modifying the list changes the iteration order predictably. A hash-based Set may change its iteration order completely when adding a new element to the set.

Modifying the underlying collection after creating the new iterator may cause an error the next time Iterator.moveNext is called on that iterator. Any modifiable iterable class should specify which operations will break iteration.

Inherited from ListBase.

Implementation
@pragma('vm:prefer-inline')
Iterator<E> get iterator => ListIterator<E>(this);

last read / write inherited#

T get last

getter:

The last element.

Throws a StateError if this is empty. Otherwise may iterate through the elements and returns the last one seen. Some iterables may have more efficient ways to find the last element (for example a list can directly access the last element, without iterating through the previous ones).

setter:

The last element of the list.

The list must be non-empty when accessing its last element.

The last element of a list can be modified, unlike an Iterable. A list.last is equivalent to theList[theList.length - 1], both for getting and setting the value.

final numbers = <int>[1, 2, 3];
print(numbers.last); // 3
numbers.last = 10;
print(numbers.last); // 10
numbers.clear();
numbers.last; // Throws.

Inherited from ListBase.

Implementation
E get last {
  if (length == 0) throw IterableElementError.noElement();
  return this[length - 1];
}

void set last(E value) {
  if (length == 0) throw IterableElementError.noElement();
  this[length - 1] = value;
}

length read / write inherited#

int get length

getter:

The number of objects in this list.

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

final numbers = <int>[1, 2, 3];
print(numbers.length); // 3

setter:

Setting the length changes the number of elements in the list.

The list must be growable. If newLength is greater than current length, new entries are initialized to null, so newLength must not be greater than the current length if the element type E is non-nullable.

final maybeNumbers = <int?>[1, null, 3];
maybeNumbers.length = 5;
print(maybeNumbers); // [1, null, 3, null, null]
maybeNumbers.length = 2;
print(maybeNumbers); // [1, null]

final numbers = <int>[1, 2, 3];
numbers.length = 1;
print(numbers); // [1]
numbers.length = 5; // Throws, cannot add `null`s.

Inherited from List.

Implementation
int get length;

set length(int newLength);

marginEdge no setter#

CssRect get marginEdge

Access dimensions and position of the first Element's content + padding + border + margin box in this list.

This returns a rectangle with the dimensions actually available for content in this element, in pixels, regardless of this element's box-sizing property. Unlike Element.getBoundingClientRect, the dimensions of this rectangle will return the same numerical height if the element is hidden or not. This can be used to retrieve jQuery's outerHeight value for an element.

Implementation
CssRect get marginEdge;

onAbort no setter#

ElementStream<Event> get onAbort

Stream of abort events handled by this Element.

Implementation
ElementStream<Event> get onAbort;

onBeforeCopy no setter#

ElementStream<Event> get onBeforeCopy

Stream of beforecopy events handled by this Element.

Implementation
ElementStream<Event> get onBeforeCopy;

onBeforeCut no setter#

ElementStream<Event> get onBeforeCut

Stream of beforecut events handled by this Element.

Implementation
ElementStream<Event> get onBeforeCut;

onBeforePaste no setter#

ElementStream<Event> get onBeforePaste

Stream of beforepaste events handled by this Element.

Implementation
ElementStream<Event> get onBeforePaste;

onBlur no setter#

ElementStream<Event> get onBlur

Stream of blur events handled by this Element.

Implementation
ElementStream<Event> get onBlur;

onCanPlay no setter#

ElementStream<Event> get onCanPlay
Implementation
ElementStream<Event> get onCanPlay;

onCanPlayThrough no setter#

ElementStream<Event> get onCanPlayThrough
Implementation
ElementStream<Event> get onCanPlayThrough;

onChange no setter#

ElementStream<Event> get onChange

Stream of change events handled by this Element.

Implementation
ElementStream<Event> get onChange;

onClick no setter#

ElementStream<MouseEvent> get onClick

Stream of click events handled by this Element.

Implementation
ElementStream<MouseEvent> get onClick;

onContextMenu no setter#

ElementStream<MouseEvent> get onContextMenu

Stream of contextmenu events handled by this Element.

Implementation
ElementStream<MouseEvent> get onContextMenu;

onCopy no setter#

Stream of copy events handled by this Element.

Implementation
ElementStream<ClipboardEvent> get onCopy;

onCut no setter#

Stream of cut events handled by this Element.

Implementation
ElementStream<ClipboardEvent> get onCut;

onDoubleClick no setter#

ElementStream<Event> get onDoubleClick

Stream of doubleclick events handled by this Element.

Implementation
@DomName('Element.ondblclick')
ElementStream<Event> get onDoubleClick;

onDrag no setter#

A stream of drag events fired when this element currently being dragged.

A drag event is added to this stream as soon as the drag begins. A drag event is also added to this stream at intervals while the drag operation is still ongoing.

Other resources

Implementation
ElementStream<MouseEvent> get onDrag;

onDragEnd no setter#

ElementStream<MouseEvent> get onDragEnd

A stream of dragend events fired when this element completes a drag operation.

Other resources

Implementation
ElementStream<MouseEvent> get onDragEnd;

onDragEnter no setter#

ElementStream<MouseEvent> get onDragEnter

A stream of dragenter events fired when a dragged object is first dragged over this element.

Other resources

Implementation
ElementStream<MouseEvent> get onDragEnter;

onDragLeave no setter#

ElementStream<MouseEvent> get onDragLeave

A stream of dragleave events fired when an object being dragged over this element leaves this element's target area.

Other resources

Implementation
ElementStream<MouseEvent> get onDragLeave;

onDragOver no setter#

ElementStream<MouseEvent> get onDragOver

A stream of dragover events fired when a dragged object is currently being dragged over this element.

Other resources

Implementation
ElementStream<MouseEvent> get onDragOver;

onDragStart no setter#

ElementStream<MouseEvent> get onDragStart

A stream of dragstart events fired when this element starts being dragged.

Other resources

Implementation
ElementStream<MouseEvent> get onDragStart;

onDrop no setter#

A stream of drop events fired when a dragged object is dropped on this element.

Other resources

Implementation
ElementStream<MouseEvent> get onDrop;

onDurationChange no setter#

ElementStream<Event> get onDurationChange
Implementation
ElementStream<Event> get onDurationChange;

onEmptied no setter#

ElementStream<Event> get onEmptied
Implementation
ElementStream<Event> get onEmptied;

onEnded no setter#

ElementStream<Event> get onEnded
Implementation
ElementStream<Event> get onEnded;

onError no setter#

ElementStream<Event> get onError

Stream of error events handled by this Element.

Implementation
ElementStream<Event> get onError;

onFocus no setter#

ElementStream<Event> get onFocus

Stream of focus events handled by this Element.

Implementation
ElementStream<Event> get onFocus;

onFullscreenChange no setter#

ElementStream<Event> get onFullscreenChange

Stream of fullscreenchange events handled by this Element.

Implementation
ElementStream<Event> get onFullscreenChange;

onFullscreenError no setter#

ElementStream<Event> get onFullscreenError

Stream of fullscreenerror events handled by this Element.

Implementation
ElementStream<Event> get onFullscreenError;

onInput no setter#

ElementStream<Event> get onInput

Stream of input events handled by this Element.

Implementation
ElementStream<Event> get onInput;

onInvalid no setter#

ElementStream<Event> get onInvalid

Stream of invalid events handled by this Element.

Implementation
ElementStream<Event> get onInvalid;

onKeyDown no setter#

ElementStream<KeyboardEvent> get onKeyDown

Stream of keydown events handled by this Element.

Implementation
ElementStream<KeyboardEvent> get onKeyDown;

onKeyPress no setter#

ElementStream<KeyboardEvent> get onKeyPress

Stream of keypress events handled by this Element.

Implementation
ElementStream<KeyboardEvent> get onKeyPress;

onKeyUp no setter#

Stream of keyup events handled by this Element.

Implementation
ElementStream<KeyboardEvent> get onKeyUp;

onLoad no setter#

ElementStream<Event> get onLoad

Stream of load events handled by this Element.

Implementation
ElementStream<Event> get onLoad;

onLoadedData no setter#

ElementStream<Event> get onLoadedData
Implementation
ElementStream<Event> get onLoadedData;

onLoadedMetadata no setter#

ElementStream<Event> get onLoadedMetadata
Implementation
ElementStream<Event> get onLoadedMetadata;

onMouseDown no setter#

ElementStream<MouseEvent> get onMouseDown

Stream of mousedown events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseDown;

onMouseEnter no setter#

ElementStream<MouseEvent> get onMouseEnter

Stream of mouseenter events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseEnter;

onMouseLeave no setter#

ElementStream<MouseEvent> get onMouseLeave

Stream of mouseleave events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseLeave;

onMouseMove no setter#

ElementStream<MouseEvent> get onMouseMove

Stream of mousemove events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseMove;

onMouseOut no setter#

ElementStream<MouseEvent> get onMouseOut

Stream of mouseout events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseOut;

onMouseOver no setter#

ElementStream<MouseEvent> get onMouseOver

Stream of mouseover events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseOver;

onMouseUp no setter#

ElementStream<MouseEvent> get onMouseUp

Stream of mouseup events handled by this Element.

Implementation
ElementStream<MouseEvent> get onMouseUp;

onMouseWheel no setter#

ElementStream<WheelEvent> get onMouseWheel

Stream of mousewheel events handled by this Element.

Implementation
ElementStream<WheelEvent> get onMouseWheel;

onPaste no setter#

Stream of paste events handled by this Element.

Implementation
ElementStream<ClipboardEvent> get onPaste;

onPause no setter#

ElementStream<Event> get onPause
Implementation
ElementStream<Event> get onPause;

onPlay no setter#

ElementStream<Event> get onPlay
Implementation
ElementStream<Event> get onPlay;

onPlaying no setter#

ElementStream<Event> get onPlaying
Implementation
ElementStream<Event> get onPlaying;

onRateChange no setter#

ElementStream<Event> get onRateChange
Implementation
ElementStream<Event> get onRateChange;

onReset no setter#

ElementStream<Event> get onReset

Stream of reset events handled by this Element.

Implementation
ElementStream<Event> get onReset;

onResize no setter#

ElementStream<Event> get onResize
Implementation
ElementStream<Event> get onResize;

onScroll no setter#

ElementStream<Event> get onScroll

Stream of scroll events handled by this Element.

Implementation
ElementStream<Event> get onScroll;

onSearch no setter#

ElementStream<Event> get onSearch

Stream of search events handled by this Element.

Implementation
ElementStream<Event> get onSearch;

onSeeked no setter#

ElementStream<Event> get onSeeked
Implementation
ElementStream<Event> get onSeeked;

onSeeking no setter#

ElementStream<Event> get onSeeking
Implementation
ElementStream<Event> get onSeeking;

onSelect no setter#

ElementStream<Event> get onSelect

Stream of select events handled by this Element.

Implementation
ElementStream<Event> get onSelect;

onSelectStart no setter#

ElementStream<Event> get onSelectStart

Stream of selectstart events handled by this Element.

Implementation
ElementStream<Event> get onSelectStart;

onStalled no setter#

ElementStream<Event> get onStalled
Implementation
ElementStream<Event> get onStalled;

onSubmit no setter#

ElementStream<Event> get onSubmit

Stream of submit events handled by this Element.

Implementation
ElementStream<Event> get onSubmit;

onSuspend no setter#

ElementStream<Event> get onSuspend
Implementation
ElementStream<Event> get onSuspend;

onTimeUpdate no setter#

ElementStream<Event> get onTimeUpdate
Implementation
ElementStream<Event> get onTimeUpdate;

onTouchCancel no setter#

ElementStream<TouchEvent> get onTouchCancel

Stream of touchcancel events handled by this Element.

Implementation
ElementStream<TouchEvent> get onTouchCancel;

onTouchEnd no setter#

ElementStream<TouchEvent> get onTouchEnd

Stream of touchend events handled by this Element.

Implementation
ElementStream<TouchEvent> get onTouchEnd;

onTouchEnter no setter#

ElementStream<TouchEvent> get onTouchEnter

Stream of touchenter events handled by this Element.

Implementation
ElementStream<TouchEvent> get onTouchEnter;

onTouchLeave no setter#

ElementStream<TouchEvent> get onTouchLeave

Stream of touchleave events handled by this Element.

Implementation
ElementStream<TouchEvent> get onTouchLeave;

onTouchMove no setter#

ElementStream<TouchEvent> get onTouchMove

Stream of touchmove events handled by this Element.

Implementation
ElementStream<TouchEvent> get onTouchMove;

onTouchStart no setter#

ElementStream<TouchEvent> get onTouchStart

Stream of touchstart events handled by this Element.

Implementation
ElementStream<TouchEvent> get onTouchStart;

onTransitionEnd no setter#

ElementStream<TransitionEvent> get onTransitionEnd

Stream of transitionend events handled by this Element.

Implementation
@SupportedBrowser(SupportedBrowser.CHROME)
@SupportedBrowser(SupportedBrowser.FIREFOX)
@SupportedBrowser(SupportedBrowser.IE, '10')
@SupportedBrowser(SupportedBrowser.SAFARI)
ElementStream<TransitionEvent> get onTransitionEnd;

onVolumeChange no setter#

ElementStream<Event> get onVolumeChange
Implementation
ElementStream<Event> get onVolumeChange;

onWaiting no setter#

ElementStream<Event> get onWaiting
Implementation
ElementStream<Event> get onWaiting;

onWheel no setter#

ElementStream<WheelEvent> get onWheel
Implementation
ElementStream<WheelEvent> get onWheel;

paddingEdge no setter#

CssRect get paddingEdge

Access dimensions and position of the first Element's content + padding box in this list.

This returns a rectangle with the dimensions actually available for content in this element, in pixels, regardless of this element's box-sizing property. Unlike Element.getBoundingClientRect, the dimensions of this rectangle will return the same numerical height if the element is hidden or not. This can be used to retrieve jQuery's innerHeight value for an element. This is also a rectangle equalling the dimensions of clientHeight and clientWidth.

Implementation
CssRect get paddingEdge;

reversed no setter inherited#

Iterable<T> get reversed

An Iterable of the objects in this list in reverse order.

final numbers = <String>['two', 'three', 'four'];
final reverseOrder = numbers.reversed;
print(reverseOrder.toList()); // [four, three, two]

Inherited from ListBase.

Implementation
Iterable<E> get reversed => ReversedListIterable<E>(this);

runtimeType no setter inherited#

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
external Type get runtimeType;

single no setter inherited#

T get single

Checks that this iterable has only one element, and returns that element.

Throws a StateError if this is empty or has more than one element. This operation will not iterate past the second element.

Inherited from ListBase.

Implementation
E get single {
  if (length == 0) throw IterableElementError.noElement();
  if (length > 1) throw IterableElementError.tooMany();
  return this[0];
}

style no setter#

Access the union of all CssStyleDeclarations that are associated with an ElementList.

Grouping the style objects all together provides easy editing of specific properties of a collection of elements. Setting a specific property value will set that property in all Elements in the ElementList. Getting a specific property value will return the value of the property of the first element in the ElementList.

Implementation
CssStyleDeclarationBase get style;

Methods#

add() inherited#

void add(T element)

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

The list must be growable.

final numbers = <int>[1, 2, 3];
numbers.add(4);
print(numbers); // [1, 2, 3, 4]

Inherited from ListBase.

Implementation
void add(E element) {
  &#47;&#47; This implementation only works for lists which allow `null` as element.
  this[this.length++] = element;
}

addAll() inherited#

void addAll(Iterable<T> iterable)

Appends all objects of iterable to the end of this list.

Extends the length of the list by the number of objects in iterable. The list must be growable.

final numbers = <int>[1, 2, 3];
numbers.addAll([4, 5, 6]);
print(numbers); // [1, 2, 3, 4, 5, 6]

Inherited from ListBase.

Implementation
void addAll(Iterable<E> iterable) {
  int i = this.length;
  for (E element in iterable) {
    assert(this.length == i || (throw ConcurrentModificationError(this)));
    add(element);
    i++;
  }
}

any() inherited#

bool any(bool Function(T element) test)

Checks whether any element of this iterable satisfies test.

Checks every element in iteration order, and returns true if any of them make test return true, otherwise returns false. Returns false if the iterable is empty.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.any((element) => element >= 5); // true;
result = numbers.any((element) => element >= 10); // false;

Inherited from ListBase.

Implementation
bool any(bool test(E element)) {
  int length = this.length;
  for (int i = 0; i < length; i++) {
    if (test(this[i])) return true;
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  return false;
}

asMap() inherited#

Map<int, T> asMap()

An unmodifiable Map view of this list.

The map uses the indices of this list as keys and the corresponding objects as values. The Map.keys Iterable iterates the indices of this list in numerical order.

var words = <String>['fee', 'fi', 'fo', 'fum'];
var map = words.asMap();  // {0: fee, 1: fi, 2: fo, 3: fum}
map.keys.toList(); // [0, 1, 2, 3]

Inherited from ListBase.

Implementation
Map<int, E> asMap() {
  return ListMapView<E>(this);
}

cast() inherited#

List<R> cast<R>()

Returns a view of this list as a list of R instances.

If this list contains only instances of R, all read operations will work correctly. If any operation tries to read an element that is not an instance of R, the access will throw instead.

Elements added to the list (e.g., by using add or addAll) must be instances of R to be valid arguments to the adding function, and they must also be instances of E to be accepted by this list as well.

Methods which accept Object? as argument, like contains and remove, will pass the argument directly to the this list's method without any checks. That means that you can do listOfStrings.cast<int>().remove("a") successfully, even if it looks like it shouldn't have any effect.

Typically implemented as List.castFrom<E, R>(this).

Inherited from ListBase.

Implementation
List<R> cast<R>() => List.castFrom<E, R>(this);

clear() inherited#

void clear()

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

The list must be growable.

final numbers = <int>[1, 2, 3];
numbers.clear();
print(numbers.length); // 0
print(numbers); // []

Inherited from ListBase.

Implementation
void clear() {
  this.length = 0;
}

contains() inherited#

bool contains(Object? element)

Whether the collection contains an element equal to element.

This operation will check each element in order for being equal to element, unless it has a more efficient way to find an element equal to element. Stops iterating on the first equal element.

The equality used to determine whether element is equal to an element of the iterable defaults to the Object.== of the element.

Some types of iterable may have a different equality used for its elements. For example, a Set may have a custom equality (see Set.identity) that its contains uses. Likewise the Iterable returned by a Map.keys call should use the same equality that the Map uses for keys.

Example:

final gasPlanets = <int, String>{1: 'Jupiter', 2: 'Saturn'};
final containsOne = gasPlanets.keys.contains(1); // true
final containsFive = gasPlanets.keys.contains(5); // false
final containsJupiter = gasPlanets.values.contains('Jupiter'); // true
final containsMercury = gasPlanets.values.contains('Mercury'); // false

Inherited from ListBase.

Implementation
bool contains(Object? element) {
  int length = this.length;
  for (int i = 0; i < length; i++) {
    if (this[i] == element) return true;
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  return false;
}

elementAt() inherited#

T elementAt(int index)

Returns the indexth element.

The index must be non-negative and less than length. Index zero represents the first element (so iterable.elementAt(0) is equivalent to iterable.first).

May iterate through the elements in iteration order, ignoring the first index elements and then returning the next. Some iterables may have a more efficient way to find the element.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
final elementAt = numbers.elementAt(4); // 6

Inherited from ListBase.

Implementation
E elementAt(int index) => this[index];

every() inherited#

bool every(bool Function(T element) test)

Checks whether every element of this iterable satisfies test.

Checks every element in iteration order, and returns false if any of them make test return false, otherwise returns true. Returns true if the iterable is empty.

Example:

final planetsByMass = <double, String>{0.06: 'Mercury', 0.81: 'Venus',
  0.11: 'Mars'};
// Checks whether all keys are smaller than 1.
final every = planetsByMass.keys.every((key) => key < 1.0); // true

Inherited from ListBase.

Implementation
bool every(bool test(E element)) {
  int length = this.length;
  for (int i = 0; i < length; i++) {
    if (!test(this[i])) return false;
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  return true;
}

expand() inherited#

Iterable<T> expand<T>(Iterable<T> Function(T element) f)

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

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

The returned Iterable is lazy, and calls toElements for each element of this iterable every time the returned iterable is iterated.

Example:

Iterable<int> count(int n) sync* {
  for (var i = 1; i <= n; i++) {
    yield i;
   }
 }

var numbers = [1, 3, 0, 2];
print(numbers.expand(count)); // (1, 1, 2, 3, 1, 2)

Equivalent to:

Iterable<T> expand<T>(Iterable<T> toElements(E e)) sync* {
  for (var value in this) {
    yield* toElements(value);
  }
}

Inherited from ListBase.

Implementation
Iterable<T> expand<T>(Iterable<T> f(E element)) =>
    ExpandIterable<E, T>(this, f);

fillRange() inherited#

void fillRange(int start, int end, [ T? fill])

Overwrites a range of elements with fillValue.

Sets the positions greater than or equal to start and less than end, to fillValue.

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ startendlength. An empty range (with end == start) is valid.

If the element type is not nullable, the fillValue must be provided and must be non-null.

Example:

final words = List.filled(5, 'old');
print(words); // [old, old, old, old, old]
words.fillRange(1, 3, 'new');
print(words); // [old, new, new, old, old]

Inherited from ListBase.

Implementation
void fillRange(int start, int end, [E? fill]) {
  &#47;&#47; Hoist the case to fail eagerly if the user provides an invalid `null`
  &#47;&#47; value (or omits it) when E is a non-nullable type.
  E value = fill as E;
  RangeError.checkValidRange(start, end, this.length);
  for (int i = start; i < end; i++) {
    this[i] = value;
  }
}

firstWhere() inherited#

T firstWhere(bool Function(T element) test, { T Function()? orElse})

The first element that satisfies the given predicate test.

Iterates through elements and returns the first to satisfy test.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.firstWhere((element) => element < 5); // 1
result = numbers.firstWhere((element) => element > 5); // 6
result =
    numbers.firstWhere((element) => element > 10, orElse: () => -1); // -1

If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError. Stops iterating on the first matching element.

Inherited from ListBase.

Implementation
E firstWhere(bool test(E element), {E Function()? orElse}) {
  int length = this.length;
  for (int i = 0; i < length; i++) {
    E element = this[i];
    if (test(element)) return element;
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  if (orElse != null) return orElse();
  throw IterableElementError.noElement();
}

fold() inherited#

T fold<T>( T initialValue, T Function(T previousValue, T element) combine, );

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

Uses initialValue as the initial value, then iterates through the elements and updates the value with each element using the combine function, as if by:

var value = initialValue;
for (E element in this) {
  value = combine(value, element);
}
return value;

Example of calculating the sum of an iterable:

final numbers = <double>[10, 2, 5, 0.5];
const initialValue = 100.0;
final result = numbers.fold<double>(
    initialValue, (previousValue, element) => previousValue + element);
print(result); // 117.5

Inherited from ListBase.

Implementation
T fold<T>(T initialValue, T combine(T previousValue, E element)) {
  var value = initialValue;
  int length = this.length;
  for (int i = 0; i < length; i++) {
    value = combine(value, this[i]);
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  return value;
}

followedBy() inherited#

Iterable<T> followedBy(Iterable<T> other)

Creates the lazy concatenation of this iterable and other.

The returned iterable will provide the same elements as this iterable, and, after that, the elements of other, in the same order as in the original iterables.

Example:

var planets = <String>['Earth', 'Jupiter'];
var updated = planets.followedBy(['Mars', 'Venus']);
print(updated); // (Earth, Jupiter, Mars, Venus)

Inherited from ListBase.

Implementation
Iterable<E> followedBy(Iterable<E> other) =>
    FollowedByIterable<E>.firstEfficient(this, other);

forEach() inherited#

void forEach(void Function(T element) action)

Invokes action on each element of this iterable in iteration order.

Example:

final numbers = <int>[1, 2, 6, 7];
numbers.forEach(print);
// 1
// 2
// 6
// 7

Inherited from ListBase.

Implementation
void forEach(void action(E element)) {
  int length = this.length;
  for (int i = 0; i < length; i++) {
    action(this[i]);
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
}

getRange() inherited#

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

Creates an Iterable that iterates over a range of elements.

The returned iterable iterates over the elements of this list with positions greater than or equal to start and less than end.

The provided range, start and end, must be valid at the time of the call. A range from start to end is valid if 0 ≤ startendlength. An empty range (with end == start) is valid.

The returned Iterable behaves like skip(start).take(end - start). That is, it does not break if this list changes size, it just ends early if it reaches the end of the list early (if end, or even start, becomes greater than length).

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
final firstRange = colors.getRange(0, 3);
print(firstRange.join(', ')); // red, green, blue

final secondRange = colors.getRange(2, 5);
print(secondRange.join(', ')); // blue, orange, pink

Inherited from ListBase.

Implementation
Iterable<E> getRange(int start, int end) {
  RangeError.checkValidRange(start, end, this.length);
  return SubListIterable<E>(this, start, end);
}

indexOf() inherited#

int indexOf(Object? element, [ int start = 0])

The first index of element in this list.

Searches the list from index start to the end of the list. The first time an object o is encountered so that o == element, the index of o is returned.

final notes = <String>['do', 're', 'mi', 're'];
print(notes.indexOf('re')); // 1

final indexWithStart = notes.indexOf('re', 2); // 3

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.indexOf('fa'); // -1

Inherited from ListBase.

Implementation
int indexOf(Object? element, [int start = 0]) {
  if (start < 0) start = 0;
  for (int i = start; i < this.length; i++) {
    if (this[i] == element) return i;
  }
  return -1;
}

indexWhere() inherited#

int indexWhere(bool Function(T element) test, [ int start = 0])

The first index in the list that satisfies the provided test.

Searches the list from index start to the end of the list. The first time an object o is encountered so that test(o) is true, the index of o is returned.

final notes = <String>['do', 're', 'mi', 're'];
final first = notes.indexWhere((note) => note.startsWith('r')); // 1
final second = notes.indexWhere((note) => note.startsWith('r'), 2); // 3

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.indexWhere((note) => note.startsWith('k')); // -1

Inherited from ListBase.

Implementation
int indexWhere(bool test(E element), [int start = 0]) {
  if (start < 0) start = 0;
  for (int i = start; i < this.length; i++) {
    if (test(this[i])) return i;
  }
  return -1;
}

insert() inherited#

void insert(int index, T element)

Inserts element at position index in this list.

This increases the length of the list by one and shifts all objects at or after the index towards the end of the list.

The list must be growable. The index value must be non-negative and no greater than length.

final numbers = <int>[1, 2, 3, 4];
const index = 2;
numbers.insert(index, 10);
print(numbers); // [1, 2, 10, 3, 4]

Inherited from ListBase.

Implementation
void insert(int index, E element) {
  checkNotNullable(index, "index");
  var length = this.length;
  RangeError.checkValueInInterval(index, 0, length, "index");
  add(element);
  if (index != length) {
    setRange(index + 1, length + 1, this, index);
    this[index] = element;
  }
}

insertAll() inherited#

void insertAll(int index, Iterable<T> iterable)

Inserts all objects of iterable at position index in this list.

This increases the length of the list by the length of iterable and shifts all later objects towards the end of the list.

The list must be growable. The index value must be non-negative and no greater than length.

final numbers = <int>[1, 2, 3, 4];
final insertItems = [10, 11];
numbers.insertAll(2, insertItems);
print(numbers); // [1, 2, 10, 11, 3, 4]

Inherited from ListBase.

Implementation
void insertAll(int index, Iterable<E> iterable) {
  RangeError.checkValueInInterval(index, 0, length, "index");
  if (index == length) {
    addAll(iterable);
    return;
  }
  if (iterable is! EfficientLengthIterable || identical(iterable, this)) {
    iterable = iterable.toList();
  }
  int insertionLength = iterable.length;
  if (insertionLength == 0) {
    return;
  }
  &#47;&#47; There might be errors after the length change, in which case the list
  &#47;&#47; will end up being modified but the operation not complete. Unless we
  &#47;&#47; always go through a "toList" we can't really avoid that.
  int oldLength = length;
  for (int i = oldLength - insertionLength; i < oldLength; ++i) {
    add(this[i > 0 ? i : 0]);
  }
  if (iterable.length != insertionLength) {
    &#47;&#47; If the iterable's length is linked to this list's length somehow,
    &#47;&#47; we can't insert one in the other.
    this.length -= insertionLength;
    throw ConcurrentModificationError(iterable);
  }
  int oldCopyStart = index + insertionLength;
  if (oldCopyStart < oldLength) {
    setRange(oldCopyStart, oldLength, this, index);
  }
  setAll(index, iterable);
}

join() inherited#

String join([ String separator = ""])

Converts each element to a String and concatenates the strings.

Iterates through elements of this iterable, converts each one to a String by calling Object.toString, and then concatenates the strings, with the separator string interleaved between the elements.

Example:

final planetsByMass = <double, String>{0.06: 'Mercury', 0.81: 'Venus',
  0.11: 'Mars'};
final joinedNames = planetsByMass.values.join('-'); // Mercury-Venus-Mars

Inherited from ListBase.

Implementation
String join([String separator = ""]) {
  if (length == 0) return "";
  StringBuffer buffer = StringBuffer()..writeAll(this, separator);
  return buffer.toString();
}

lastIndexOf() inherited#

int lastIndexOf(Object? element, [ int? start])

The last index of element in this list.

Searches the list backwards from index start to 0.

The first time an object o is encountered so that o == element, the index of o is returned.

final notes = <String>['do', 're', 'mi', 're'];
const startIndex = 2;
final index = notes.lastIndexOf('re', startIndex); // 1

If start is not provided, this method searches from the end of the list.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.lastIndexOf('re'); // 3

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.lastIndexOf('fa'); // -1

Inherited from ListBase.

Implementation
int lastIndexOf(Object? element, [int? start]) {
  if (start == null || start >= this.length) start = this.length - 1;

  for (int i = start; i >= 0; i--) {
    if (this[i] == element) return i;
  }
  return -1;
}

lastIndexWhere() inherited#

int lastIndexWhere(bool Function(T element) test, [ int? start])

The last index in the list that satisfies the provided test.

Searches the list from index start to 0. The first time an object o is encountered so that test(o) is true, the index of o is returned. If start is omitted, it defaults to the length of the list.

final notes = <String>['do', 're', 'mi', 're'];
final first = notes.lastIndexWhere((note) => note.startsWith('r')); // 3
final second = notes.lastIndexWhere((note) => note.startsWith('r'),
    2); // 1

Returns -1 if element is not found.

final notes = <String>['do', 're', 'mi', 're'];
final index = notes.lastIndexWhere((note) => note.startsWith('k'));
print(index); // -1

Inherited from ListBase.

Implementation
int lastIndexWhere(bool test(E element), [int? start]) {
  if (start == null || start >= this.length) start = this.length - 1;

  for (int i = start; i >= 0; i--) {
    if (test(this[i])) return i;
  }
  return -1;
}

lastWhere() inherited#

T lastWhere(bool Function(T element) test, { T Function()? orElse})

The last element that satisfies the given predicate test.

An iterable that can access its elements directly may check its elements in any order (for example a list starts by checking the last element and then moves towards the start of the list). The default implementation iterates elements in iteration order, checks test(element) for each, and finally returns that last one that matched.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.lastWhere((element) => element < 5); // 3
result = numbers.lastWhere((element) => element > 5); // 7
result = numbers.lastWhere((element) => element > 10,
    orElse: () => -1); // -1

If no element satisfies test, the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.

Inherited from ListBase.

Implementation
E lastWhere(bool test(E element), {E Function()? orElse}) {
  int length = this.length;
  for (int i = length - 1; i >= 0; i--) {
    E element = this[i];
    if (test(element)) return element;
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  if (orElse != null) return orElse();
  throw IterableElementError.noElement();
}

map() inherited#

Iterable<T> map<T>(T Function(T element) f)

The current elements of this iterable modified by toElement.

Returns a new lazy Iterable with elements that are created by calling toElement on each element of this Iterable in iteration order.

The returned iterable is lazy, so it won't iterate the elements of this iterable until it is itself iterated, and then it will apply toElement to create one element at a time. The converted elements are not cached. Iterating multiple times over the returned Iterable will invoke the supplied toElement function once per element for on each iteration.

Methods on the returned iterable are allowed to omit calling toElement on any element where the result isn't needed. For example, elementAt may call toElement only once.

Equivalent to:

Iterable<T> map<T>(T toElement(E e)) sync* {
  for (var value in this) {
    yield toElement(value);
  }
}

Example:

var products = jsonDecode('''
[
  {"name": "Screwdriver", "price": 42.00},
  {"name": "Wingnut", "price": 0.50}
]
''');
var values = products.map((product) => product['price'] as double);
var totalPrice = values.fold(0.0, (a, b) => a + b); // 42.5.

Inherited from ListBase.

Implementation
Iterable<T> map<T>(T f(E element)) => MappedListIterable<E, T>(this, f);

noSuchMethod() inherited#

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

reduce() inherited#

T reduce(T Function(T previousValue, T element) combine)

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

The iterable must have at least one element. If it has only one element, that element is returned.

Otherwise this method starts with the first element from the iterator, and then combines it with the remaining elements in iteration order, as if by:

E value = iterable.first;
iterable.skip(1).forEach((element) {
  value = combine(value, element);
});
return value;

Example of calculating the sum of an iterable:

final numbers = <double>[10, 2, 5, 0.5];
final result = numbers.reduce((value, element) => value + element);
print(result); // 17.5

Consider using fold if the iterable can be empty.

Inherited from ListBase.

Implementation
E reduce(E combine(E previousValue, E element)) {
  int length = this.length;
  if (length == 0) throw IterableElementError.noElement();
  E value = this[0];
  for (int i = 1; i < length; i++) {
    value = combine(value, this[i]);
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  return value;
}

remove() inherited#

bool remove(Object? element)

Removes the first occurrence of value from this list.

Returns true if value was in the list, false otherwise. The list must be growable.

final parts = <String>['head', 'shoulders', 'knees', 'toes'];
final retVal = parts.remove('head'); // true
print(parts); // [shoulders, knees, toes]

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

final parts = <String>['shoulders', 'knees', 'toes'];
// Note: 'head' has already been removed.
final retVal = parts.remove('head'); // false
print(parts); // [shoulders, knees, toes]

Inherited from ListBase.

Implementation
bool remove(Object? element) {
  for (int i = 0; i < this.length; i++) {
    if (this[i] == element) {
      this._closeGap(i, i + 1);
      return true;
    }
  }
  return false;
}

removeAt() inherited#

T removeAt(int index)

Removes the object at position index from this list.

This method reduces the length of this by one and moves all later objects down by one position.

Returns the removed value.

The index must be in the range 0 ≤ index < length. The list must be growable.

final parts = <String>['head', 'shoulder', 'knees', 'toes'];
final retVal = parts.removeAt(2); // knees
print(parts); // [head, shoulder, toes]

Inherited from ListBase.

Implementation
E removeAt(int index) {
  E result = this[index];
  _closeGap(index, index + 1);
  return result;
}

removeLast() inherited#

T removeLast()

Removes and returns the last object in this list.

The list must be growable and non-empty.

final parts = <String>['head', 'shoulder', 'knees', 'toes'];
final retVal = parts.removeLast(); // toes
print(parts); // [head, shoulder, knees]

Inherited from ListBase.

Implementation
E removeLast() {
  if (length == 0) {
    throw IterableElementError.noElement();
  }
  E result = this[length - 1];
  length--;
  return result;
}

removeRange() inherited#

void removeRange(int start, int end)

Removes a range of elements from the list.

Removes the elements with positions greater than or equal to start and less than end, from the list. This reduces the list's length by end - start.

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ startendlength. An empty range (with end == start) is valid.

The list must be growable.

final numbers = <int>[1, 2, 3, 4, 5];
numbers.removeRange(1, 4);
print(numbers); // [1, 5]

Inherited from ListBase.

Implementation
void removeRange(int start, int end) {
  RangeError.checkValidRange(start, end, this.length);
  if (end > start) {
    _closeGap(start, end);
  }
}

removeWhere() inherited#

void removeWhere(bool Function(T element) test)

Removes all objects from this list that satisfy test.

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

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.removeWhere((item) => item.length == 3);
print(numbers); // [three, four]

The list must be growable.

Inherited from ListBase.

Implementation
void removeWhere(bool test(E element)) {
  _filter(test, false);
}

replaceRange() inherited#

void replaceRange(int start, int end, Iterable<T> newContents)

Replaces a range of elements with the elements of replacements.

Removes the objects in the range from start to end, then inserts the elements of replacements at start.

final numbers = <int>[1, 2, 3, 4, 5];
final replacements = [6, 7];
numbers.replaceRange(1, 4, replacements);
print(numbers); // [1, 6, 7, 5]

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ startendlength. An empty range (with end == start) is valid.

The operation list.replaceRange(start, end, replacements) is roughly equivalent to:

final numbers = <int>[1, 2, 3, 4, 5];
numbers.removeRange(1, 4);
final replacements = [6, 7];
numbers.insertAll(1, replacements);
print(numbers); // [1, 6, 7, 5]

but may be more efficient.

The list must be growable. This method does not work on fixed-length lists, even when replacements has the same number of elements as the replaced range. In that case use setRange instead.

Inherited from ListBase.

Implementation
void replaceRange(int start, int end, Iterable<E> newContents) {
  RangeError.checkValidRange(start, end, this.length);
  if (start == this.length) {
    addAll(newContents);
    return;
  }
  if (newContents is! EfficientLengthIterable) {
    newContents = newContents.toList();
  }
  int removeLength = end - start;
  int insertLength = newContents.length;
  if (removeLength >= insertLength) {
    int insertEnd = start + insertLength;
    this.setRange(start, insertEnd, newContents);
    if (removeLength > insertLength) {
      _closeGap(insertEnd, end);
    }
  } else if (end == this.length) {
    int i = start;
    for (E element in newContents) {
      if (i < end) {
        this[i] = element;
      } else {
        add(element);
      }
      i++;
    }
  } else {
    int delta = insertLength - removeLength;
    int oldLength = this.length;
    int insertEnd = start + insertLength; &#47;&#47; aka. end + delta.
    for (int i = oldLength - delta; i < oldLength; ++i) {
      add(this[i > 0 ? i : 0]);
    }
    if (insertEnd < oldLength) {
      this.setRange(insertEnd, oldLength, this, end);
    }
    this.setRange(start, insertEnd, newContents);
  }
}

retainWhere() inherited#

void retainWhere(bool Function(T element) test)

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

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

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.retainWhere((item) => item.length == 3);
print(numbers); // [one, two]

The list must be growable.

Inherited from ListBase.

Implementation
void retainWhere(bool test(E element)) {
  _filter(test, true);
}

setAll() inherited#

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

Overwrites elements with the objects of iterable.

The elements of iterable are written into this list, starting at position index. This operation does not increase the length of the list.

The index must be non-negative and no greater than length.

The iterable must not have more elements than what can fit from index to length.

If iterable is based on this list, its values may change during the setAll operation.

final list = <String>['a', 'b', 'c', 'd'];
list.setAll(1, ['bee', 'sea']);
print(list); // [a, bee, sea, d]

Inherited from ListBase.

Implementation
void setAll(int index, Iterable<E> iterable) {
  if (iterable is List) {
    setRange(index, index + iterable.length, iterable);
  } else {
    for (E element in iterable) {
      this[index++] = element;
    }
  }
}

setRange() inherited#

void setRange( int start, int end, Iterable<T> iterable, [ int skipCount = 0, ]);

Writes some elements of iterable into a range of this list.

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

final list1 = <int>[1, 2, 3, 4];
final list2 = <int>[5, 6, 7, 8, 9];
// Copies the 4th and 5th items in list2 as the 2nd and 3rd items
// of list1.
const skipCount = 3;
list1.setRange(1, 3, list2, skipCount);
print(list1); // [1, 8, 9, 4]

The provided range, given by start and end, must be valid. A range from start to end is valid if 0 ≤ startendlength. An empty range (with end == start) is valid.

The iterable must have enough objects to fill the range from start to end after skipping skipCount objects.

If iterable is this list, the operation correctly copies the elements originally in the range from skipCount to skipCount + (end - start) to the range start to end, even if the two ranges overlap.

If iterable depends on this list in some other way, no guarantees are made.

Inherited from ListBase.

Implementation
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) {
  RangeError.checkValidRange(start, end, this.length);
  int length = end - start;
  if (length == 0) return;
  RangeError.checkNotNegative(skipCount, "skipCount");

  List<E> otherList;
  int otherStart;
  &#47;&#47; TODO(floitsch): Make this accept more.
  if (iterable is List<E>) {
    otherList = iterable;
    otherStart = skipCount;
  } else {
    otherList = iterable.skip(skipCount).toList(growable: false);
    otherStart = 0;
  }
  if (otherStart + length > otherList.length) {
    throw IterableElementError.tooFew();
  }
  if (otherStart < start) {
    &#47;&#47; Copy backwards to ensure correct copy if [from] is this.
    for (int i = length - 1; i >= 0; i--) {
      this[start + i] = otherList[otherStart + i];
    }
  } else {
    for (int i = 0; i < length; i++) {
      this[start + i] = otherList[otherStart + i];
    }
  }
}

shuffle() inherited#

void shuffle([ Random? random])

Shuffles the elements of this list randomly.

final numbers = <int>[1, 2, 3, 4, 5];
numbers.shuffle();
print(numbers); // [1, 3, 4, 5, 2] OR some other random result.

Inherited from ListBase.

Implementation
void shuffle([Random? random]) {
  random ??= Random();

  int length = this.length;
  while (length > 1) {
    int pos = random.nextInt(length);
    length -= 1;
    var tmp = this[length];
    this[length] = this[pos];
    this[pos] = tmp;
  }
}

singleWhere() inherited#

T singleWhere(bool Function(T element) test, { T Function()? orElse})

The single element that satisfies test.

Checks elements to see if test(element) returns true. If exactly one element satisfies test, that element is returned. If more than one matching element is found, throws StateError. If no matching element is found, returns the result of orElse. If orElse is omitted, it defaults to throwing a StateError.

Example:

final numbers = <int>[2, 2, 10];
var result = numbers.singleWhere((element) => element > 5); // 10

When no matching element is found, the result of calling orElse is returned instead.

result = numbers.singleWhere((element) => element == 1,
    orElse: () => -1); // -1

There must not be more than one matching element.

result = numbers.singleWhere((element) => element == 2); // Throws Error.

Inherited from ListBase.

Implementation
E singleWhere(bool test(E element), {E Function()? orElse}) {
  int length = this.length;
  late E match;
  bool matchFound = false;
  for (int i = 0; i < length; i++) {
    E element = this[i];
    if (test(element)) {
      if (matchFound) {
        throw IterableElementError.tooMany();
      }
      matchFound = true;
      match = element;
    }
    if (length != this.length) {
      throw ConcurrentModificationError(this);
    }
  }
  if (matchFound) return match;
  if (orElse != null) return orElse();
  throw IterableElementError.noElement();
}

skip() inherited#

Iterable<T> skip(int count)

Creates an Iterable that provides all but the first count elements.

When the returned iterable is iterated, it starts iterating over this, first skipping past the initial count elements. If this has fewer than count elements, then the resulting Iterable is empty. After that, the remaining elements are iterated in the same order as in this iterable.

Some iterables may be able to find later elements without first iterating through earlier elements, for example when iterating a List. Such iterables are allowed to ignore the initial skipped elements.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
final result = numbers.skip(4); // (6, 7)
final skipAll = numbers.skip(100); // () - no elements.

The count must not be negative.

Inherited from ListBase.

Implementation
Iterable<E> skip(int count) => SubListIterable<E>(this, count, null);

skipWhile() inherited#

Iterable<T> skipWhile(bool Function(T element) test)

Creates an Iterable that skips leading elements while test is satisfied.

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

The returned iterable provides elements by iterating this iterable, but skipping over all initial elements where test(element) returns true. If all elements satisfy test the resulting iterable is empty, otherwise it iterates the remaining elements in their original order, starting with the first element for which test(element) returns false.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.skipWhile((x) => x < 5); // (5, 6, 7)
result = numbers.skipWhile((x) => x != 3); // (3, 5, 6, 7)
result = numbers.skipWhile((x) => x != 4); // ()
result = numbers.skipWhile((x) => x.isOdd); // (2, 3, 5, 6, 7)

Inherited from ListBase.

Implementation
Iterable<E> skipWhile(bool test(E element)) {
  return SkipWhileIterable<E>(this, test);
}

sort() inherited#

void sort([ int Function(T a, T b)? compare])

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

The compare function must act as a Comparator.

final numbers = <String>['two', 'three', 'four'];
// Sort from shortest to longest.
numbers.sort((a, b) => a.length.compareTo(b.length));
print(numbers); // [two, four, three]

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

final numbers = <int>[13, 2, -11, 0];
numbers.sort();
print(numbers); // [-11, 0, 2, 13]

In that case, the elements of the list must be Comparable to each other.

A Comparator may compare objects as equal (return zero), even if they are distinct objects. The sort function is not guaranteed to be stable, so distinct objects that compare as equal may occur in any order in the result:

final numbers = <String>['one', 'two', 'three', 'four'];
numbers.sort((a, b) => a.length.compareTo(b.length));
print(numbers); // [one, two, four, three] OR [two, one, four, three]

Inherited from ListBase.

Implementation
void sort([int Function(E a, E b)? compare]) {
  Sort.sort(this, compare ?? _compareAny);
}

sublist() inherited#

List<T> sublist(int start, [ int? end])

Returns a new list containing the elements between start and end.

The new list is a List<E> containing the elements of this list at positions greater than or equal to start and less than end in the same order as they occur in this list.

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
print(colors.sublist(1, 3)); // [green, blue]

If end is omitted, it defaults to the length of this list.

final colors = <String>['red', 'green', 'blue', 'orange', 'pink'];
print(colors.sublist(3)); // [orange, pink]

The start and end positions must satisfy the relations 0 ≤ startendlength. If end is equal to start, then the returned list is empty.

Inherited from ListBase.

Implementation
List<E> sublist(int start, [int? end]) {
  int listLength = this.length;
  end ??= listLength;

  RangeError.checkValidRange(start, end, listLength);
  return List.of(getRange(start, end));
}

take() inherited#

Iterable<T> take(int count)

Creates a lazy iterable of the count first elements of this iterable.

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

The elements can be computed by stepping through iterator until count elements have been seen.

The count must not be negative.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
final result = numbers.take(4); // (1, 2, 3, 5)
final takeAll = numbers.take(100); // (1, 2, 3, 5, 6, 7)

Inherited from ListBase.

Implementation
Iterable<E> take(int count) =>
    SubListIterable<E>(this, 0, checkNotNullable(count, "count"));

takeWhile() inherited#

Iterable<T> takeWhile(bool Function(T element) test)

Creates a lazy iterable of the leading elements satisfying test.

The filtering happens lazily. Every new iterator of the returned iterable starts iterating over the elements of this.

The elements can be computed by stepping through iterator until an element is found where test(element) is false. At that point, the returned iterable stops (its moveNext() returns false).

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.takeWhile((x) => x < 5); // (1, 2, 3)
result = numbers.takeWhile((x) => x != 3); // (1, 2)
result = numbers.takeWhile((x) => x != 4); // (1, 2, 3, 5, 6, 7)
result = numbers.takeWhile((x) => x.isOdd); // (1)

Inherited from ListBase.

Implementation
Iterable<E> takeWhile(bool test(E element)) {
  return TakeWhileIterable<E>(this, test);
}

toList() inherited#

List<T> toList({ bool growable = true})

Creates a List containing the elements of this Iterable.

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

Example:

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Mars'};
final keysList = planets.keys.toList(growable: false); // [1, 2, 3]
final valuesList =
    planets.values.toList(growable: false); // [Mercury, Venus, Mars]

Inherited from ListBase.

Implementation
List<E> toList({bool growable = true}) {
  if (this.isEmpty) return List<E>.empty(growable: growable);
  var first = this[0];
  var result = List<E>.filled(this.length, first, growable: growable);
  for (int i = 1; i < this.length; i++) {
    result[i] = this[i];
  }
  return result;
}

toSet() inherited#

Set<T> toSet()

Creates a Set containing the same elements as this iterable.

The set may contain fewer elements than the iterable, if the iterable contains an element more than once, or it contains one or more elements that are equal. The order of the elements in the set is not guaranteed to be the same as for the iterable.

Example:

final planets = <int, String>{1: 'Mercury', 2: 'Venus', 3: 'Mars'};
final valueSet = planets.values.toSet(); // {Mercury, Venus, Mars}

Inherited from ListBase.

Implementation
Set<E> toSet() {
  Set<E> result = Set<E>();
  for (int i = 0; i < length; i++) {
    result.add(this[i]);
  }
  return result;
}

toString() inherited#

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from ListBase.

Implementation
String toString() => listToString(this);

where() inherited#

Iterable<T> where(bool Function(T element) test)

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

The matching elements have the same order in the returned iterable as they have in iterator.

This method returns a view of the mapped elements. As long as the returned Iterable is not iterated over, the supplied function test will not be invoked. Iterating will not cache results, and thus iterating multiple times over the returned Iterable may invoke the supplied function test multiple times on the same element.

Example:

final numbers = <int>[1, 2, 3, 5, 6, 7];
var result = numbers.where((x) => x < 5); // (1, 2, 3)
result = numbers.where((x) => x > 5); // (6, 7)
result = numbers.where((x) => x.isEven); // (2, 6)

Inherited from ListBase.

Implementation
Iterable<E> where(bool test(E element)) => WhereIterable<E>(this, test);

whereType() inherited#

Iterable<T> whereType<T>()

Creates a new lazy Iterable with all elements that have type T.

The matching elements have the same order in the returned iterable as they have in iterator.

This method returns a view of the mapped elements. Iterating will not cache results, and thus iterating multiple times over the returned Iterable may yield different results, if the underlying elements change between iterations.

Inherited from ListBase.

Implementation
Iterable<T> whereType<T>() => WhereTypeIterable<T>(this);

Operators#

operator +() inherited#

List<T> operator +(List<T> other)

Returns the concatenation of this list and other.

Returns a new list containing the elements of this list followed by the elements of other.

The default behavior is to return a normal growable list. Some list types may choose to return a list of the same type as themselves (see Uint8List.+);

Inherited from ListBase.

Implementation
List<E> operator +(List<E> other) => [...this, ...other];

operator ==() inherited#

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

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

Inherited from Object.

Implementation
external bool operator ==(Object other);

operator []() inherited#

T operator [](int index)

The object at the given index in the list.

The index must be a valid index of this list, which means that index must be non-negative and less than length.

Inherited from List.

Implementation
E operator [](int index);

operator []=() inherited#

void operator []=(int index, T value)

Sets the value at the given index in the list to value.

The index must be a valid index of this list, which means that index must be non-negative and less than length.

Inherited from List.

Implementation
void operator []=(int index, E value);