flutter - 是否可以在 dart 中使用 getter 作为函数参数?

标签 flutter dart freezed

我有一个像这样的重复函数:

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,这里numberRecord类的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/

相关文章:

android - 尝试在 VSCode 和 Flutter 中调试时突然出现 Gradle 错误

sqlite - 如何在 Flutter 中获取每月数据 sqflite?

flutter - 卡住和 json_serializable : How to use a custom converter

flutter - 如何处理不同的登录导航流程?

flutter - 当我运行 "Building flutter tool..."时卡住 "flutter doctor"

android - flutter 安装 .apk 版本应用程序卡在黑屏上

flutter - 继承 Widget 和 BLoC 之间的区别?

flutter - 使用 Pageview.builder 在 Flutter 中分页

flutter - 常量创建的参数必须是常量表达式,同时使用卡住实现模型