基于Flutter已知:MyModelint count; List modelList; 过滤出modelList中不为null的count并转生新的Listint
你可以使用where方法和map方法来过滤和转换列表。以下是一个例子:
class MyModel {
int? count;
MyModel(this.count);
}
void main() {
List<MyModel> modelList = [
MyModel(1),
MyModel(null),
MyModel(3),
MyModel(null),
MyModel(5),
];
List<int> filteredCountList = modelList
.where((model) => model.count != null) // 过滤出count不为null的元素
.map((model) => model.count!) // 转换为int类型
.toList(); // 转换为List<int>
print(filteredCountList); // 输出:[1, 3, 5]
}
在上面的例子中,我们使用where方法过滤出count不为null的元素,然后使用map方法将这些元素转换为int类型,并最终通过toList方法将结果转换为List<int>类型
原文地址: https://www.cveoy.top/t/topic/iRM0 著作权归作者所有。请勿转载和采集!