如何在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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...