schultek/dart_mappable

Update companion (patch/dto) generation

Closed this issue · 2 comments

Most projects involve forms and other types of data manipulation that can greatly benefit from a partial copy of the model getting changed. Example:

class Todo {
  Todo({
    required this.title,
    required this.dueDate,
    required this.completed,
  });

  final String title;
  final DateTime dueDate;
  final bool completed;

  Todo patch(TodoPatch patch) {
    return Todo(
      title: patch.title ?? title,
      dueDate: patch.dueDate ?? dueDate,
      completed: patch.completed ?? completed,
    );
  }
}

class TodoPatch {
  TodoPatch({
    this.title,
    this.dueDate,
    this.completed,
  });

  final String? title;
  final DateTime? dueDate;
  final bool? completed;
}

In this simple scenario, you can have a form making changes on TodoPatch and committing this patch in the end (or use it for partially updating data db). To my knowledge, it's not possible right now. Other solutions would be using a delta map or alike, which isn't desirable for in domain mutations. Drift has a similar functionality in the form of Companions.

Although I understand the use-case this is not something I would add to the package, as its not part of the core purpose of the package and would further increase the api surface of it, which I try to keep as small as possible.

There is already the feature to use a delta map as shown here: https://pub.dev/documentation/dart_mappable/latest/topics/Copy-With-topic.html
I know its not ideal as its not type-safe, but atleast it should work.
Additionally I can recommend another package of mine you could use to generate the patch class yourself: super_annotations. Combining both should give you a way to implement this without needing to change dart_mappable.

Was hoping to find a way to automatically generate patch classes. This would be normal classes with all fields nullable, which could be used for updating a server record with toMap() or updating/merging into an existing mappable class. Or combining multiple patch maps into a single class