Flutter Freezed – Union type with default data

I would like to have a union type which has default data. Right now I have this:

import 'package:freezed_annotation/freezed_annotation.dart';

part 'form_state.freezed.dart';
part 'form_state.g.dart';

class FormState with _$FormState {
  const factory FormState.add(String? heading) = Add;
  const factory FormState.edit(String? heading) = Edit;
  const factory FormState.view(String? heading) = View;

  factory FormState.fromJson(Map<String, dynamic> json) =>

But the main point of this union class is to have the heading always be "Add" for type FormState.Add, "Edit" for type FormState.Edit and "View" for type FormState.View.

Can I somehow give them that value once, instead of everywhere that i create a new one?

I tried this:

const factory FormState.add(@Default('Add') String? heading) = Add;

But got this error:

[SEVERE] freezed:freezed on lib/src/presentation/pages/manage_vegan_item/common/manage_vegan_item_form_states/form_state/form_state.dart:

@Default cannot be used on non-optional parameters package:vepo/src/presentation/pages/manage_vegan_item/common/manage_vegan_item_form_states/form_state/form_state.dart:8:55 ╷ 8 │ const factory FormState.add(@Default('Add') String? heading) = Add; │ ^^^^^^^ ╵ [WARNING] freezed:freezed on lib/src/application/entities/every_vegan_item_field_entity/every_vegan_item_field_entity.dart: The class EveryVeganItemFieldEntity was declared as abstract, but it is not need anymore. Read here: https://github.com/rrousselGit/freezed/tree/master/packages/freezed#the-abstract-keyword

[INFO] 2.1s elapsed, 1/2 actions completed. [SEVERE] json_serializable:json_serializable on lib/src/application/entities/every_vegan_item_field_entity/every_vegan_item_field_entity.dart:

Could not generate toJson code for formState. To support the type FormState you can:

[INFO] Caching finalized dependency graph... [INFO] Caching finalized dependency graph completed, took 127ms

[SEVERE] Failed after 2.9s

Read more here: https://stackoverflow.com/questions/67944475/flutter-freezed-union-type-with-default-data

Content Attribution

This content was originally published by BeniaminoBaggins at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: