如何将特定索引处的值添加到 dart 中的空列表中? [英] How do I add a value at a specific index to an empty list in dart?

查看:35
本文介绍了如何将特定索引处的值添加到 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

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

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

推荐答案

如果你想要一些像稀疏数组一样的东西,你可以使用 Map 代替.如果您希望能够按数字索引(而不是按插入顺序)按顺序迭代项目,则可以使用 SplayTreeMap.

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.

例如:

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!

这篇关于如何将特定索引处的值添加到 dart 中的空列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆