'How to copyWith list items on Blco[Flutter]

I want to change List<Map<String, dynamic>> list on Bloc.

Below is my sample bloc code.

Please teach me how to use copyWith correctly.

[Sample Code]

class StateA extends Equatable {
  List<Map<String, dynamic>> listMap;

  StateA({ required this.listMap});

  StateA copyWith(
   {List<Map<String, dynamic>>? listMap,}) {
  return StateA(
    listMap: listMap ?? this.listMap);
}
}

class CubitA extends Cubit<StateA> {
 CubitA() : super(StateA(listMap: []));

 void testCopy() {
  emit(state.copyWith(listMap: [{"test_key": "test_value"}]));
  print(state.listMap); // => []
}

(I'm not good at English, sorry)



Solution 1:[1]

you have to create a object for your StateA and then access the copywith through that object.

Solution 2:[2]

So the copy with function in this context should be used to add maps to the list of maps.

StateA copyWith(
   {List<Map<String, dynamic>> newListMap}) {
  return StateA(
    listMap: [listMap, newListMap]);
}

This function will allow you to add items to the current state's listMap and emit a new state.

Suggestions:

  1. Don't make the the copyWith function's parameter as an optional parameter (remove the question mark).

  2. You'll have to override the props function for equatable to work. Refer to the docs or some video to get an understanding of that.

  3. If you're very new to flutter ignore this.. but I'd recommend going through the freezed class videos to make bloc state. I'll link a video below. It generates all the boilerplate code for copyWith and equality operations. https://youtu.be/ApvMmTrBaFI

Solution 3:[3]

I solve it to add object?.

The code is below.

class StateA extends Equatable {
  List<Map<String, dynamic>> listMap;

  StateA({ required this.listMap});

  StateA copyWith(
   {List<Map<String, dynamic>>? listMap,}) {
  return StateA(
    listMap: listMap ?? this.listMap);
  };

  // Add below code
  List<Object?> get props => [listMap];
}

class CubitA extends Cubit<StateA> {
 CubitA() : super(StateA(listMap: []));

 void testCopy() {
  emit(state.copyWith(listMap: [{"test_key": "test_value"}]));
  print(state.listMap); // => [{"test_key": "test_value"}]
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sneha G Sneha
Solution 2
Solution 3 ????