feat: @Initialable Static .initial() function & .isInitial property
Description
It would be really handy if a static initial(), function could be created for every property. This would be in the line of immutable objects and the copy with function.
It would take the 'initial' values of each primary type/class in dart. And if there is a custom type, check if that has the Data Class annotation on it to see if it has a .initial function.
Example:
@Initialable
class TestClass extends Equatable {
final String name;
final DateTime dateOfBirth;
final double? age;
final List<int> chains;
const TestClass({
required this.dateOfBirth,
required this.name,
required this.age,
required this.chains,
});
bool get isInitial => this == TestClass.initial();
factory TestClass.initial() {
return TestClass(
age: null,
chains: List.empty(growable: true),
dateOfBirth: DateTime.fromMillisecondsSinceEpoch(0),
name: '',
);
}
}
This is useful in immutable objects.
Hi @Sten435 👋 Thanks for opening an issue!
This is interesting and I'll definitely consider this. For my understanding, is there an existing library/package that provides something similar? Thanks!
Couldn't you simply declare a static variable named initial with the initial values and to check if the class is still initial do a equals with it? The proposed solution fells overengineered imo. And having only one instance should be also less memory intensive!
Hi @Sten435 👋
Thanks for opening an issue!
This is interesting and I'll definitely consider this. For my understanding, is there an existing library/package that provides something similar? Thanks!
Yea, but for my example i thought it would be easier to scale using annotations and less code geny messy with yet another package.
Couldn't you simply declare a static variable named initial with the initial values and to check if the class is still initial do a equals with it? The proposed solution fells overengineered imo. And having only one instance should be also less memory intensive!
No this does work with inheritance.
You can't override static methods so a macro would fix this.
I've put some thought into this and feel it's a bit out of scope for this package but you're more than welcome to write our own package that uses data_class_macro and adds the new functionality. I took a look at the APIs of other data class implementations and didn't encounter this in any of them (happy to be corrected).
Going to close this for now but if you feel strongly about this being part of @Data() let me know and I'm happy to continue the discussion.