Reading the fields

Accessing a property (field) of a modddel differs depending on whether it's a "member" or a "dependency".

Let's take as an example a Book modddel :

final book = Book(
  id: '#1',
  title: 'The adventures of Dash',
  availabilityService: MyAvailabilityService(),
);

Reading dependency fields

You can access "dependency" field from both the sealed class (Book) and the union-cases.

In our example : Let's suppose Book has a dependency parameter availabilityService that checks whether a book is available.

// Good
final service = book.availabilityService;

// Also good
book.mapOrNull(
  valid: (validBook) { 
    final service = validBook.availabilityService;
    //...
  },
);

Reading member fields

By default, a modddel hides its "member" fields inside its union-cases, so you can only access them after using a pattern matching method (map, mapValidity...).

In our example : Book has two member parameters, id and title.

// ERROR : The getter 'title' isn't defined for the type 'Book'.
final title = book.title;

// Good.
final title = book.mapValidity(
    valid: (validBook) => validBook.title,
    invalid: (invalidBook) => invalidBook.title);

As you can see, you must use pattern matching to access the members of the modddel. This is so that you address all cases, and failures never go unnoticed by you the developer.

The @withGetter annotation

Sometimes you may want to have a direct getter for a member parameter. For this, you can use the @withGetter annotation.

For example, let's say you want to have a direct getter for the id member parameter. First, annotate it with @withGetter:

factory Book({
  @withGetter required String id,
  required String title, 
  required MyAvailabilityService availabilityService,
})

Now you can directly access the id field :

// Allowed.
final id = book.id;

// Error.
final title = book.title;

It is advised to use @withGetter sparingly, because it allows direct access to a member parameter, no matter if the modddel is valid or not. This can defeat the purpose of using a modddel, since you will be able to manipulate data that can be either valid or invalid in one place.

However, there are legitimate use cases where it is very useful. For example, if a member parameter is unrelated to the validity of the modddel (like in the case of the id field in our Book example), using @withGetter is a good choice as it makes it easily accessible.