How do I update a Map with BLoC and equatable?

Viewed 18

I am still a beginner with BLoC architecture. So far the UI updates when using int, bool, and other basic data types. But when it comes to Maps it really confuses me. My code basically looks like this:

my state

enum TalentStatus { initial, loading, loaded, error }

class TalentState extends Equatable {
  const TalentState({
    required this.talentStatus,
    this.selectedService = const {},
    required this.talents,
    this.test = 0,
  });

  final TalentStatus talentStatus;
  final Talents talents;
  final Map<String, Service> selectedService;
  final int test;

  TalentState copyWith({
    TalentStatus? talentStatus,
    Talents? talents,
    Map<String, Service>? selectedService,
    int? test,
  }) =>
      TalentState(
        selectedService: selectedService ?? this.selectedService,
        talentStatus: talentStatus ?? this.talentStatus,
        talents: talents ?? this.talents,
        test: test ?? this.test,
      );

  @override
  List<Object> get props => [talentStatus, talents, selectedService, test];
}

my event

abstract class TalentEvent extends Equatable {
  const TalentEvent();

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

class TalentStarted extends TalentEvent {}

class TalentSelectService extends TalentEvent {
  const TalentSelectService(
    this.service,
    this.talentName,
  );

  final Service service;
  final String talentName;
}

and my bloc

class TalentBloc extends Bloc<TalentEvent, TalentState> {
  TalentBloc(this._talentRepository)
      : super(TalentState(
            talentStatus: TalentStatus.initial, talents: Talents())) {
    on<TalentSelectService>(_selectService);
  }

  final TalentRepository _talentRepository;

  Future<void> _selectService(
    TalentSelectService event,
    Emitter<TalentState> emit,
  ) async {
    state.selectedService[event.talentName] = event.service;
    final selectedService = Map<String, Service>.of(state.selectedService);

    emit(
      state.copyWith(
        selectedService: selectedService,
      ),
    );
  }
}

whenever an event TalentSelectService is called BlocBuilder doesn't trigger, what's wrong with my code?

1 Answers

Your Service object must be comparable. One suggestion is that it extends Equatable. Either way it have to implement (override) the == operator and hashCode

The reason your BlocBuilder doesn't trigger is (probably) that it doesn't recognize that there has been a change in the Map.

Related