如何将特定索引处的值添加到 dart 中的空列表?

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);
  }

所以基本上我想做的是在共享首选项中为指定索引处的问题保存一个选项(我检查并正确返回了索引)。当它运行并且我按下选项时,它 returns 给我以下错误:

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

我使用 insert 方法而不是 add 方法的原因是因为我想基本上替换已经存储在索引中的值,以防用户想要覆盖他们以前的答案。有人可以帮忙吗?谢谢

如果您想要类似于稀疏数组的内容,可以改用 Map。如果您希望能够按数字索引(而不是插入顺序)顺序遍历项目,您可以使用 SplayTreeMap.

例如:

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}');
  }
}

打印:

3: Hello
12: world!