Avoiding bugs related to state equality and mutability
One last thing that we need to discuss in this chapter is the equality and immutability of data classes, specifically the state. What you need to know about the equality of objects in Dart is that, by default, they’re only equal if they’re actually the same instance. Let’s compare objects in vanilla Dart:
void main() { final o1 = Object(); final o2 = Object(); final o3 = o1; print(o1 == o2); // prints "false" print(o3 == o1); // prints "true" }
Even though o1
and o2
look the same visually, in computer memory, they are two different objects, hence why the ==
operator returns false
by default. We could override that behavior by manually overriding the ==
operator in every data class, but that would be a lot of boilerplate. Instead, many libraries do this for us. The one that we will be using is called Equatable (https://pub.dev...