Home > database >  In DART, Is overriding the "==" and comparing both ojects' fields the only way to kno
In DART, Is overriding the "==" and comparing both ojects' fields the only way to kno

Time:09-16

Does dart have a built-in way that one can compare two objects based on their fields values without overriding "==" in the class.

I have a class with 20 fields and I want two objects of that class to be equal only when values in all fields are the same for both objects.

class Items {
  final String? field1;
  final String? field2;
  final String? field3;
  //...................
  final String? field20;

  Items({
    this.field1,
    this.field2,
    this.field3,
    this.field20,
  });

  bool operator ==(Items other) {
    return (field1 == other.field1 &&
        field2 == other.field2 &&
        field3 == other.field3 &&
        field20 == other.field20);
  }
}

Is this the only way to accomplish that in dart? What if I have 100 fields? How can I avoid all these comparisons?

CodePudding user response:

If your equal method is rather simple, as suggested by your example, you use a package like equatable which is designed to make it simple for creating data classes with easy hashCode and ==:

By using equatable, you just need to tell equatable how it can fetch your properties.

import 'package:equatable/equatable.dart';

class Items extends Equatable {
  final String? field1;
  final String? field2;
  final String? field3;
  //...................
  final String? field20;

  Items({
    this.field1,
    this.field2,
    this.field3,
    this.field20,
  });

  @override
  List<Object?> get props => [
        field1,
        field2,
        field3,
        //...................
        field20,
      ];
}

It can even make a toString() method for you if you add this to your class:

  @override
  bool? get stringify => true;
void main() {
  print(Items(field1: 'hello', field2: 'world'));
  // Items(hello, world, null, null)
}
  •  Tags:  
  • dart
  • Related