【问题标题】:Flutter Comparing 2 lists of objects using map and contains not workingFlutter使用地图比较2个对象列表并包含不起作用
【发布时间】:2019-11-03 00:36:49
【问题描述】:

我有 2 个对象列表,即 newList 和 oldList,如下所示:

新列表:[Object{id: -LhnrmWPWN2X_cWdIAQW, title: , category: abandoned, latitude: -17.8594103, longitude: 30.9615846}, Object{id: -LhnpMHQ3l288W28qoDW, title: , category: potholes, latitude: -17.8593472, longitude: 30.9614917}]

旧列表:[Object{id: -LhnpMHQ3l288W28qoDW, title: , category: potholes, latitude: -17.8593472, longitude: 30.9614917}]

问题是使用以下代码检查 newList 中的所有对象是否都在 oldList 中时使用 contains 不起作用:

newList.where((Object p) => !oldList.contains(p)) .map((Object obj) => print('\n\n\n\ntest \n$obj')) .toList();

事实上,这段代码对于 newList 中对象的两个实例都返回 true。

我希望代码应该只对其中一个对象返回 true。

请帮忙。

【问题讨论】:

    标签: list dictionary flutter contains


    【解决方案1】:

    我想你想检查两个对象是否相等,

    默认情况下,在 Dart 中,== 如果两个对象是同一个实例,则返回 true 包含也是相同的。

    此外,您可以使用equatable 包来比较对象。

    或者像equatable包提供的那样,你可以在没有包的情况下做到这一点,你需要在你的对象和hashCode人员中覆盖==方法。

    class Person {
      final String name;
    
      const Person(this.name);
    
      @override
      bool operator ==(Object other) =>
        identical(this, other) ||
        other is Person &&
        runtimeType == other.runtimeType &&
        name == other.name;
    
      @override
      int get hashCode => name.hashCode;
    }
    

    我会推荐使用equatable

    import 'package:equatable/equatable.dart';
    
    class Person extends Equatable {
      final String name;
    
      Person(this.name) : super([name]);
    }
    

    【讨论】:

      【解决方案2】:

      似乎您正在寻找 oldList 是否不包含代码 sn-p 中的对象。尝试使用此代码。

      newList.where((i) => oldList.contains(i)).map((obj) {
          print('${obj.id}');
          return obj;
        }).toList();
      

      这里有一点snippet 上面代码的工作原理。

      【讨论】:

      • 片段打不开
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2022-06-26
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多