shouldPreserveState static method

bool shouldPreserveState(
  1. Hook<Object?> hook1,
  2. Hook<Object?> hook2
)

The algorithm to determine if a HookState should be reused or disposed.

This compares Hook.keys to see if they contains any difference. A state is preserved when:

  • hook1.keys == hook2.keys (typically if the list is immutable)
  • If there's any difference in the content of Hook.keys, using operator==.

There are exceptions when comparing Hook.keys before using operator==:

  • A state is preserved when one of the Hook.keys is double.nan.
  • A state is NOT preserved when one of the Hook.keys is changed from 0.0 to -0.0.

Implementation

static bool shouldPreserveState(Hook<Object?> hook1, Hook<Object?> hook2) {
  final p1 = hook1.keys;
  final p2 = hook2.keys;

  if (p1 == p2) {
    return true;
  }
  // if one list is null and the other one isn't, or if they have different sizes
  if (p1 == null || p2 == null || p1.length != p2.length) {
    return false;
  }

  final i1 = p1.iterator;
  final i2 = p2.iterator;
  // ignore: literal_only_boolean_expressions, returns will abort the loop
  while (true) {
    if (!i1.moveNext() || !i2.moveNext()) {
      return true;
    }

    final curr1 = i1.current;
    final curr2 = i2.current;

    if (curr1 is num && curr2 is num) {
      // Checks if both are NaN
      if (curr1.isNaN && curr2.isNaN) {
        continue;
      }

      // Checks if one is 0.0 and the other is -0.0
      if (curr1 == 0 && curr2 == 0) {
        if (curr1.isNegative != curr2.isNegative) {
          return false;
        }
        continue;
      }
    }

    if (curr1 != curr2) {
      return false;
    }
  }
}