ListQueue<E> final#
List based Queue.
Keeps a cyclic buffer of elements, and grows to a larger buffer when it fills up. This guarantees constant time peek and remove operations, and amortized constant time add operations.
The structure is efficient for any queue or stack usage.
Example:
final queue = ListQueue<int>();
To add objects to a queue, use add, addAll, addFirst oraddLast.
queue.add(5);
queue.addFirst(0);
queue.addLast(10);
queue.addAll([1, 2, 3]);
print(queue); // {0, 5, 10, 1, 2, 3}
To check if the queue is empty, use isEmpty or isNotEmpty. To find the number of queue entries, use length.
final isEmpty = queue.isEmpty; // false
final queueSize = queue.length; // 6
To get first or last item from queue, use first or last.
final first = queue.first; // 0
final last = queue.last; // 3
To get item value using index, use elementAt.
final itemAt = queue.elementAt(2); // 10
To convert queue to list, call toList.
final numbers = queue.toList();
print(numbers); // [0, 5, 10, 1, 2, 3]
To remove item from queue, call remove, removeFirst or removeLast.
queue.remove(10);
queue.removeFirst();
queue.removeLast();
print(queue); // {5, 1, 2}
To remove multiple elements at the same time, use removeWhere.
queue.removeWhere((element) => element == 1);
print(queue); // {5, 2}
To remove all elements in this queue that do not meet a condition, use retainWhere.
queue.retainWhere((element) => element < 4);
print(queue); // {2}
To remove all items and empty the set, use clear.
queue.clear();
print(queue.isEmpty); // true
print(queue); // {}
Inheritance
Object → Iterable<E> → ListQueue<E>
Implemented types
Available Extensions
Constructors#
ListQueue()#
Create an empty queue.
If initialCapacity is given, prepare the queue for at least that many
elements.
Implementation
ListQueue([int? initialCapacity])
: _head = 0,
_tail = 0,
_table = List<E?>.filled(_calculateCapacity(initialCapacity), null);
ListQueue.from() factory#
Create a ListQueue containing all elements.
The elements are added to the queue, as by addLast, in the order given
by elements.iterator.
All the elements should be instances of E.
The elements iterable itself may have any element type, so this
constructor can be used to down-cast a Queue, for example as:
Queue<SuperType> superQueue = ...;
Queue<SubType> subQueue =
ListQueue<SubType>.from(superQueue.whereType<SubType>());
Example:
final numbers = <num>[10, 20, 30];
final queue = ListQueue<int>.from(numbers);
print(queue); // {10, 20, 30}
Implementation
factory ListQueue.from(Iterable<dynamic> elements) {
if (elements is List<dynamic>) {
int length = elements.length;
ListQueue<E> queue = ListQueue<E>(length + 1);
assert(queue._table.length > length);
for (int i = 0; i < length; i++) {
queue._table[i] = elements[i] as E;
}
queue._tail = length;
return queue;
} else {
int capacity = _INITIAL_CAPACITY;
if (elements is EfficientLengthIterable) {
capacity = elements.length;
}
ListQueue<E> result = ListQueue<E>(capacity);
for (final element in elements) {
result.addLast(element as E);
}
return result;
}
}
ListQueue.of() factory#
Create a ListQueue from elements.
The elements are added to the queue, as by addLast, in the order given
by elements.iterator.
Example:
final baseQueue = ListQueue.of([1.0, 2.0, 3.0]); // A ListQueue<double>
final numQueue = ListQueue<num>.of(baseQueue);
print(numQueue); // {1.0, 2.0, 3.0}
Implementation
factory ListQueue.of(Iterable<E> elements) =>
ListQueue<E>()..addAll(elements);
Properties#
first no setter#
The first element.
Throws a StateError if
this is empty.
Otherwise returns the first element in the iteration order,
equivalent to this.elementAt(0).
Implementation
E get first {
if (_head == _tail) throw IterableElementError.noElement();
return _table[_head] as E;
}
firstOrNull extension no setter#
The first element of this iterator, or null if the iterable is empty.
Available on Iterable<E>, provided by the IterableExtensions<T> extension
Implementation
T? get firstOrNull {
var iterator = this.iterator;
if (iterator.moveNext()) return iterator.current;
return null;
}
hashCode no setter inherited#
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;
indexed extension no setter#
Pairs of elements of the indices and elements of this iterable.
The elements are (0, this.first) through
(this.length - 1, this.last), in index/iteration order.
Available on Iterable<E>, provided by the IterableExtensions<T> extension
Implementation
@pragma('vm:prefer-inline')
Iterable<(int, T)> get indexed => IndexedIterable<T>(this, 0);
isEmpty no setter#
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
Implementation
bool get isEmpty => _head == _tail;
isNotEmpty no setter inherited#
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 Iterable.
Implementation
bool get isNotEmpty => !isEmpty;
iterator no setter#
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.
Implementation
Iterator<E> get iterator => _ListQueueIterator<E>(this);
last no setter#
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).
Implementation
E get last {
if (_head == _tail) throw IterableElementError.noElement();
return _table[(_tail - 1) & (_table.length - 1)] as E;
}
lastOrNull extension no setter#
The last element of this iterable, or null if the iterable is empty.
This computation may not be efficient. The last value is potentially found by iterating the entire iterable and temporarily storing every value. The process only iterates the iterable once. If iterating more than once is not a problem, it may be more efficient for some iterables to do:
var lastOrNull = iterable.isEmpty ? null : iterable.last;
Available on Iterable<E>, provided by the IterableExtensions<T> extension
Implementation
T? get lastOrNull {
if (this is EfficientLengthIterable) {
if (isEmpty) return null;
return last;
}
var iterator = this.iterator;
if (!iterator.moveNext()) return null;
T result;
do {
result = iterator.current;
} while (iterator.moveNext());
return result;
}
length no setter#
Returns the number of elements in the iterable.
This is an efficient operation that doesn't require iterating through the elements.
Implementation
int get length => (_tail - _head) & (_table.length - 1);
nonNulls extension no setter#
The non-null elements of this iterable.
The same elements as this iterable, except that null values
are omitted.
Available on Iterable<E>, provided by the NullableIterableExtensions<T extends Object> extension
Implementation
Iterable<T> get nonNulls => NonNullsIterable<T>(this);
runtimeType no setter inherited#
A representation of the runtime type of the object.
Inherited from Object.
Implementation
external Type get runtimeType;
single no setter#
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.
Implementation
E get single {
if (_head == _tail) throw IterableElementError.noElement();
if (length > 1) throw IterableElementError.tooMany();
return _table[_head] as E;
}
singleOrNull extension no setter#
The single element of this iterator, or null.
If the iterator has precisely one element, this is that element.
Otherwise, if the iterator has zero elements, or it has two or more,
the value is null.
Available on Iterable<E>, provided by the IterableExtensions<T> extension
Implementation
T? get singleOrNull {
var iterator = this.iterator;
if (iterator.moveNext()) {
var result = iterator.current;
if (!iterator.moveNext()) return result;
}
return null;
}
wait extension no setter#
Waits for futures in parallel.
Waits for all the futures in this iterable. Returns a list of the resulting values, in the same order as the futures which created them, if all futures are successful.
Similar to Future.wait, but reports errors using a ParallelWaitError, which allows the caller to handle errors and dispose successful results if necessary.
The returned future is completed when all the futures have completed. If any of the futures do not complete, nor does the returned future.
If any future completes with an error,
the returned future completes with a ParallelWaitError.
The ParallelWaitError.values
is a list of the values for
successful futures and null for futures with errors.
The ParallelWaitError.errors
is a list of the same length,
with null values for the successful futures
and an AsyncError
with the error for futures
which completed with an error.
Available on Iterable<E>, provided by the FutureIterable<T> extension
Implementation
Future<List<T>> get wait {
var results = [for (var f in this) _FutureResult<T>(f)];
if (results.isEmpty) return Future<List<T>>.value(<T>[]);
@pragma('vm:awaiter-link')
final c = Completer<List<T>>.sync();
_FutureResult._waitAll(results, (errors) {
if (errors == 0) {
c.complete([for (var r in results) r.value]);
} else {
var errorList = [for (var r in results) r.errorOrNull];
c.completeError(
ParallelWaitError<List<T?>, List<AsyncError?>>(
[for (var r in results) r.valueOrNull],
errorList,
errorCount: errors,
defaultError: errorList.firstWhere(_notNull),
),
);
}
});
return c.future;
}
Methods#
add() override#
Adds value at the end of the queue.
Implementation
void add(E value) {
_add(value);
}
addAll() override#
Adds all elements of iterable at the end of the queue. The
length of the queue is extended by the length of iterable.
Implementation
void addAll(Iterable<E> elements) {
if (elements is List<E>) {
List<E> list = elements;
int addCount = list.length;
int length = this.length;
if (length + addCount >= _table.length) {
_preGrow(length + addCount);
// After preGrow, all elements are at the start of the list.
_table.setRange(length, length + addCount, list, 0);
_tail += addCount;
} else {
// Adding addCount elements won't reach _head.
int endSpace = _table.length - _tail;
if (addCount < endSpace) {
_table.setRange(_tail, _tail + addCount, list, 0);
_tail += addCount;
} else {
int preSpace = addCount - endSpace;
_table.setRange(_tail, _tail + endSpace, list, 0);
_table.setRange(0, preSpace, list, endSpace);
_tail = preSpace;
}
}
_modificationCount++;
} else {
for (E element in elements) _add(element);
}
}
addFirst() override#
Adds value at the beginning of the queue.
Implementation
void addFirst(E value) {
_head = (_head - 1) & (_table.length - 1);
_table[_head] = value;
if (_head == _tail) _grow();
_modificationCount++;
}
addLast() override#
Adds value at the end of the queue.
Implementation
void addLast(E value) {
_add(value);
}
any() inherited#
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 ListIterable.
Implementation
bool any(bool test(E element)) {
int length = this.length;
for (int i = 0; i < length; i++) {
if (test(elementAt(i))) return true;
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return false;
}
asNameMap() extension#
Creates a map from the names of enum values to the values.
The collection that this method is called on is expected to have
enums with distinct names, like the values list of an enum class.
Only one value for each name can occur in the created map,
so if two or more enum values have the same name (either being the
same value, or being values of different enum type), at most one of
them will be represented in the returned map.
Available on Iterable<E>, provided by the EnumByName<T extends Enum> extension
Implementation
Map<String, T> asNameMap() => <String, T>{
for (var value in this) value._name: value,
};
byName() extension#
Finds the enum value in this list with name name.
Goes through this collection looking for an enum with
name name, as reported by EnumName.name.
Returns the first value with the given name. Such a value must be found.
Available on Iterable<E>, provided by the EnumByName<T extends Enum> extension
Implementation
T byName(String name) {
for (var value in this) {
if (value._name == name) return value;
}
throw ArgumentError.value(name, "name", "No enum value with that name");
}
cast() override#
A view of this iterable as an iterable of R instances.
If this iterable only contains instances of R, all operations
will work correctly. If any operation tries to access an element
that is not an instance of R, the access will throw instead.
When the returned iterable creates a new object that depends on
the type R, e.g., from toList, it will have exactly the type
R.
Implementation
Queue<R> cast<R>() => Queue.castFrom<E, R>(this);
clear() override#
Removes all elements in the queue. The size of the queue becomes zero.
Implementation
void clear() {
if (_head != _tail) {
for (int i = _head; i != _tail; i = (i + 1) & (_table.length - 1)) {
_table[i] = null;
}
_head = _tail = 0;
_modificationCount++;
}
}
contains() inherited#
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 ListIterable.
Implementation
bool contains(Object? element) {
int length = this.length;
for (int i = 0; i < length; i++) {
if (elementAt(i) == element) return true;
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return false;
}
elementAt()#
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
Implementation
E elementAt(int index) {
IndexError.check(index, length, indexable: this);
return _table[(_head + index) & (_table.length - 1)] as E;
}
elementAtOrNull() extension#
The element at position index of this iterable, or null.
The index is zero based, and must be non-negative.
Returns the result of elementAt(index) if the iterable has
at least index + 1 elements, and null otherwise.
Available on Iterable<E>, provided by the IterableExtensions<T> extension
Implementation
T? elementAtOrNull(int index) {
RangeError.checkNotNegative(index, "index");
if (this is EfficientLengthIterable) {
if (index >= length) return null;
return elementAt(index);
}
var iterator = this.iterator;
do {
if (!iterator.moveNext()) return null;
} while (--index >= 0);
return iterator.current;
}
every() inherited#
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 ListIterable.
Implementation
bool every(bool test(E element)) {
int length = this.length;
for (int i = 0; i < length; i++) {
if (!test(elementAt(i))) return false;
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return true;
}
expand() inherited#
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 Iterable.
Implementation
Iterable<T> expand<T>(Iterable<T> toElements(E element)) =>
ExpandIterable<E, T>(this, toElements);
firstWhere() inherited#
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 ListIterable.
Implementation
E firstWhere(bool test(E element), {E Function()? orElse}) {
int length = this.length;
for (int i = 0; i < length; i++) {
E element = elementAt(i);
if (test(element)) return element;
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
if (orElse != null) return orElse();
throw IterableElementError.noElement();
}
fold() inherited#
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 ListIterable.
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, elementAt(i));
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return value;
}
followedBy() inherited#
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 Iterable.
Implementation
Iterable<E> followedBy(Iterable<E> other) {
var self = this; // TODO(lrn): Remove when we can promote `this`.
if (self is EfficientLengthIterable<E>) {
return FollowedByIterable<E>.firstEfficient(self, other);
}
return FollowedByIterable<E>(this, other);
}
forEach()#
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
Implementation
void forEach(void f(E element)) {
int modificationCount = _modificationCount;
for (int i = _head; i != _tail; i = (i + 1) & (_table.length - 1)) {
f(_table[i] as E);
_checkModification(modificationCount);
}
}
join() inherited#
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 ListIterable.
Implementation
String join([String separator = ""]) {
int length = this.length;
if (!separator.isEmpty) {
if (length == 0) return "";
String first = "${elementAt(0)}";
if (length != this.length) {
throw ConcurrentModificationError(this);
}
StringBuffer buffer = StringBuffer(first);
for (int i = 1; i < length; i++) {
buffer.write(separator);
buffer.write(elementAt(i));
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return buffer.toString();
} else {
StringBuffer buffer = StringBuffer();
for (int i = 0; i < length; i++) {
buffer.write(elementAt(i));
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return buffer.toString();
}
}
lastWhere() inherited#
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 ListIterable.
Implementation
E lastWhere(bool test(E element), {E Function()? orElse}) {
int length = this.length;
for (int i = length - 1; i >= 0; i--) {
E element = elementAt(i);
if (test(element)) return element;
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
if (orElse != null) return orElse();
throw IterableElementError.noElement();
}
map() inherited#
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 ListIterable.
Implementation
Iterable<T> map<T>(T toElement(E element)) =>
MappedListIterable<E, T>(this, toElement);
noSuchMethod() inherited#
Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dynamic object = 1;
object.add(42); // Statically allowed, run-time error
This invalid code will invoke the noSuchMethod method
of the integer 1 with an Invocation
representing the
.add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}
This code has no compile-time warnings or errors even though
the MockList class has no concrete implementation of
any of the List interface methods.
Calls to List methods are forwarded to noSuchMethod,
so this code will log an invocation similar to
Invocation.method(#add, [42])
and then throw.
If a value is returned from noSuchMethod,
it becomes the result of the original invocation.
If the value is not of a type that can be returned by the original
invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
reduce() inherited#
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 ListIterable.
Implementation
E reduce(E combine(E value, E element)) {
int length = this.length;
if (length == 0) throw IterableElementError.noElement();
E value = elementAt(0);
for (int i = 1; i < length; i++) {
value = combine(value, elementAt(i));
if (length != this.length) {
throw ConcurrentModificationError(this);
}
}
return value;
}
remove() override#
Removes a single instance of value from the queue.
Returns true if a value was removed, or false if the queue
contained no element equal to value.
Implementation
bool remove(Object? value) {
for (int i = _head; i != _tail; i = (i + 1) & (_table.length - 1)) {
E? element = _table[i];
if (element == value) {
_remove(i);
_modificationCount++;
return true;
}
}
return false;
}
removeFirst() override#
Removes and returns the first element of this queue.
The queue must not be empty when this method is called.
Implementation
E removeFirst() {
if (_head == _tail) throw IterableElementError.noElement();
_modificationCount++;
E result = _table[_head] as E;
_table[_head] = null;
_head = (_head + 1) & (_table.length - 1);
return result;
}
removeLast() override#
Removes and returns the last element of the queue.
The queue must not be empty when this method is called.
Implementation
E removeLast() {
if (_head == _tail) throw IterableElementError.noElement();
_modificationCount++;
_tail = (_tail - 1) & (_table.length - 1);
E result = _table[_tail] as E;
_table[_tail] = null;
return result;
}
removeWhere() override#
Remove all elements matched by test.
This method is inefficient since it works by repeatedly removing single elements, each of which can take linear time.
Implementation
void removeWhere(bool test(E element)) {
_filterWhere(test, true);
}
retainWhere() override#
Remove all elements not matched by test.
This method is inefficient since it works by repeatedly removing single elements, each of which can take linear time.
Implementation
void retainWhere(bool test(E element)) {
_filterWhere(test, false);
}
singleWhere() inherited#
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 ListIterable.
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 = elementAt(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#
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 ListIterable.
Implementation
Iterable<E> skip(int count) => SubListIterable<E>(this, count, null);
skipWhile() inherited#
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 ListIterable.
Implementation
Iterable<E> skipWhile(bool test(E element)) => super.skipWhile(test);
take() inherited#
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 ListIterable.
Implementation
Iterable<E> take(int count) =>
SubListIterable<E>(this, 0, checkNotNullable(count, "count"));
takeWhile() inherited#
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 ListIterable.
Implementation
Iterable<E> takeWhile(bool test(E element)) => super.takeWhile(test);
toList()#
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]
Implementation
List<E> toList({bool growable = true}) {
int mask = _table.length - 1;
int length = (_tail - _head) & mask;
if (length == 0) return List<E>.empty(growable: growable);
var list = List<E>.filled(length, first, growable: growable);
for (int i = 0; i < length; i++) {
list[i] = _table[(_head + i) & mask] as E;
}
return list;
}
toSet() inherited#
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 ListIterable.
Implementation
Set<E> toSet() {
Set<E> result = Set<E>();
for (int i = 0; i < length; i++) {
result.add(elementAt(i));
}
return result;
}
toString() override#
Returns a string representation of (some of) the elements of this.
Elements are represented by their own toString results.
The default representation always contains the first three elements. If there are less than a hundred elements in the iterable, it also contains the last two elements.
If the resulting string isn't above 80 characters, more elements are included from the start of the iterable.
The conversion may omit calling toString on some elements if they
are known to not occur in the output, and it may stop iterating after
a hundred elements.
Implementation
String toString() => Iterable.iterableToFullString(this, "{", "}");
where() inherited#
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 ListIterable.
Implementation
Iterable<E> where(bool test(E element)) => super.where(test);
whereType() inherited#
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 Iterable.
Implementation
Iterable<T> whereType<T>() => WhereTypeIterable<T>(this);
Operators#
operator ==() inherited#
The equality operator.
The default behavior for all Objects is to return true if and
only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.-
Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false. -
Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
external bool operator ==(Object other);