如何在循环中将数组列表传递给构造函数

How to pass an array list to the constructor within loop

这更像是一个代码优化问题。假设我有以下代码。我需要多次调用构造函数并且它需要 4 个参数,多次手动调用此构造函数然后将参数传递给它们将是一个耗时的过程。所以我想缩短这个过程

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

尝试以更短的方式实现相同的结果

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
}

一开始你有循环错误,在你的情况下“for-loop”只会完成3次,如果你想要4次,应该是这样的:

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

关于你的问题,你可以这样回答:

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]);
  }

更灵活的解决方案是:

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]);
  }

如果您有不同类型的参数,更好的解决方案是创建实体-class(对象)来包含参数,例如:

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);
}