How can I use variable of CubitState inside Cubit? Flutter/Bloc

Issue

so I don’t have any idea how to take argument from mine Cubit state which is AnswerPicked in this case, there is a code from states file.

part of 'answer_cubit.dart';

abstract class AnswerState extends Equatable {
  const AnswerState();

  @override
  List<Object> get props => [];
}

class AnswerInitial extends AnswerState {}

class AnswerPicked extends AnswerState {
  final String answer;
  AnswerPicked({
    this.answer,
  });
  String toString() => '{AnswerPicked: $answer}';
}

I want to use it in Cubit function right there:

part 'answer_state.dart';

class AnswerCubit extends Cubit<AnswerState> {
  final ExamScoreCubit scoreCubit;
  AnswerCubit({
    @required this.scoreCubit,
  }) : super(AnswerInitial());

  List<String> userAnswersList = [];

  void pickAnswer(String answer) {
    emit(AnswerInitial());
    emit(AnswerPicked(answer: answer));
  }

  void takeAnswer(String questionAnswer, int type) {
    if(state is AnswerPicked){
      userAnswersList.add(state.answer); // state.answer don't work
      scoreCubit.checkAnswer(AnswerPicked().answer, questionAnswer, type); // AnswerPicked().answer don't work
    }
    emit(AnswerInitial());
  }
}

In void takeAnswer() I don’t want to pass it throw argument inside the widget tree using context. Any ideas how to do it?

Solution

userAnswersList.add((state as AnswerPicked) .answer); 

Answered By – Adnan Alshami

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.