skip to Main Content

I have an array of data .
Here is a photo of the model:
enter image description here

This model has an array of services.
I want to use a request to combine all services from all elements and have one list.

I tried to do like this but it doesn’t work. Maybe someone knows how to do it??
My example :

  List<PriceServicesModel> get selectedServices {
    List<PriceServicesModel> list = [];
    for (var element in multiServicesModel) {
      for (var services in element.services) {
        list = [...list, services];
        print(list);
      }
      return list;
    }
    return list;
  }

I will be grateful for any help.

2

Answers


  1. You don’t need to create a list with every iteration, just use list.add() instead. And also remove the first return, so it doesn’t return after the first loop.

    List<PriceServicesModel> get selectedServices {
        List<PriceServicesModel> list = [];
        for (var element in multiServicesModel) {
          for (var services in element.services) {
            list.add(services);
          }
        }
        return list;
      }
    
    Login or Signup to reply.
  2. You should return the list at the end of function.

    List<PriceServicesModel> get selectedServices {
        final List<PriceServicesModel> list = [];
        for (var element in multiServicesModel) {
          list = list.addAll(element.services);
          //return list; //This line should be removed
        }
        return list;
      }
    

    I made some optimisations here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search