How to cast Right side of Either to generic type in flutter

642 views Asked by At

I have an extension to Task (from the dartz package) which looks like this

extension TaskX<T extends Either<Object, U>, U> on Task<T> {
  Task<Either<Failure, U>> mapLeftToFailure() {
    return this.map(
      // Errors are returned as objects
      (either) => either.leftMap((obj) {
        try {
          // So we cast them into a Failure
          return obj as Failure;
        } catch (e) {
          // If it's an unexpected error (not caught by the service)
          // We simply rethrow it
          throw obj;
        }
      }),
    );
  }
}

The goal of this extension is to return a value of type Either<Failure, U>

This was working fine, until I switch my flutter project to null safety. Now, for some reason, the return type is Either<Failure, dynamic>.

In my code, it looks like so:

await Task(
      () => _recipesService.getProduct(),
    )
        .attempt() // Attempt to run the above code, and catch every exceptions
        .mapLeftToFailure() // this returns Task<Either<Failure, dynamic>>
        .run()
        .then(
          (product) => _setProduct(product), // Here I get an error because I expect a type of Either<Failure, Product>
        );

My question is, how can I cast the Right side of Either to the correct type?

0

There are 0 answers