Skip to main content

Comprehensive Example

This page provides a single, comprehensive example demonstrating all major features of Zorphy. It mirrors the comprehensive_example.dart file.

Basic Definition & Patching

(generatePatch: true)
abstract class $User {
String get name;
int get age;
String? get email;
}

// Usage
final user = User(name: 'Alice', age: 30);
final patched = user.patchWithUser(
patchInput: UserPatch.create()..withName('Bob'),
);

JSON Serialization

(generateJson: true)
abstract class $Product {
String get id;
String get name;
double get price;
bool get inStock;
}

// Serialization
final json = product.toJson();
final product2 = Product.fromJson(json);

Sealed Classes & Polymorphism

(generateJson: true, explicitSubTypes: [$CreditCard, $PayPal])
abstract class $$PaymentMethod {
String get displayName;
}

(generateJson: true)
abstract class $CreditCard implements $$PaymentMethod {
String get cardNumber;
String get expiryDate;
String get displayName => 'Credit Card';
}

Enum Support

enum UserStatus { active, inactive, suspended, pending }

(generateJson: true)
abstract class $Account {
String get username;
UserStatus get status;
DateTime get createdAt;
}

Function-based CopyWith

(generateCopyWithFn: true)
abstract class $Counter {
int get value;
String get label;
}

// Increment using function
final next = counter.copyWithFn(value: (current) => current + 1);

Nested Objects & Patching

()
abstract class $Address {
String get street;
String get city;
}

()
abstract class $PersonWithAddress {
String get name;
$Address get address;
}

// Nested patching
final patched = person.patchWithPersonWithAddress(
patchInput: PersonWithAddressPatch.create()
..withAddressPatch(AddressPatch.create()..withCity('New York')),
);

Self-Referencing Trees

(generateJson: true)
abstract class $CategoryNode {
String get id;
String get name;
List<$CategoryNode>? get children;
$CategoryNode? get parent;
}

Multiple Inheritance

()
abstract class $Timestamped {
DateTime get createdAt;
DateTime? get updatedAt;
}

()
abstract class $Identified {
String get id;
}

()
abstract class $Post implements $Timestamped, $Identified {
String get title;
String get content;
}

CompareTo & Diffs

(generateCompareTo: true, generateJson: true)
abstract class $Document {
String get title;
int get version;
}

// Get structural difference
final diff = doc1.compareToDocument(doc2);
// Result: {'version': 2}

Generic Classes

(generateJson: false)
abstract class $Result<T> {
bool get success;
T? get data;
String? get errorMessage;
}

Explicit Subtypes & changeTo

(explicitSubTypes: [$Circle, $Rectangle])
abstract class $$Shape {
String get name;
}

// Convert between subtypes
final rect = circle.changeToRectangle(width: 10.0, height: 15.0);

Constants & Defaults

()
abstract class $Color {
int get red;
int get green;
int get blue;
const $Color();
}

()
abstract class $StartupOptions {
const $StartupOptions();
Duration? get timeout => Duration(seconds: 5);
}