Pannam
Pannam

Reputation: 721

what is operator == method in flutter?

As per the documentation https://api.flutter.dev/flutter/painting/BoxShadow/operator_equals.html has its implementation as follows

@override
bool operator ==(Object other) {
  if (identical(this, other))
    return true;
  if (other.runtimeType != runtimeType)
    return false;
  return other is BoxShadow
      && other.color == color
      && other.offset == offset
      && other.blurRadius == blurRadius
      && other.spreadRadius == spreadRadius;
}

and the hashcode property as follows

@override
int get hashCode => hashValues(color, offset, blurRadius, spreadRadius);

What does this actually do? and where is it useful? What is the purpose of opeartor, runtimeType, and hasCode etc in the code? Would be great if you could provide some examples too in simpler terms.

Upvotes: 5

Views: 6220

Answers (2)

JaffaKetchup
JaffaKetchup

Reputation: 1631

The keyword operator specifies a special symbol function. For example, '+' for add, '==' for equal.

In Dart, objects (by default) won't equal each other, even if the properties are the same: because Dart does not automatically perform deep equality (the process of checking each property of an object), and the instances are separate.

The operator is, in this case, overriding the default equality checks, and performing a deep equality check, and checking that the runtime type (for example, String or BoxShadow or Widget) is the same. Any code can be run on equality, but it's bad practise to run anything other than more equality checks. The hash code overriding is necessary when overriding the equality operator, as Dart uses this internally to perform other equality operations - the hash code basically converts an object and it's properties into a unique-ish value, that should be the same with a similar object.

Upvotes: 3

Ruchit
Ruchit

Reputation: 2700

this operator is useful when you need to compare actual values of two objects/classses, because flutter by default Compares instances of objects and that case two objects will never be same even their actual values are same,

For Example, ~just run following examples on DartPad.dev

Flutter default case:

void main() {
  Person p1 = Person("StackOverFlow");
  Person p2 = Person("StackOverFlow");

  print("Both Classes are same: ${p1 == p2}"); // <- print 'false'
}

class Person {
  String name;
  Person(this.name);
}

For override Case:

void main() {
  Person p1 = Person("StackOverFlow");
  Person p2 = Person("StackOverFlow");

  print("Both Classes are same: ${p1 == p2}"); // <- print 'true'
}

class Person {
  String name;
  Person(this.name);

  @override
  bool operator ==(Object other) {
    return (other is Person) && other.name == name;
  }
}

and for more details read this article.

Upvotes: 8

Related Questions