简体   繁体   English

是否可以在 dart 中使用 getter 作为 function 参数?

[英]Is it possible to use a getter as function parameter in dart?

I have a repetitive function like this:我有一个重复的 function 像这样:

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;
  });
}

Here Record class is freezed data class.这里Record class 是freezed数据 class。 I have to use this function multiple times just changing record.number , here number is a getter of Record class.我必须多次使用这个 function 只是更改record.number ,这里的numberRecord class 的获取器。 So can I use this getter as a function parameter?那么我可以使用这个 getter 作为 function 参数吗?

You can't directly use getters/setters as functions since the point of getters/setters is to be indistinguishable from member variables.您不能直接将 getter/setter 用作函数,因为 getter/setter 的点与成员变量无法区分。

You instead can easily wrap the getters in anonymous functions (eg (record) => record.number) , and you then can supply different anonymous functions for different getters:相反,您可以轻松地将 getter 包装在匿名函数中(例如(record) => record.number) ,然后您可以为不同的 getter 提供不同的匿名函数:

Here's a concrete example:这是一个具体的例子:

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;
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM