Flutter如何比较两个Map相等

2021-09-26  本文已影响0人  少缶

Dart提供了mapEquals方法用于比较两个Map是否深度相等,示例代码:

import 'package:flutter/foundation.dart';

void main() {
  Map map1 = {'size': 38, 'color': 'red'};
  Map map2 = {'size': 38, 'color': 'red'};


  if(mapEquals(map1, map2)){
    print('yes');
  }else{
    print('no');
  }
}

下面我们来看一下mapEquals的源代码,一起研究一下方法具体是如何判断深度相等的:

/// Compares two maps for deep equality.
///
/// Returns true if the maps are both null, or if they are both non-null, have
/// the same length, and contain the same keys associated with the same values.
/// Returns false otherwise.
///
/// The term "deep" above refers to the first level of equality: if the elements
/// are maps, lists, sets, or other collections/composite objects, then the
/// values of those elements are not compared element by element unless their
/// equality operators ([Object.==]) do so.
///
/// See also:
///
///  * [setEquals], which does something similar for sets.
///  * [listEquals], which does something similar for lists.
bool mapEquals<T, U>(Map<T, U>? a, Map<T, U>? b) {
  if (a == null)
    return b == null;
  if (b == null || a.length != b.length)
    return false;
  /// Check whether two references are to the same object.
  if (identical(a, b))
    return true;
  for (final T key in a.keys) {
    if (!b.containsKey(key) || b[key] != a[key]) {
      return false;
    }
  }
  return true;
}

mapEquals的源代码相对比较简单,通过三个if语句和一个for循环语句可以看出,仅有三种情况会返回True:

需要注意的是如果key对应的valuemaps, lists, sets,或其他集合/复合对象,则这些元素的值不会逐个深入进行比较,而是通过相等运算符==来比较。

上一篇 下一篇

猜你喜欢

热点阅读