Home > front end >  How to pass an array list to the constructor within loop
How to pass an array list to the constructor within loop

Time:11-23

This is more of a code optimization question. Let's say I'm having the following code. I need to call the constructor lots of times and it expects 4 arguments, calling this constructor many times manually and then passing arguments to them would be a time-consuming process. So I'm trying to shorten this process

constructor(argument1, argument2, argument3, argument4);
constructor(argument5, argument6, argument7, argument8);
constructor(argument9, argument10, argument11, argument12);
constructor(argument13, argument14, argument15, argument16);

Trying to achieve the same result in a shorter way

List = [argument1, argument2, argument3, argument4, argument5, argument6, argument7, argument8, argument9, argument10, argument11, argument12, argument13, argument14, argument15, argument16] // Stored all the arguments in an array or list

// Assuming constructor needs to be called 4 times 

for(int i = 0; i < 3; i  ){
    constructor(); // this is where I need your help, how to pass value to them
}

CodePudding user response:

At first, you have loop error, in you case "for-loop" will be complete only 3 times, if you would like 4 times, it's should be like this:

for(int i = 0; i < 4; i  ){
    constructor(); // this is where I need your help, how to pass value to them
}

About your question, you can do it like this:

List<String> arguments = [
    "arg01",
    "arg02",
    "arg03",
    "arg04",
    "arg05",
    "arg06",
    "arg07",
    "arg08",
    "arg09",
    "arg10",
    "arg11",
    "arg12",
    "arg13",
    "arg14",
    "arg15",
    "arg16"
  ];

  for (int i = 0; i < 16; i  = 4) {
    constructor(arguments[i], arguments[i   1], arguments[i   2], arguments[i   3]);
  }

More flexible solution is:

List<String> arguments = [
    "arg01",
    "arg02",
    "arg03",
    "arg04",
    "arg05",
    "arg06",
    "arg07",
    "arg08",
    "arg09",
    "arg10",
    "arg11",
    "arg12",
    "arg13",
    "arg14",
    "arg15",
    "arg16"
  ];

  // Number of arguments in constructor
  int argsNumber = 4;

  for (int i = 0; i < arguments.length; i  = argsNumber) {
    constructor(arguments[i], arguments[i   1], arguments[i   2], arguments[i   3]);
  }

If you have different types of arguments, better solution would be to create entity-class(object) to contain arguments, for example:

void main() {
  // List with objects
  List<Item> items = [
    Item("Name1", 23, 80.2),
    Item("Name2", 32, 77.1),
    Item("Name3", 54, 78.8),
    Item("Name4", 18, 67.5),
  ];

  // Call constructor for each object
  items.forEach((it) => constructor(it));
}

// Object to contain arguments
class Item {
  String name;
  int age;
  double weight;

  Item(this.name, this.age, this.weight);
}
  • Related