“This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Introduction to the

Generators have been introduced in ES6 along with asynchronous programming, using yield keywords to generate corresponding data. Dart also has the concepts of yield keywords and generators.

When is the generator? A generator is a device that continuously generates some data, also known as a generator.

Generator for both return types

Dart returns different results depending on whether the generation is synchronous or asynchronous.

If the return is synchronous, an Iterable object is returned.

If it is returned asynchronously, a Stream object is returned.

The synchronous generator uses sync* keywords as follows:

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

An asynchronous generator uses async.

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

Yield is used for keyword generation.

If yield is itself a generator, use yield*.

Iterable<int> naturalsDownFrom(int n) sync* { if (n > 0) { yield n; yield* naturalsDownFrom(n - 1); }}Copy the code

The operation of the Stream

Stream refers to a stream, and once we have this stream, we need to retrieve the data from the stream.

There are two ways to retrieve data from a Stream. The first is to use the Stream’s API to retrieve data from the Stream.

The simplest is to call the stream’s listen method:

StreamSubscription<T> listen(void onData(T event)? , {Function? onError, void onDone()? , bool? cancelOnError});Copy the code

Listen can be connected with data processing methods, which are as follows:

final startingDir = Directory(searchPath); startingDir.list().listen((entity) { if (entity is File) { searchFile(entity, searchTerms); }});Copy the code

The default method is the onData method.

The other kind is “await for”.

The syntax for await for is as follows:

await for (varOrType identifier in expression) {
  // Executes each time the stream emits a value.
}
Copy the code

Note that the above expression must be a Stream object. And await for must be used in async as follows:

Future<void> main() async {
  // ...
  await for (final request in requestServer) {
    handleRequest(request);
  }
  // ...
}
Copy the code

If you want to interrupt listening on a stream, you can use either break or return.

conclusion

That’s how generators are used in DART.