gpt4 book ai didi

dart - Dart流-跳过但不跳过事件

转载 作者:行者123 更新时间:2023-12-03 04:47:42 26 4
gpt4 key购买 nike

似乎不像skipWhile正在执行任何操作...还是我理解这个错误?

下面的代码...我期望skipWhile删除两个条目!

Dart版本(来自Flutter Doctor):Dart version 2.9.0 (build 2.9.0-10.0.dev 7706afbcf5)

import 'package:flutter_test/flutter_test.dart';

class Car {
final String name;
final bool active;
final int wheels;

Car({this.name, this.active=true, this.wheels=4});
}

void main() {
test("Check skipWhile", () {
List dataSet = [
Car(name: "Thunder", active: false),
Car(name: "Lightening", active: false),
Car(name: "Dinky", wheels: 3),
Car(name: "Camry"),
Car(name: "Outback"),
];

List activeCars = dataSet.skipWhile((car) => car.active).toList();

expect(activeCars.length, 3);
});
}

最佳答案

如果您阅读 skipWhile 的文档,则会看到:

Returns an Iterable that skips leading elements while test is satisfied.



因此,它只是跳过了主要元素,而不是所有元素。

您正确想要的是 where ,它可以:

Returns a new lazy Iterable with all elements that satisfy the predicate test.



因此,如果在您的示例中将 skipWhile更改为 where,则现在的长度为3:
class Car {
final String name;
final bool active;
final int wheels;

Car({this.name, this.active = true, this.wheels = 4});
}

void main() {
final dataSet = [
Car(name: "Thunder", active: false),
Car(name: "Lightening", active: false),
Car(name: "Dinky", wheels: 3),
Car(name: "Camry"),
Car(name: "Outback"),
];

final activeCars = dataSet.where((car) => car.active).toList();

print(activeCars.length); // 3
}

关于dart - Dart流-跳过但不跳过事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61993680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com