Home > Back-end >  How to select the desired elements in a list in Dart, and change the data of this element
How to select the desired elements in a list in Dart, and change the data of this element

Time:10-18

I have an array with such data (more data in reality)

          [ 
           {
                 serviceid: "979cf8e6",
                 amount: 1,
                 price: 0,
                 materialsPrice: 100,
                 enable: true,
                 chenge: true
            },
            {
                 serviceid: "979cf812",
                 amount: 1,
                 price: 15.5,
                 materialsPrice: 0,
                 enable: true,
                 chenge: false
            }
         ]

My goal is to change "enable" to the desired status in the selected element of the array. For this I will use a block. That is, if when I click on the event, I transfer (false and "979cf8e6") . Then the required element should be found (service = 979cf8e6). And this element should have enable on false. I tried to start something, but it didn't work. Maybe someone knows how to do it?))

    on<OnChangeStatusListItemClick>((event, emit) async {
      var serviceId = event.serviceId;//(my  serviceId here)
      var paymentStatus = event.status;//(my  new status here)
      var paymentDetails = state.listVariant; //(my  list here)
      PaymentDetailsModel? selected;

      paymentDetails = paymentDetails.map((paymentDetailsOne) {
       paymentDetailsOne.serviceid == serviceId;
        var selectedPaymentDetails = paymentDetailsOne.copyWith(enable: paymentStatus);
        return selectedPaymentDetails;
      }).toList();
      emit(state.copyWith(listVariant: paymentDetails));     
    });

My PaymentDetailsModel model (this model is used in listVariant)

@freezed
class PaymentDetailsModel with _$PaymentDetailsModel {
  @JsonSerializable(fieldRename: FieldRename.none, explicitToJson: true)
  const factory PaymentDetailsModel({
    required String  serviceid,
    required double? price,
    required int?  minmal,
    required int  amount,
    required bool enable,
    required bool chenge,
  }) = _PaymentDetailsModel;

  factory PaymentDetailsModel.fromJson(Map<String, dynamic> json) =>
      _$PaymentDetailsModelFromJson(json);
}

CodePudding user response:

I think maybe you miss if else check in your map function, not pretty sure, but you can try :

on<OnChangeStatusListItemClick>((event, emit) async {
  final serviceId = event.serviceId;//(my  serviceId here)
  final paymentStatus = event.status;//(my  new status here)

  final paymentDetails = state.listVariant.map((paymentDetailsOne) {
    if ( paymentDetailsOne.serviceid == serviceId) {
      return paymentDetailsOne.copyWith(enable: paymentStatus);
    } else {
      return paymentDetailsOne;
    }
  }).toList();

  emit(state.copyWith(listVariant: paymentDetails));
});
  • Related