Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get all the naturals less than a number in ascending order

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading