How do I add a value at a specific index to an empty list in dart?

Viewed 2215
  List<String> currentList =new List<String>(); 
void initState() {
    super.initState();
    currentList=[];
  }
Future<Null> savePreferences(option,questionIndex) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    currentList.insert(questionIndex, option);
  }

So basically what I am trying to do is save an option for a question at the specified index (I checked and the index is returned properly) in shared preferences. When it runs and I press the option, it returns to me the following error:

E/flutter ( 6354): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: RangeError (index): Invalid value: Valid alue range is empty: 0

The reason I am using the insert method and not the add method is because I want to essentially replace the value that is already stored at the index in the case that the user wants to overwrite their previous answer. Can someone help? Thanks

1 Answers

If you want something that acts like a sparse array, you can use a Map instead. If you want to be able to iterate over the items in order by numeric index (instead of by insertion order), you could use a SplayTreeMap.

For example:

import 'dart:collection';

void main() {
  final sparseList = SplayTreeMap<int, String>();
  sparseList[12] = 'world!';
  sparseList[3] = 'Hi';
  sparseList[3] = 'Hello';
  for (var entry in sparseList.entries) {
    print('${entry.key}: ${entry.value}');
  }
}

prints:

3: Hello
12: world!
Related