1

我目前正在关注 resocoders clean 架构,他强烈建议将Equatable用于未来将进行比较的基本数据保存类。问题是我的课看起来像这样:

class Person extends Equatable {
  final String name;
  final List<AlterEgo> alterEgos;

  Person({@required name, @required alterEgos}):super([name, alterEgos]);

  @override
  List<Object> get props => [name, alterEgos];
}

class AlterEgo extends Equatable {
  final String name;
  final String superPower;

  AlterEgo({@required name, @required superPower}):super([name, superPower]);

  @override
  List<Object> get props => [name, superPower];
}

void main(){
Person("Clark", <AlterEgo>[AlterEgo("Superman", "Flying")]) == Person("Clark", <AlterEgo>[AlterEgo("Superman", "Flying")]) //true
}

问题是当我编写构造函数时,IDE 抱怨列表不可比较。对于现在要定义哪些函数/类以获取由原始类型组成的对象列表以与 equatable 一起使用,我有点迷失了。该包的文档似乎也省略了这个用例,只说明 Equatable 仅适用于不可变类型。但是我不介意列表是不可变的。

编辑:完成的例子。现在在手机上,不能马上测试。

4

1 回答 1

3

好的,我的错误一定在其他地方,在正确的 MWE 中使用列表似乎根本不是问题:

import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

class Person extends Equatable {
  final String name;
  final List<AlterEgo> alterEgos;

  Person({@required this.name, @required this.alterEgos});

  @override
  List<Object> get props => [name, alterEgos];
}

class AlterEgo extends Equatable {
  final String name;
  final String superPower;

  AlterEgo({@required this.name, @required this.superPower});

  @override
  List<Object> get props => [name, superPower];
}

void main() {
  print(Person(name: "Clark", alterEgos: <AlterEgo>[
        AlterEgo(name: "Superman", superPower: "Flying"),
        AlterEgo(name: "Spiderman", superPower: "Climbing"),
      ]) ==
      Person(name: "Clark", alterEgos: <AlterEgo>[
        AlterEgo(name: "Superman", superPower: "Flying"),
        AlterEgo(name: "Spiderman", superPower: "Climbing"),
      ]));
  print(Person(name: "Clark", alterEgos: <AlterEgo>[
        AlterEgo(name: "Superman", superPower: "Flying"),
        AlterEgo(name: "Spiderman", superPower: "Climbing"),
      ]) ==
      Person(name: "Clark", alterEgos: <AlterEgo>[
        AlterEgo(name: "Superman", superPower: "Flying"),
      ]));
  print(Person(name: "Clark", alterEgos: <AlterEgo>[
        AlterEgo(name: "Superman", superPower: "Flying"),
        AlterEgo(name: "Spiderman", superPower: "Climbing"),
      ]) ==
      Person(name: "Clark", alterEgos: <AlterEgo>[
        AlterEgo(name: "Superman", superPower: "Flying"),
        AlterEgo(name: "Spiderman", superPower: "Jumping"),
      ]));
}

结果符合预期:

true
false
false
于 2020-08-08T19:51:55.030 回答