Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  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

like image 454
Gautham Hari Avatar asked Jun 14 '20 02:06

Gautham Hari


People also ask

How do you add an element to an empty list in darts?

For adding elements to a List , we can use add , addAll , insert , or insertAll . Those methods return void and they mutate the List object.

How do I add a element to an index in darts?

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.

How do you append to a Dart 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.


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!
like image 155
jamesdlin Avatar answered Oct 18 '22 01:10

jamesdlin