Home > Software design >  How to copyWith list items on Blco[Flutter]
How to copyWith list items on Blco[Flutter]

Time:03-29

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)

CodePudding user response:

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>> listMap}) {
  return StateA(
    listMap: [state.listMap, listMap]);
}

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

CodePudding user response:

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

  • Related