Access Shared vs. Specific Properties in Union Types
masterWhen using Union types, you can only directly access properties that are shared across all constructors. Properties unique to a specific constructor cannot be accessed directly on the base class instance.
Shared Properties
If all constructors define a property with the same name and type, it is accessible via the base class.
@freezed
sealed class Example with _$Example {
const factory Example.person(String name, int age) = Person;
const factory Example.city(String name, int population) = City;
}
var example = Example.person('Remi', 24);
print(example.name); // Works: 'Remi'Specific Properties
To access properties that are not shared (like age in Person), you must use pattern matching (Dart 3 switch or Freezed's legacy when/map methods).
Using Dart 3 Pattern Matching (Recommended)
switch (example) {
case Person(:final name, :final age): print('Person $name, age $age');
case City(:final name, :final population): print('City $name, pop $population');
}