【问题标题】:Flutter. Dart. Flutter - replacing a item in a list扑。镖。 Flutter - 替换列表中的项目
【发布时间】:2021-06-13 15:57:34
【问题描述】:
List<int> myList = [1,2,3];
int i = 2;
myList[i] = 4; // myList = [1,2,4]

但是如果我不知道 myList 是否包含特定索引处的数据怎么办?然后它给了我范围错误。

i = 4;
myList[i] = 4 // range error
if(myList[i] != null) myList[i] = 4 //range error
myList.insert(i, 4) // i want to replace, not shift values.

在特定索引处替换列表值的唯一方法是先检查整个列表长度吗?

【问题讨论】:

  • 你的第一行问题是错误的。 List&lt;myList&gt; = [1,2,3]; 在那里是变量名。什么是列表类型?我认为根据您给定的数据,它是 int 的。请提供有效信息。
  • 即使我发布了我的答案(对于 int)。你可以去看看。

标签: list flutter dart replace


【解决方案1】:

这是您可以在之前检查索引的示例,如果该条件为真,那么只有它会更新值。

void main() {
  List<int> myList1 = [1,2,3];
  int i = 2;
  if(myList1.length> i) myList1[i] = 4; // myList = [1,2,4]
  myList1.forEach(print);
  
  
  int j = 5;
  if(myList1.length> j) myList1[j] = 4; // myList = [1,2,4]
  myList1.forEach(print); // It will print as it is last one.
}

谢谢。

【讨论】:

    【解决方案2】:

    据我了解,您想知道是否有任何其他方法可以检查您的列表是否存在索引。 如果是的话:

    List<int> myList = [1,2,3];
    int i = 2;
    if(myList.asMap().containsKey(i)) myList[i] = 4
    
    

    如果我理解你的问题,请告诉我。

    【讨论】:

    • 是的,但是,有没有更高效的方法来做到这一点,开箱即用?如果不是,这是一个选项。
    • myList = myList.map((e) =&gt; e == 2 ? 4 : e).toList();
    【解决方案3】:

    试试这样:

    if(i<=myList.length){
     myList[i]=4;
     }
    

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 1970-01-01
      • 2019-12-02
      • 2012-11-11
      • 1970-01-01
      • 2010-09-15
      • 2019-02-21
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多