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
@withGetter annotationSometimes 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;