Flutter Bloc Cubit update Map in State

98 views Asked by At

I have a Map<int,int> inside my State which I want to update at some point. Currently I am updating the map like this:

final updatedMap = Map<int, int>.from(state.skipViewsWithSkipValues);
updatedMap[state.currentViewIndex] = _viewsIfMnp.length;

emit(
  state.copyWith(
    skipViewsWithSkipValues: updatedMap,
  ),
);

And this works, but seems quite dirty. What is the "clean" way to update a map inside a state of a cubit?

1

There are 1 answers

1
Albert221 On BEST ANSWER

IMO this is the right way to do it, if you're discussing the code readability, you may utilize Map.of instead of Map.from, which uses the same key and value types, so no need to pass the generic types. You may also use the cascade operator mixed with the subscript access, like so:

emit(
  state.copyWith(
    skipViewsWithSkipValues: Map.of(state.skipViewsWithSkipValues)
        ..[state.currentViewIndex] = _viewsIfMnp.length,
  ),
);