2

我收集了一些菜肴。

我想检索在他的菜单中有特定菜肴列表的所有餐厅。

我的数据模型是这样的:

restaurant---->rest1
      |         |-->menu
      |                   | --> 1: true
      |                   | --> 2: true
      |                   | --> 3: true
      |--->rest2
      |         |-->menu
      |                   | --> 1: true
      |                   | --> 2: true
      |                   | --> 3: true
      |--->rest3
      |         |-->menu
      |                   | --> 1: true


我的菜肴清单是 [1,2],因此我只想检索rest1并且rest2

我的代码是这样的:

Future loadRestaurantsByDishes({List idPiatti})async{


    idPiatti.forEach((element) async {
      dynamic result2 = await _restaurantServices.getRestaurantOfDish(id_piatto: element["dishId"].toString());
      rest.add( result2);
    });
    if(rest.length >0){
      List<RestaurantModel> mom = [];
      List<RestaurantModel> temp = [];
      rest.forEach((item) {
        if(mom.isEmpty){
          mom.addAll(item);
        }else{
          temp.addAll(item);
          mom.removeWhere((element) => !temp.contains(element));
          temp = [];
        }

      });
      notifyListeners();
    }
  }


Future<List<RestaurantModel>> getRestaurantOfDish({String id_piatto}) async =>
      _firestore.collection(collection).where("menu."+id_piatto, isEqualTo: true).get().then((result) {
        List<RestaurantModel> restaurants = [];
        for (DocumentSnapshot restaurant in result.docs) {
          restaurants.add(RestaurantModel.fromSnapshot(restaurant));
        }
        return restaurants;
      });


我的想法是检索所有制作特定菜肴的餐厅,然后检索这些列表之间的公共元素,以检索唯一拥有所有这些元素的餐厅蚂蚁。

问题是mom在第一个语句中等于 item,但是当我运行它时mom.removeWhere((element) => !temp.contains(element));它返回一个空列表。

我哪里错了?

谢谢

4

1 回答 1

2

在比较您创建的自定义类的对象时,您必须覆盖==覆盖和hashCode函数。

您可以使用下面解释的方法为您自己的自定义类,以便使用==运算符比较其中两个。

尝试在DartPad中运行它。

class Cat {
  String id;
  Cat(this.id);

  @override
  bool operator == (Object other){
    return other is Cat && id == other.id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() => '{ id: $id }';

}

void main() {
  List l1 = [Cat('1'), Cat('2')];
  List l2 = [Cat('2'), Cat('3')];
  List l3 = [Cat('2'), Cat('4')];

  l1.removeWhere((item) => !l2.contains(item));
  l1.removeWhere((item) => !l3.contains(item));
  print(l1);
}
于 2021-05-18T08:23:15.790 回答