flutter 从对象列表中过滤ID

vltsax25  于 2023-03-13  发布在  Flutter
关注(0)|答案(3)|浏览(214)

我需要从对象列表中筛选ID,并将这些ID列表添加到新数组中。请建议一种方法来完成此操作。根据下面的示例,我需要从“_studentDetails”列表中筛选ID,并将这些ID存储在“_idList”数组中。
示例:

List<int> _idList = [];

List<Student> _studentDetails = [];

_studentDetails = [
       Student(id:1 , name:'Peter' , age: 14),
       Student(id:2 , name:'Anne' , age: 20),
];
92vpleto

92vpleto1#

如果只需要id列表,可以使用方法.map

List<int> _idList = [];

List<Student> _studentDetails = [];

_studentDetails = [
       Student(id:1 , name:'Peter' , age: 14),
       Student(id:2 , name:'Anne' , age: 20),
];

_idList.addAll(
  _studentDetails.map((student) => student.id),
);
yc0p9oo0

yc0p9oo02#

您也可以使用forEach()循环实现此目的
下面的代码:

void main(){
  List<int> _idList = [];

List<Student> _studentDetails = [];

_studentDetails = [
       Student(id:1 , name:'Peter' , age: 14),
       Student(id:2 , name:'Anne' , age: 20),
];
  
  _studentDetails.forEach((element) {
    _idList.add(element.id);
    
  } );
  
  print(_idList);
}

class Student{

  int id;
 String? name;
  int? age;
  
  Student({required this.id, required this.name, required this.age});
}
i2loujxw

i2loujxw3#

您可以使用list.map()方法实现此目的
循环遍历列表项,并为每个项返回其preoperty id的值,然后将所有返回值转换为list:

List<int> _idList = _studentDetails.map((student) => student.id).toList();

相关问题