未为类型“x”定义运算符“+” - Flutter

时间:2021-07-25 06:17:58

标签: flutter dart bloc

我正在尝试为我的关注者添加 +1,但我不能,因为我遇到了错误。我已经评论了下面的错误,我正在通过 reso 编码器实现颤振 DDD。

@immutable
abstract class ValueObject<T> {
  const ValueObject();
  Either<ValueFailure<T>, T> get value;
  

  /// throws [UnexpextedValueError] containing the [ValueFailure]
  T getOrCrash() {
    // id = identity - same as writing (right) => right
    return value.fold((f) => throw UnexpectedValueError(f), id);
  }

  Either<ValueFailure<dynamic>, Unit> get failureOrUnit {
    return value.fold(
      (l) => left(l),
      (r) => right(unit),
    );
  }

  bool isValid() => value.isRight();

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;

    return other is ValueObject<T> && other.value == value;
  }

  @override
  int get hashCode => value.hashCode;

  @override
  String toString() => 'Value($value)';
}
class Followers extends ValueObject<int> {
  @override
  final Either<ValueFailure<int>, int> value;
  factory Followers(int input) {
    return Followers._(validateintegerNotNegative(input));
  }
  const Followers._(this.value);
}
final updatedUser =
            state.user.copyWith(followers: state.user.followers + 1); 

错误:

<块引用>

"message": "没有为类型 'Followers' 定义运算符 '+'。\n尝试定义运算符 '+'。"

1 个答案:

答案 0 :(得分:0)

TL;DR:定义operator +方法

这是改变的类:

class Followers extends ValueObject<int> {
  @override
  final Either<ValueFailure<int>, int> value;
  factory Followers(int input) {
    return Followers._(validateintegerNotNegative(input));
  }

  Followers operator +(int val) {
    return Followers(value.getOrElse(() => null) + val);
  }

  Followers operator -(int val) {
    return Followers(value.getOrElse(() => null) + val);
  }

  @override
  String toString() {
    return value.getOrElse(() => null).toString();
  }
  const Followers._(this.value);
}

我如何使用它进行测试:

Followers f = Followers(0);         // 0
f = Followers(f.getOrCrash() + 1);  // 1
f = Followers(f.getOrCrash() + 10); // 11
f = Followers(f.getOrCrash() - 2);  // 9