Home > Net >  Use of "get Stringify" and "get props" in dart
Use of "get Stringify" and "get props" in dart

Time:05-12

import 'package:equatable/equatable.dart';

class Point extends Equatable {
  const Point(this.x, this.y);
  final int x;
  final int y;

  @override
  List<Object?> get props => [x, y];

  @override
  bool? get stringify => true;

  Point operator  (Point other) {
    return Point(x   other.x, y   other.y);
  }

  Point operator *(int other) {
    return Point(x * other, y * other);
  }
}

void main() {
  print(Point(1, 1) == Point(1, 1));

  print(Point(2, 1));
}

                                                                                     

What does "Stringify" and "get props" does is this block of code? It is given that "If set to true, the [toString] method will be overridden to output this instance's [props]." regarding the use of Stringify. What does it mean by "this instance's [props]."?

CodePudding user response:

The purpose of the equatable package are described as:

A Dart package that helps to implement value based equality without needing to explicitly override == and hashCode.

To do achieve this goal, we can make our classes extend from Equatable (or use the EquatableMixin with with) which will then come with the implementation for == and hashCode.

But Equatable can't inspect the object at runtime to figure out what fields your class have defined. And Equatable does also not require a precompile step. Also, you might not want to compare all fields of your objects when determine that two objects are equal.

So the way Equatable understands what fields you want to have compared, is by using a props getter that you must define if using Equatable. This getter must then return a list of objects that should be compared when determining the equality of two objects.

Behind the scene, Equatable will call this probs getter whenever something calls == or hashCode on your object.

The purpose of the stringify getter is then to tell Equatable if it, besides == and hashCode, should also implement a toString() for your class. By default, the toString() method, in Dart, will just tell you the type of object you have like Instance of 'Point'.

If stringify returns true, then Equatable will use the returned value from probs to contruct its own toString() method which lists the value of each element in probs (which correspond to each field of your class).

It is just an extra optional service if you already want your toString() to list the value of each field of your class.

  • Related