jojoclt
jojoclt

Reputation: 117

How to add element with same name using for loop to a list

I want to add some element with a same name to a List in Dart.

For example:

List<house> home = List<house>();

I want to add:

home.add(house1);
home.add(house2);
home.add(house3);

Is there anyway to add it iteratively like this?

for (int i = 1; i <= 3; i++) home.add(house$i);

Upvotes: 0

Views: 196

Answers (2)

gi097
gi097

Reputation: 7701

First of all: Why do you want to do this?

The behaviour you want to write can't be programmed. A name of a variable is passed to the compiler only for a reference, but once your code is compiled the name house1 or any other name you choose will be irrelevant. (for example house$i (which will be a String type) can only be generated at runtime, not at compile time).

You can actually achieve the behaviour you want by writing the following:

for (int i = 0; i < 3; i++) {
   home.add(new house());
}

As mentioned above, the following code will not work. The compiler is smart, but not smart enough to know that you will have 3 instances of house with their corresponding name, for example:

for (int i = 1; i <= 3; i++) home.add(house$i)
var a = house1; // Can't compile. Where can I find house1?

However you can always write the following:

var house1 = house();
var house2 = house();
var house3 = house();

home.add(house1); // Compiles! Now I know where to find house1!
home.add(house2);
home.add(house3);

Upvotes: 1

Tirth Patel
Tirth Patel

Reputation: 5736

You can create n Objects of House & store them in a List as follows, instead of creating multiple variables.

List<House> home = [House(), House(), House()]; // House() is an object of House.

OR

List<House> home = new List<House>();
for(int i = 0; i < n; i++) home.add(House());

Upvotes: 0

Related Questions