newList method

List<T> newList(
  1. int length, {
  2. bool growable = false,
  3. bool reactive = true,
})

Returns a new list of this kind, which is guaranteed some properties.

The method allocates the most performant list possible. For instance, Float32Kind, will give you a dart:typed_data Float32List rather than normal List<double>.

Example

import 'package:kind/kind.dart';

void main() {
  final kind = StringKind();
  final list = kind.newList(
    3,
    growable: false,
    reactive: false,
  );
}

Implementation

List<T> newList(int length, {bool growable = false, bool reactive = true}) {
  late List<T> list;
  if (length < 0) {
    throw ArgumentError.value(length, 'length');
  } else if (length == 0) {
    list = List<T>.empty(
      growable: growable,
    );
    // Non-growable empty list can't be mutated,
    // so it does not need to be reactive.
    if (!growable) {
      return list;
    }
  } else {
    // Construct default instance.
    late T defaultInstance;
    try {
      defaultInstance = newInstance();
    } catch (error, stackTrace) {
      throw TraceableError(
        message:
            'Constructing `List<$name>` (length $length) failed because filler instance could not be constructed.',
        error: error,
        stackTrace: stackTrace,
      );
    }
    list = List<T>.filled(
      length,
      defaultInstance,
      growable: growable,
    );

    // The defaultInstance could be mutable, so we need to construct a new
    // instance for every index.
    //
    // We can retain the item at index 0.
    //
    // In PrimitiveKind we override this method to avoid this.
    for (var i = 1; i < length; i++) {
      list[i] = newInstance();
    }
  }

  // Wrap with ReactiveList?
  if (reactive) {
    return ReactiveList<T>.wrap(list);
  }

  return list;
}