Home > Net >  get all the naturals less than a number in ascending order
get all the naturals less than a number in ascending order

Time:11-22

I'm making a quiz app, and the options are storage this way:

option1 = 'First option'
option2 = 'Second option'
option3 = 'Third option'
numberOfOptions = 3

As some questions will have 4 alternatives, others 2, I'm trying to create a method to dynamically retrieve the number of alternatives available. For that, I have the numberOfOptions variable. Based on this number, I need to get all the natural numbers less than it until 1 (as in the example, [1, 2, 3]), where I need to add to 'option'. The final result must be:

['option1', 'option2', 'option3'];

For now, what I did was:

void options() {
  int numberOfOptions = 3;
   for (int i = 0; i < numberOfOptions; i  ) {
   print('option${i   1}');

 }
}

On the output I get option1, option2, option3, but I'm stuck trying to return it as a List

CodePudding user response:

One elegant solution would be to make use of the List.generate() constructor and achieve our objective with just one line:

List<String>.generate(numberOfOptions, (int index) => 'option${index   1}');

The List.generate() constructor takes two arguments:

  • length;
  • a generator function that has an index variable;

You can read more about it on the official documentation.

It can be useful as it's much easier to read and leaner than a for-loop.


As outlined by @jamesdlin, another option would be to use the collection-for:

List<String> options = [
  for(int i = 0; i < numberOfOptions; i  ) 'option${i   1}'
];

CodePudding user response:

You need to create a list in your options() functions and fill it in the foor loop like so:

List<String> options(int numberOfOptions) {
   final List<String> options = [];
   for (int i = 0; i < numberOfOptions; i  ) {
      print('option${i   1}');
      options[i] = 'option${i   1}';
   }
   return options;
}
  • Related