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

问题描述 投票:0回答:1
  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);
  }

因此,我基本上想做的是在共享首选项中的指定索引(我检查并正确返回索引)中保存一个问题选项。当它运行并按该选项时,它会向我返回以下错误:

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

之所以使用插入方法而不是添加方法,是因为在用户想要覆盖其先前答案的情况下,我想本质上替换已经存储在索引中的值。有人可以帮忙吗?谢谢

flutter dart sharedpreferences
1个回答
0
投票

[如果您想要某种行为像稀疏数组,则可以改用Map。如果您希望能够按数字索引依次遍历项目,则可以使用SplayTreeMap

例如:

© www.soinside.com 2019 - 2024. All rights reserved.