首页 > 建站教程 > dart >  dart笔记17:stream流的监听、循环、筛选正文

dart笔记17:stream流的监听、循环、筛选

dart笔记17:stream流的listen监听、forEach循环、where筛选:
import 'dart:async';

void main() {}

createStream() async {
  Duration duration = Duration(seconds: 1);
  Stream<int> stream = Stream<int>.periodic(duration, (data) => data);

  //拦截处理,只获取0-9
  stream = stream.take(10);

  //筛选流,只显示大于2小于6的流
  // stream.where((data) => data > 2);
  // stream.where((data) => data < 6);

  //监听流
  // stream.listen((data) {
  //   print(data);
  // }, onDone: () {
  //   print('流已完成');
  // }, onError: (error) {
  //   print('流发生错误');
  // }, cancelOnError: false);

  //循环foreach
  // stream.forEach((val) {
  //   print(val);
  // });
}