Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update length of list in dart with default value?

Tags:

list

flutter

dart

In my app, at many places I have used Lists like this:-

List<int> nums = [];
// initializing list dynamically with some values.
nums.length = 12; // increasing length of list
// setting these values afterward using nums[i] at different places.

Now after migrating to null-safety obviously nums.length = 4 is giving me a runtime error, so I was wondering is there any method to set the length of the list with default values such that, after if the length of the list was smaller than before then with new length extra elements are added with some default value.

Note: Of course I know we can use for loop, but I was just wondering if there is any easier and cleaner method than that.

like image 498
Vishnu Avatar asked Oct 15 '25 23:10

Vishnu


2 Answers

Another approach:

extension ExtendList<T> on List<T> {
  void extend(int newLength, T defaultValue) {
    assert(newLength >= 0);

    final lengthDifference = newLength - this.length;
    if (lengthDifference <= 0) {
      return;
    }

    this.addAll(List.filled(lengthDifference, defaultValue));
  }
}

void main() {
  var list = <int>[];
  list.extend(4, 0);
  print(list); // [0, 0, 0, 0];
}

Or, if you must set .length instead of calling a separate method, you could combine it with a variation of julemand101's answer to fill with a specified default value instead of with null:

class ExtendableList<T> with ListMixin<T> {
  ExtendableList(this.defaultValue);

  final T defaultValue;
  final List<T> _list = [];

  @override
  int get length => _list.length;

  @override
  T operator [](int index) => _list[index];

  @override
  void operator []=(int index, T value) {
    if (index >= length) {
      _list.extend(index + 1, defaultValue);
    }
    _list[index] = value;
  }

  @override
  set length(int newLength) {
    if (newLength > length) {
      _list.extend(newLength, defaultValue);
    } else {
      _list.length = newLength;
    }
  }
}

(I also made its operator []= automatically grow the ExtendableList if the specified index is out-of-bounds, similar to JavaScript.)

like image 194
jamesdlin Avatar answered Oct 18 '25 17:10

jamesdlin


var num = List<int>.generate(4, (i) => i);

You can read this.

like image 38
Ουιλιαμ Αρκευα Avatar answered Oct 18 '25 17:10

Ουιλιαμ Αρκευα



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!