isDirty method
Checks if any attributes have been modified since the last sync.
When attributes is provided, checks if those specific attributes are dirty.
- If a single String is provided, checks that one attribute
- If a List<String> is provided, checks if any of those attributes are dirty
When
attributesis null, checks if any attribute is dirty.
Returns false if no original state is tracked (e.g., on new unsaved models).
Example:
final user = await Users.query().where('id', 1).first();
print(user.isDirty()); // false
user.setAttribute('name', 'New Name');
print(user.isDirty()); // true
print(user.isDirty('name')); // true
print(user.isDirty(['name', 'email'])); // true (name is dirty)
print(user.isDirty('email')); // false
Implementation
bool isDirty([Object? attributes]) {
final original = _getOriginalAttributes();
if (original == null) {
return false; // No original state tracked
}
final current = _ensureAttributes();
if (attributes == null) {
// Check if any attribute is dirty
final allKeys = {...original.keys, ...current.keys};
for (final key in allKeys) {
if (original[key] != current[key]) {
return true;
}
}
return false;
}
// Handle both String and List<String>
final List<String> attrsToCheck;
if (attributes is String) {
attrsToCheck = [attributes];
} else if (attributes is List<String>) {
attrsToCheck = attributes;
} else {
throw ArgumentError(
'attributes must be a String or List<String>, got ${attributes.runtimeType}',
);
}
// Check specific attributes
for (final attr in attrsToCheck) {
if (original[attr] != current[attr]) {
return true;
}
}
return false;
}