Line data Source code
1 : import 'dart:collection'; 2 : 3 : /// {@template iterable.immutable_list} 4 : /// Base class for immutable lists. 5 : /// Creates an unmodifiable list backed by source. 6 : /// 7 : /// The source of the elements may be a [List] or any [Iterable] with 8 : /// efficient [Iterable.length] and [Iterable.elementAt]. 9 : /// {@endtemplate} 10 : class ImmutableList<E> extends IterableBase<E> { 11 : /// {@macro iterable.immutable_list} 12 1 : ImmutableList(Iterable<E> source) 13 1 : : _source = List<E>.of(source, growable: false); 14 : 15 : /// {@macro iterable.immutable_list} 16 : /// Empty collection 17 1 : const ImmutableList.empty() : _source = const Iterable.empty(); 18 : 19 : final Iterable<E> _source; 20 : 21 1 : @override 22 3 : ImmutableList<R> cast<R>() => ImmutableList<R>(_source.cast<R>()); 23 : 24 1 : @override 25 2 : int get length => _source.length; 26 : 27 1 : @override 28 2 : E get last => _source.last; 29 : 30 1 : @override 31 2 : Iterator<E> get iterator => _source.iterator; 32 : 33 : /// Adds [value] to the end of this list, 34 : /// Returns a new list with the element added. 35 1 : ImmutableList<E> add(E value) => 36 4 : ImmutableList<E>(List<E>.of(_source)..add(value)); 37 : 38 : /// Appends all objects of [iterable] to the end of this list. 39 : /// Returns a new list with the elements added. 40 1 : ImmutableList<E> addAll(Iterable<E> iterable) => 41 4 : ImmutableList<E>(List<E>.of(_source)..addAll(iterable)); 42 : 43 : /// Removes the first occurrence of [value] from this list. 44 : /// Returns a new list with removed element. 45 2 : ImmutableList<E> remove(E value) => ImmutableList<E>( 46 3 : List<E>.of(_source)..remove(value), 47 : ); 48 : 49 : /// Removes all objects from this list that satisfy [test]. 50 : /// 51 : /// An object `o` satisfies [test] if `test(o)` is true. 52 : /// ```dart 53 : /// final numbers = <String>['one', 'two', 'three', 'four']; 54 : /// numbers.removeWhere((item) => item.length == 3); 55 : /// print(numbers); // [three, four] 56 : /// ``` 57 : /// Returns a new list with removed element. 58 2 : ImmutableList<E> removeWhere(bool Function(E) test) => ImmutableList<E>( 59 3 : List<E>.of(_source)..removeWhere(test), 60 : ); 61 : 62 : /// Set element. 63 : /// Returns a new list with element. 64 2 : ImmutableList<E> set(E element) => ImmutableList<E>( 65 2 : List<E>.of(_source) 66 1 : ..remove(element) 67 1 : ..add(element), 68 : ); 69 : 70 : /// Sorts this list according to the order specified by the [compare] function 71 2 : ImmutableList<E> sort([int Function(E a, E b)? compare]) => ImmutableList<E>( 72 3 : List<E>.of(_source, growable: false)..sort(compare), 73 : ); 74 : 75 : /// Returns the element at the given [index] in the list 76 : /// or throws an [RangeError] 77 3 : E operator [](int index) => _source.elementAt(index); 78 : }