微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Dart中定义Lambda函数的返回类型?

如何解决如何在Dart中定义Lambda函数的返回类型?

我尝试创建带有类型安全参数的存储库。为此,我将函数参数创建为typedef并使用Dartz package,以便能够返回失败或期望的结果。

问题是,如果我想传递typedef类型的参数,则必须创建一个特定的函数

typedef FailOrModel<T> = Future<Either<Failure,T>> Function();

class Repository {

  Future<Either<Failure,T>> _runAfterSync<T>(FailOrModel func) async {
    await synchronize().then(
      (value) => value.fold(
        (failure) {
          log.e('Synchronization error: $failure');
        },(_) {},),);
    return await func();
  }
  
  Future<Either<Failure,Storage>> getStorage(int id) async {
    // Todo: Find out why lambda does not work
    Future<Either<Failure,Storage>> func() async {
      try {
        final model = await localDataSource.getStorage(id);
        return Right(model);
      } on CacheException {
        log.e('Could not load storage with id $id');
        return Left(CacheFailure());
      }
    }

    return await _runAfterSync<Storage>(func);
  }
}

当我直接将相同的函数体作为lambda函数传递时,出现运行时错误

  Future<Either<Failure,Storage>> getStorage(int id) async {
    return await _runAfterSync<Storage>(() async {
      try {
        final model = await localDataSource.getStorage(id);
        return Right(model);
      } on CacheException {
        log.e('Could not load storage with id $id');
        return Left(CacheFailure());
      }
    });
  }

类型'Right '不是类型'FutureOr >'的子类型

这没什么大不了的,但是也许有人可以启发我,如何在这里使用lambda函数,或者如果我使用lambda函数,为什么会出现此错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。