You need to enable JavaScript to run this app. Flutter空安全下如何将dartz包Either的右侧值转换为指定泛型类型
优惠活动
大模型
产品
解决方案
定价
更多

Flutter空安全下如何将dartz包Either的右侧值转换为指定泛型类型

问题原因

空安全升级后Dart泛型隐式推导规则收紧,你现有扩展的泛型定义中,类型参数U依附于T extends Either<Object, U>的约束,Dart类型推导器无法反向从Either的约束中提取出U的实际类型,最终U就退化为dynamic。

解决方案

优先选择修改扩展的泛型定义,直接针对Task<Either<Object, U>>类型做扩展,简化泛型推导逻辑:

extension TaskX<U> on Task<Either<Object, U>> {
  Task<Either<Failure, U>> mapLeftToFailure() {
    return this.map(
      (either) => either.leftMap((obj) {
        try {
          return obj as Failure;
        } catch (e) {
          throw obj;
        }
      }),
    );
  }
}

修改完成后无需调整业务代码,Dart可以自动从attempt()返回的Task<Either<Object, Product>>中推导出U为Product,mapLeftToFailure的返回值会自动匹配Task<Either<Failure, Product>>类型,符合你的业务预期。

如果不想修改扩展定义,也可以在调用时显式指定泛型参数:

await Task(
      () => _recipesService.getProduct(),
    )
        .attempt()
        .mapLeftToFailure<Either<Failure, Product>, Product>()
        .run()
        .then(
          (product) => _setProduct(product),
        );

内容的提问来源于stack exchange,提问作者Manu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 21:15:04