似乎skipWhile什么都没做..。还是我理解错了?
下面的代码..。我期待skipWhile删除两个条目!
Dart版本(来自颤振医生):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);
});
}发布于 2020-05-25 08:25:34
如果您阅读了skipWhile的文档,您将看到:
返回一个Iterable,它在满足测试时跳过前导元素。
所以它只是跳过了主导元素,而不是所有元素。
相反,您需要的是where,它可以:
返回一个新的惰性Iterable,它包含满足谓词测试的所有元素。
因此,如果我在示例中将您的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
}https://stackoverflow.com/questions/61993680
复制相似问题