本教程通过实例向您展示了从列表中移除元素的多种方法,并以dart为例进行了说明。
Dart列表移除元素的例子
列表类内置的方法:
-
删除
-
使用remove方法
List 类有一个 方法,可以用给定的输入元素移除元素。 它减少了列表的大小。remove
bool remove(Object? value)
它接受一个元素。
它删除一个元素,如果该元素被从列表中删除,则返回真,否则返回假。
下面的程序不检查大小写。 下面是一个例子程序。
void main() {
List wordsList = ['one', 'two', 'three'];
print(wordsList.remove("five")); //false
print(wordsList.remove("One")); //false
print(wordsList.remove("one")); //false
print(wordsList);
}
输出
false
false
true
[two, three]
假设在一个列表中匹配了多个元素(重复的),它将从列表中删除第一个匹配的元素。
void main() {
List wordsList = ['one', 'two', 'one','three'];
print(wordsList.remove("one")); //false
print(wordsList);
}
输出
true
[two, one, three]
- 使用removeAt方法
List 类有一个 方法,它可以删除具有给定索引的元素。 它减少了列表的大小。removeAt
dynamic removeAt(int index)
它接受一个有效的索引。
它在索引处删除一个元素,如果该元素被从列表中删除,则返回一个元素。
如果它是一个无效的索引,它会抛出Uncaught Error: RangeError: Value not in the range: 5
无效的索引是一个大于 list.length 的数字。 下面是一个示例程序。
void main() {
List wordsList = ['one', 'two', 'three'];
print(wordsList.removeAt(0)); //false
print(wordsList);
wordsList.removeAt(5); //Uncaught Error: RangeError: Value not in range: 5
print(wordsList);
}
输出
false
false
true
[two, three]
如何从列表中删除一个基于键或属性的对象?
这个例子解释了如何从一个包含条件的对象键的列表中删除一个对象。
在下面的例子中:
-
创建一个包含id、name、salary、joinDate的雇员对象。
-
将雇员对象添加到列表中。
-
列表包含
removeWhere方法,它接受一个函数void removeWhere(bool Function(Employee) test)该函数在每次迭代中都被执行
-
删除id等于21的雇员对象。
employees.removeWhere((element) => element.id == 21);
下面是一个示例程序
class Employee {
final int id;
final String name;
final int salary;
final DateTime joinDate;
Employee(this.id, this.name, this.salary, this.joinDate);
@override
String toString() {
return '{id: ${id}, name: ${name}}';
}
Map<String, dynamic> toJson() =>
{"id": id, "name": name, "salary": salary, "doj": joinDate.toString()};
}
void main() {
final e1 =
Employee(11, 'Erwin', 9000, DateTime.parse("2020-06-21 00:00:00.000"));
final e2 =
Employee(21, 'Andrew', 70000, DateTime.parse("2021-07-23 00:00:00.000"));
final e3 =
Employee(4, 'Mark', 8000, DateTime.parse("2017-08-24 00:00:00.000"));
final e4 =
Employee(12, 'Otroc', 5000, DateTime.parse("2022-12-05 00:00:00.000"));
final List<Employee> employees = [e1, e2, e3, e4];
print(employees); //92000
employees.removeWhere((element) => element.id == 21);
print(employees); //92000
}
输出
[{id: 11, name: Erwin}, {id: 21, name: Andrew}, {id: 4, name: Mark}, {id: 12, name: Otroc}]
[{id: 11, name: Erwin}, {id: 4, name: Mark}, {id: 12, name: Otroc}]
结论
综上所述,学会了在flutter和dart中根据关键值删除原始值和对象的多种方法,并举例说明