我有一个像这样的重复函数:
repetitiveFunction(Type type) async* {
yield* _recordCollectionQuery(type)
.snapshots()
.map((snapshot) {
final List<Record> records = snapshot.docs
.map((doc) => RecordDto.fromFirestore(doc).toDomain())
.toList();
// Here instead of using "record1.number", I want to use parameter like "record1.param"
records.sort((record1, record2) => record2.number.compareTo(record1.number));
return records;
});
}
这里的Record
类是卡住
数据类。我必须多次使用这个函数,只是改变record.number
,这里number
是Record
类的getter。那么我可以使用这个getter作为函数参数吗?
最佳答案
您不能直接将 getter/setter 用作函数,因为 getter/setter 的目的是与成员变量无法区分。
您可以轻松地将 getters 包装在匿名函数中(例如 (record) => record.number)
,然后您可以为不同的 getters 提供不同的匿名函数:
这是一个具体的例子:
Stream<List<Record>> repetitiveFunction(
List<Record> records,
Comparable Function(Record) getComparableProperty,
) async* {
yield* _recordCollectionQuery(type).snapshots().map((snapshot) {
final List<Record> records = snapshot.docs
.map((doc) => RecordDto.fromFirestore(doc).toDomain())
.toList();
records.sort((record1, record2) => getComparableProperty(record2)
.compareTo(getComparableProperty(record1)));
return records;
});
}
关于flutter - 是否可以在 dart 中使用 getter 作为函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66937976/