【问题标题】:What is Left and Right in the Either module in Flutter?Flutter 中的 Either 模块中的 Left 和 Right 是什么?
【发布时间】:2021-11-12 01:49:01
【问题描述】:

我正在查看一些看起来像这样的 Flutter 代码:

    try {
      return Right(_doSomethingAndReturnSingleValue());
    } on CustomException {
      return Left(CustomException());
    }

LeftRight 来自核心 either.dart 包,这是代码:

class Left<L, R> extends Either<L, R> {
  final L _l;
  const Left(this._l);
  L get value => _l;
  @override B fold<B>(B ifLeft(L l), B ifRight(R r)) => ifLeft(_l);
  @override bool operator ==(other) => other is Left && other._l == _l;
  @override int get hashCode => _l.hashCode;
}

class Right<L, R> extends Either<L, R> {
  final R _r;
  const Right(this._r);
  R get value => _r;
  @override B fold<B>(B ifLeft(L l), B ifRight(R r)) => ifRight(_r);
  @override bool operator ==(other) => other is Right && other._r == _r;
  @override int get hashCode => _r.hashCode;
}

我真的很难理解这个逻辑应该做什么。

谁能帮我理解 Left()Right() 在 Dart 中的用途?

【问题讨论】:

标签: flutter dart either


【解决方案1】:

Left 和 Right 是从同一个父类继承的两个泛型类,它们的作用几乎相同。主要区别在于 fold 方法的实现。左类调用 ifLeft 回调,右类调用 ifRight 回调。

例如:

Either<CustomException, String> getSomething() {
   try {
      return Right(_doSomethingAndReturnSingleValue());
   } on CustomException {
      return Left(CustomException());
   }
}

无论发生什么,上述函数都将返回 带有 CustomException 的对象(意味着左)带有字符串的对象(意味着右)

现在如果你使用如下函数:

final eitherData = getSomething();

您将得到一个对象(左或右对象)。您可以在该对象上调用 fold 方法,而不是检查 anyData 是 Left 还是 Right 类型,如下所示:

eitherData.fold<Widget>(
   (err) => Text('Error Happened: $err'), // ifLeft callback
   (data) => Text('Got data: $data'), // ifRight callback
)

正如我之前提到的,根据对象类型,相应的回调将被触发,您可以优雅地处理成功和错误情况,而无需编写任何 if else 语句或类型检查。

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2015-01-26
    • 2014-08-05
    • 1970-01-01
    • 2018-10-09
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多