【Dart】Streamとは?使い方

最終更新日

import 'dart:math';

Stream<int> chinchiroAsync([int times = 3]) async* {
  final random = Random();
  int count = 0;

  while (true) {
    if (count == times) {
      yield -1; // = 'Finish!'
      break;
    }
    yield 0; // = 'Roll'
    for (var i = 0; i < 3; ++i) {
      await Future.delayed(Duration(seconds: 1));
      yield random.nextInt(6) + 1;
    }
    ++count;
  }
}

void main() async {
  final stream = chinchiroAsync();
  await for (int i in stream) {
    print(i);
  }
}

fem