blue492
blue492

Reputation: 670

insert value at specific index in empty list dart

I want to add element at specific index in empty list dart like the following

List values = List();
values[87] = {'value': 'hello'};

When I try to run this code it shows this error

Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 87

The solution is to set the list length List values = List(100); but the problem is I dont know the length because the index is the id, it can be 87 or 1523 .... so I can not set the length.

Another solution is to use final sparseList = SplayTreeMap<int, dynamic>(); and insert the element sparseList[87] = {'value': 'hello'};

The problem with SplayTreeMap is I cannon do jsonencode or json.encode to this type of list, it shows this error msg

Unhandled Exception: Converting object to an encodable object failed: Instance of 'SplayTreeMap<int, dynamic>'

Questions:

1- How to set element at a specific index in empty list in dart?

2- How to json encode a SplayTreeMap list to send it to the server to php file.

Thanks

Upvotes: 1

Views: 2551

Answers (1)

jamesdlin
jamesdlin

Reputation: 90025

I want to add element at specific index in empty list dart like the following

One way would be to add a convenience function to append dummy elements to the List if necessary.

extension ListFiller<T> on List<T> {
  void fillAndSet(int index, T value) {
    if (index >= this.length) {
      this.addAll(List<T>.filled(index - this.length + 1, null));
    }
    this[index] = value;
  }
}

void main() {
  var list = <String>[];
  list.fillAndSet(3, 'world');
  list.fillAndSet(2, 'hello');
  print(list); // Prints: [null, null, hello, world]
}

The problem with SplayTreeMap is I cannon do jsonencode or json.encode to this type of list

The jsonEncode documentation states (with emphasis added):

If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), ...

So the reason why jsonEncode failed for SplayTreeMap<int, dynamic> is not because it's a SplayTreeMap instead of a Map/LinkedHashMap but because your keys are not Strings. (jsonEncode on a SplayTreeMap<String, dynamic> should work.) You could convert your SplayTreeMap<int, dynamic> when encoding:

final sparseList = SplayTreeMap<int, dynamic>();

...

var encoded = jsonEncode(<String, dynamic>{
  for (var mapEntry in sparseList.entries)
    mapEntry.key.toString(): mapEntry.value,
});

Upvotes: 2

Related Questions