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
For adding elements to a List , we can use add , addAll , insert , or insertAll . Those methods return void and they mutate the List object.
The insert() method in Dart is used to insert an element at a specific index in the list. This increases the list's length by one and moves all elements after the index towards the end of the list.
Using addAll() method to add all the elements of another list to the existing list. Creating a new list by adding two or more lists using addAll() method of the list. Creating a new list by adding two or more list using expand() method of the list. Using + operator to combine list.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With