Home > Software design >  How to return a dart list without creating another list inside the function?
How to return a dart list without creating another list inside the function?

Time:11-05

List<int> getNumbers() {
  List<int> numbers = [];
  for (int i = 0; i < 100; i  ) {
    numbers.add(i);
  }
  return numbers;
}

I want to return a List of integers but the list itself is generated using a loop, so is there is any way to directly return the values of the loop without creating another list to store the values of each iteration?

CodePudding user response:

It's not entirely clear to me what you are asking for. You want to return a list, but you also don't want to create a list.

You are not creating another list inside the function. You are creating the list, and then returning that list. There is only one list in play.

But, you can write it differently too.

First of all, your functions should probably be a getter named numbers, not a function named getNumbers.

You can also create the list in a single expressions:

 [for (var i = 0; i < 100; i  ) i]

What you can do differently is return an iterable:

Iterable<int> get numbers sync* {
  for (var i = 0; i < 100; i  ) {
    yield i;
  }
}

That won't create a list at all.

Or, if you don't want to create a new list each time, cache it:

List<int>? _numbers;
List<int> get numbers() => _numbers ??= [
  for (var i = 0; i < 100; i  ) i
];

or just

final List<int> numbers = [
  for (var i = 0; i < 100; i  ) i
];

That will create only one list, and reuse it every time you ask for it (which can be a problem because the list is mutable, so only do this if you trust the reader to not modify the list!)

CodePudding user response:

You can create a getter that returns the list of numbers directly using the List generate function, for example

List<int> get getNumbers => List.generate(100, (index) => index   1);

Or use a method

List<int> getNumbers() {
  return List.generate(100, (index) => index   1);
}
  • Related