I was practicing for loop and lists and I was having a little problem assigning dynamic number after looping through a list of names. example: i have a list of names:
final list = ['liam','james','jerry','owen'];
and i was trying to achieve this output below:
1.liam
2.james
3.jerry
4.owen
but i keep getting this:
1. liam
1. james
1. jerry
1. owen
2. liam
2. james
2. jerry
2. owen
3. liam
3. james
3. jerry
3. owen
4. liam
4. james
4. jerry
4. owen
this is my code below:
void main() {
final list = ['liam','james','jerry','owen'];
if(list.isNotEmpty){
for(var i =1;i<=list.length;i ){
final count =i;
for(var name in list){
print('$count. $name');
}
}
}
}
CodePudding user response:
You have two loops in your code, thus making the names repeat.
You only need to use one loop, and access the names using list[i]
:
void main() {
final list = ['liam', 'james', 'jerry', 'owen'];
if (list.isNotEmpty) {
for (var i = 0; i < list.length; i ) {
print('${i 1}. ${list[i]}');
}
}
}
CodePudding user response:
Simply, it's just like that
void main() {
final list = ['liam','james','jerry','owen'];
if(list.isNotEmpty){
for(var i = 0; i <= list.length; i ){
print(((i 1).toString()) '.' list[i]);
}
}
}