Home > database >  what is operator == method in flutter?
what is operator == method in flutter?

Time:12-02

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.

CodePudding user response:

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.

CodePudding user response:

The keyword operator is used in Dart Extension Methods. For more info about extension methods, and their uses, see here: https://youtu.be/D3j0OSfT9ZI.

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 String, that will be the same with a similar object.

  • Related