How to implement shouldRepaint when the object being compared is a List?

74 views Asked by At

Lets say in Flutter we have a Custom Painter like this that takes a List as an argument:

class StackPainter02 extends CustomPainter {
  final List<double> brightnessValues;
  late final int numberOfBulbs;

  StackPainter02(
      {required this.brightnessValues}) {

    numberOfBulbs = brightnessValues.length;

  }

  @override
  void paint(Canvas canvas, Size size) {

    // ...

  }

  @override
  bool shouldRepaint(covariant StackPainter02 oldDelegate) {
    return (oldDelegate.brightnessValues != brightnessValues); // ??? does not seem to work
    //return true;
  }
}

In the shouldRepaint(), I suspect the reason this isn't working has to do with how comparing lists works in Dart and that comparing two lists will always return false even if their contents are the same.

... and that we have to use some type of special comparison like in this answer?

However, I don't want the performance hit of having to iterate through an entire list like that to compare every value.

Assuming it could ever be the same object in memory, is there some way to compare the "two" lists by asking "is it the same actual object in memory"?

1

There are 1 answers

0
Richard Heap On BEST ANSWER

That's exactly what == does. Take this example:

  final l1 = <int>[1, 2, 3];
  final l2 = <int>[1, 2, 3];
  final l3 = l1;
  print(l1 == l2);  // prints false
  print(l1 == l3);  // prints true

  l1[2] = 4;
  print(l3); // prints [1, 2, 4];

Two different lists, albeit with the same contents, are not ==, but can be compared by exhaustively checking their contents.

But in this example l3 is the same list as l1 - so == is true. (Note how modifying l1 also modifies l3.