I’m trying to trigger an update when a list
in my map
changes. Type is Map<String, List<int>>
. Basically one of the integers is changing in the list but not triggering the blocbuilder. Although when I print the state the value is updated. I’m using freezed. From what I understand freezed only provides deep copies for nested @freezed objects but not for Iterables. I’ve seen a few solutions for this kind of problem. For example create a new Map with Map.from
and emit that map. But that doesn’t trigger a rebuild. Any suggestions!
My freezed
state is
onst factory RiskAttitudeState.loaded({
required int customerId,
required RiskAttitudeQuestionsInfo riskAttitude,
required Map<String, List<int>> answerIds,
@Default(FormzStatus.pure) FormzStatus status,
int? finalRisk,
}) = RiskAttitudeLoaded;
And I’m updating an integer in the list type List<int>
in the map answerIds
Here is the bloc
Future _mapAnswerToState(
String id, List<int> answerIds, Emitter<RiskAttitudeState> emit) async {
await state.maybeMap(
loaded: (RiskAttitudeLoaded loaded) async {
if (loaded.answerIds.containsKey(id)) {
loaded.answerIds.update(
id,
(_) => answerIds,
ifAbsent: () {
add(RiskAttitudeEvent.error(Exception('unknown Question ID: $id')));
return answerIds;
},
);
}
emit(loaded.copyWith(answerIds: loaded.answerIds));
},
orElse: () async {},
);
}
For contest if I pass an empty map like this emit(loaded.copyWith(answerIds:{}));
the builder gets triggered.
2
Answers
unfortunality i came accross this problem too. if your algorithm requires change one item of list maybe you can remove this item from your list and then change its properties. after that if you add the item to the list, builder will be triggered..
I tried a small code with cubit and Equatable and it worked. the key note is that you should override props method and add answerIds and other fields if exists to props and all fields must be final.
also notice to use
Map<String, List<int>>.from
to fill the map.so the state class looks like this:
and a simple cubit class for managing events is like below. in
valueChanged
I’m just passingList<int>
.so in UI I call
valueChanged()
method of cubit:and the blocBuilder gets triggered: