Flutter freezed Default computed value

Viewed 264

I need to have a computed value in a freezed class

  factory MyState({
    ///....
    @Default(UniqueKey()) UniqueKey key,
  }) = _MyState;

This is not allowed. How can I go around this. Setting it in inital() is out of the question.

Thank you

1 Answers

While I don't know if this is idiomatic, the following snippet should provide you with a solution:

factory MyState._internal({
  UniqueKey key,
}) = _MyState;

factory MyState({
  UniqueKey? key,
}) {
  return MyState._internal(key: key ?? UniqueKey());
}
Related