Search code examples
flutterdartflutter-dependenciesequatable

Why get props using in class on dart?


I used equatable in flutter dart to generate some boilerplate codes. here is a class that generated some boilerplate code using equitable

import 'package:equatable/equatable.dart';

class Task extends Equatable {
  final String title;
  bool? isDone;
  bool? isDeleted;

  Task({
    required this.title,
    this.isDone,
    this.isDeleted,
  }) {
    isDone = isDone ?? false;
    isDeleted = isDeleted ?? false;
  }

  Task copyWith({
    String? title,
    bool? isDone,
    bool? isDeleted,
  }) {
    return Task(
      title: title ?? this.title,
      isDone: isDone ?? this.isDone,
      isDeleted: isDeleted ?? this.isDeleted,
    );
  }

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};

    result.addAll({'title': title});
    if (isDone != null) {
      result.addAll({'isDone': isDone});
    }
    if (isDeleted != null) {
      result.addAll({'isDeleted': isDeleted});
    }

    return result;
  }

  factory Task.fromMap(Map<String, dynamic> map) {
    return Task(
      title: map['title'] ?? '',
      isDone: map['isDone'],
      isDeleted: map['isDeleted'],
    );
  }

  @override
  List<Object?> get props => [
        title,
        isDeleted,
        isDone,
      ];
}

and my question is why is this code and what is this code doing? I read some documents but I didn't find the exact answer. the docs say it is used to compare with another class but why do we need to compare? also, I'm not writing any other class. so which classes are being compared? or is it not used to compare??

 @override
  List<Object?> get props => [
        id,
        title,
        isDeleted,
        isDone,
      ];

what's the purpose of this line? also, why are we using Object class?


Solution

  • This is to specify which property to compare to check if an instance is equal to the other instance of the same class. This is useful because if there is a property we want or do not want to compare we can add or remove it to the returned array.

    In this example, this code compares if the first instance of a Task is equal to the second instance of a Task.

    main() {
        var task1 =  Task(title: 'task 1', isDone: true, isDeleted: true);
        var task2 =  Task(title: 'task 2', isDone: false, isDeleted: false);
        print(task1 == task2); // false
    }
    

    It returns List<Object> because the class Task is extending Equatable, so Task needs to override List<Object?> get props.

    This function compares string and boolean. Keep in mind that string and boolean are both an Object in dart, so if you are comparing only string or only boolean you can return List<String> or List<bool>.