Creating an IterableEntity / Iterable2Entity

Steps to create an IterableEntity / Iterable2Entity

Declare your class this way :

/// ListEntity example
///
/// This will hold a list of [Todo]s
class TodoList extends ListEntity<InvalidTodoList, ValidTodoList> 
    with _$TodoList {}

/// MapEntity example
///
/// This will hold a map where the keys are [Author]s and values 
/// are [Book]s
class BookMap extends MapEntity<InvalidBookMap, ValidBookMap> 
    with _$BookMap {}

Add the imports and part statements, the @Modddel annotation (don't forget including the contentValidation), and the private empty constructor.

Add the factory constructor. The factory constructor should have only one member parameter, which type should match the type template.

/// ListEntity example
//...
factory TodoList({
  required List<Todo> todos,
}) //...

/// MapEntity example
//...
factory BookMap({
  required Map<Author, Book> booksByAuthors,
}) //...

Create your failure(s) sealed class(es).

You can now run the generator, and then override and implement the "validate" methods. Note that the "validate" method of the contentValidation is automatically generated, and you should never override it (Your IDE's Quick Fix won't override it neither).

When using some Dartz collections (ISetEntity, IMapEntity...), you also need to override the $getOrder method.

Complete Example

// ... Imports & Part statements

@Modddel(
  validationSteps: [
    ValidationStep([
      contentValidation,
      Validation('size', FailureType<TodoListSizeFailure>()),
    ]),
  ],
)
class TodoList extends ListEntity<InvalidTodoList, ValidTodoList>
    with _$TodoList {
  TodoList._();

  factory TodoList({
    required List<Todo> todos,
  }) {
    return _$TodoList._create(
      todos: todos,
    );
  }

  @override
  Option<TodoListSizeFailure> validateSize(todoList) {
    if (todoList.todos.isEmpty) {
      return some(const TodoListSizeFailure.empty());
    }
    return none();
  }
}

@freezed
class TodoListSizeFailure extends EntityFailure with _$TodoListSizeFailure {
  const factory TodoListSizeFailure.empty() = _Empty;
}