freezed
freezed copied to clipboard
Initialize private fields for late usage
Issue
I'm trying to provide default values with @late
, and I often end up with this :
factory Example({
@JsonKey(name: 'timestamp') DateTime optionalTimestamp,
}) = _Example;
@late
DateTime get timestamp =>
optionalTimestamp ??
DateTime.now().add(Duration(days: -30));
But having optional<Field>
isn't great.
Solution
I would like to be able to initialize private fields to be used by late properties.
A Private
annotation may solve the issue for example :
factory Example({
@Private() DateTime timestamp,
// equivalent to `@Private('_timestamp') DateTime timestamp,` here
}) = _Example;
@late
DateTime get timestamp =>
_timestamp ??
DateTime.now().add(Duration(days: -30));
Is there an update on this issue yet?
No nothing yet
Looking for the same feature!
Is there any update?
Looking for the same issue. Any update? Or I can help somehow?
Any update on this? This feature is still needed by some people. If you don't plan to work on it @rrousselGit what do you think the effort would be and where would be the right entry point in the code to implement this feature?
I don't like the idea. It's trying to solve the proposal of dynamic variable initialization in an underhanded way.
I'd prefer a proposal that tackles that issue directly instead. Like maybe a variant to @Default
for dynamic initialization.
I admittedly also would prefer not solving this for now, considering metaprogramming is on its way.
Metaprogramming would likely involve a significant revamp of Freezed, and any new feature now means more work for me when it's released; or having to remove the feature later.
Considering metaprogramming would also likely enable better solutions to this problem, I'd prefer just waiting for it to be released.
For example with metaprogramming we could be able to do:
@freezed
class Example {
Example({int? a});
}
(instead of using factory
)
Which therefore enables doing:
@freezed
class Example {
Example({int? a}): a = a ?? Random.nextInt();
}