Bloc library not updating state when the previous state does not equal next state

Issue

I am using a simple Bloc to manage state in my quiz app, the problem is, when I select an option, I want continue to next question button to be displayed, that for I am using a BlocBuilder in the widget.

I reckon the problem is in references in the code below. I suspect that after updating the state with the copyWith method, nothing happens and the state stays the same.

Any suggestions are much appreciated, thanks.

on<SelectOption>((SelectOption event, emit) {
  log.i('Selecting Option');

  var ini = state;

  print('initial length'); // prints 0
  print(state.questions[state.questionToDisplayIndex].selectedOptions.length);

  List<Question> transformedQuestions = [...state.questions];
  transformedQuestions[state.questionToDisplayIndex].addToSelectedOptions(event.option);

  print('questions');
  print(state.questions == transformedQuestions);//prints false

  emit(
    state.copyWith(
      questions: [...transformedQuestions]
    )
  );

  print('final length');
  print(state.questions[state.questionToDisplayIndex].selectedOptions.length); //prints1 

  print('compar');
  print(state.questions == ini.questions); // prints true

});

state class:

part of 'question_section_bloc.dart';
@freezed
class QuestionSectionState extends Equatable with 
 _$QuestionSectionState{
  const factory QuestionSectionState({
 required int questionToDisplayIndex,
 required List<Question> questions,
 required List<Question> answeredQuestions
}) = _QuestionSectionState;

factory QuestionSectionState.initial() => const 
 QuestionSectionState(
  questionToDisplayIndex: 0,
  questions: [],
  answeredQuestions: []
);

@override
List<Object?> get props => [questionToDisplayIndex, questions, 
answeredQuestions];

// this is required to implement equatable
const QuestionSectionState._();
}

Solution

Try including identityHashCode on props

  @override
  List<Object?> get props => [
        questionToDisplayIndex,
        questions,
        answeredQuestions,
        identityHashCode(this) //this
      ];

Answered By – Yeasin Sheikh

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *