freezed icon indicating copy to clipboard operation
freezed copied to clipboard

Initialize private fields for late usage

Open aloisdeniel opened this issue 3 years ago • 7 comments

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)); 

aloisdeniel avatar Nov 09 '20 09:11 aloisdeniel

Is there an update on this issue yet?

thedejifab avatar Feb 14 '21 01:02 thedejifab

No nothing yet

rrousselGit avatar Feb 14 '21 02:02 rrousselGit

Looking for the same feature!

Is there any update?

elias8 avatar May 25 '21 22:05 elias8

Looking for the same issue. Any update? Or I can help somehow?

rishabhdeepsingh avatar Aug 19 '21 10:08 rishabhdeepsingh

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?

guenth39 avatar Nov 15 '22 10:11 guenth39

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.

rrousselGit avatar Nov 15 '22 11:11 rrousselGit

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();
}

rrousselGit avatar Nov 15 '22 12:11 rrousselGit