Reference documents: dart.cn/guides/lang…

Consider using generator functions when you need to generate a string of values lazily. Dart has built-in support for two forms of generator methods:

  1. Synchro generator: Returns one可迭代Object.
  2. Asynchronous generator: Returns oneStreamObject.

Use sync* to mark a function as a synchronization generator and return an Iterable object,

可迭代<int> naturalsTo(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}
Copy the code

Use async* to mark the function as an asynchronous generator that returns a Stream object

Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}
Copy the code

What is the use of yield 🤔? According to stackOverflow, both yield and return return return a value, except that yield does not exit the function. As in the example above, yield returns the value of k but does not exit the naturalsTo function until the end of the while loop

Demos

  1. Use the synchrogenerator to generate the range function for the for loop.
可迭代<int> range(int end, {int step = 1.int start = 0}) sync* {
  if (step == 0) throw Exception('Step cannot be 0');
  if ((step > 0 && start < end) || (step < 0 && start > end)) {
    yield start;
    yield* range(end, step: step, start: start + step); }}void main() {
  // Increment interval 1(default)
  for (var value in range(5)) print(value); // [0, 1, 2, 3, 4]

  // Increment interval 2
  for (var value in range(5, step: 2)) print(value); / / [0, 2, 4]

  // Increment interval 5
  for (var value in range(5, step: 5)) print(value); / / [0]

  // Decrease the interval by 1
  for (var value in range(- 1, start: 4, step: - 1))
    print(value); // [4, 3, 2, 1, 0]

  // Decrease the interval by 2
  for (var value in range(- 1, start: 4, step: 2 -)) print(value); / / (4, 2, 0]

  // Decrease the interval by 5
  for (var value in range(- 1, start: 4, step: - 5)) print(value); / / [4]
}
Copy the code
  1. Generator syntax sugar
// Use syntactic sugar to get an iterator
var iterator = [for (var i = 0; i < 5; i++) i];

for (var value in iterator) print(value);
Copy the code

On Stream

There’s a table that makes it very clear, and I’ll talk about it later.

int Single value More value
synchronous int Iterator<int>
asynchronous Future<int> Stream<int>