Dart 编程 - 更新列表



更新索引

Dart 允许修改列表中项目的 值。换句话说,可以重写列表项的值。以下示例说明了这一点:

void main() { 
   List l = [1, 2, 3,]; 
   l[0] = 123;
   print (l);
}

以上示例更新了索引为 0 的列表项的值。代码的输出将为:

[123, 2, 3]

使用 List.replaceRange() 函数

来自 dart:core 库的 List 类提供replaceRange()函数来修改列表项。此函数替换指定范围内的元素的值。

使用 List.replaceRange() 函数的语法如下所示:

List.replaceRange(int start_index,int end_index,Iterable <items>)

其中,

  • Start_index - 表示开始替换的索引位置的整数。

  • End_index - 表示停止替换的索引位置的整数。

  • <items> - 表示更新值的 iterable 对象。

以下示例说明了这一点:

实时演示
void main() {
   List l = [1, 2, 3,4,5,6,7,8,9];
   print('The value of list before replacing ${l}');
   
   l.replaceRange(0,3,[11,23,24]);
   print('The value of list after replacing the items between the range [0-3] is ${l}');
}

它应该产生以下输出

The value of list before replacing [1, 2, 3, 4, 5, 6, 7, 8, 9]
The value of list after replacing the items between the range [0-3] is [11, 23, 24, 4, 5, 6, 7, 8, 9]
dart_programming_lists_basic_operations.htm
广告

© . All rights reserved.