I have these sealed classes for the state of a cubit:

part of 'logged_out_nickname_cubit.dart';

@freezed
abstract class LoggedOutNickNameState with _$LoggedOutNickNameState {
  factory LoggedOutNickNameState.initialised(
          LoggedOutNickNameViewModel vm, String nickNameKey, FormGroup form) =
      _Initialised;
  factory LoggedOutNickNameState.submitted(LoggedOutNickNameViewModel vm) =
      _Submitted;
}

Here is the cubit:

import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:vepo/domain/user_registration/use-cases/logged_out_use_cases/get_user_field_from_local_use_case.dart';
import 'package:vepo/presentation/modules/logged_out/logged_out_nickname/logged_out_nick_name_view_model.dart';

part 'logged_out_nickname_state.dart';
part 'logged_out_nickname_cubit.freezed.dart';

class LoggedOutNickNameCubit extends Cubit<LoggedOutNickNameState> {
  LoggedOutNickNameCubit(
      this.vm, this.nickNameKey, this.form, this.getUserFieldFromLocalUseCase)
      : super(LoggedOutNickNameState.initialised(vm, nickNameKey, form)) {
    form.control(nickNameKey).value =
        getUserFieldFromLocalUseCase.invoke(nickNameKey);

    form.markAsDirty();
  }

  void submitPressed() => emit(LoggedOutNickNameState.submitted(vm));
  void initialise() =>
      emit(LoggedOutNickNameState.initialised(vm, nickNameKey, form));

  final LoggedOutNickNameViewModel vm;
  final String nickNameKey;
  final FormGroup form;
  final GetUserFieldFromLocalUseCase getUserFieldFromLocalUseCase;
}

The issue is that within the view, I try to access loggedOutNicknameCubit.state.form and since the form does not exist on one of the sealed classes, it is not recognised as being on the bloc state, and cannot be used in my view:

The getter 'form' isn't defined for the type 'LoggedOutNickNameState'

The fix is to add the field to all sealed classes that don't use it as nullable like so:

factory LoggedOutNickNameState.submitted(LoggedOutNickNameViewModel vm,
      {@nullable @Default(null) FormGroup form}) = _Submitted;

Is there a way to silence the error that doesn't involve adding the field as null to the sealed class that doesn't need it?

1

There are 1 answers

0
arunized On

You can use cast to get those variables

(loggedOutNicknameCubit.state as _Initialised).form