首页 > 建站教程 > dart >  dart笔记15:通过periodic创建stream流正文

dart笔记15:通过periodic创建stream流

dart笔记15:通过periodic创建stream流,有点类似于定时器,每隔一秒执行一次:
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);

  //拦截处理,只获取8之前的数字
  stream = stream.takeWhile((data) {
    return data < 8;
  });

  await for (var i in stream) {
    print(i);
  }

  //跳过前两条
  // stream = stream.skip(2);

  //跳过小于5的数字
  // stream = stream.skipWhile((data) => data < 5);

  //拿到stream所有的数据(stram执行结束,一次性返给listData)
  // List listData = await stream.toList();
  // for (var i in listData) {
  //   print(i);
  // }

  //拿到stream的数据流个数
  // var len = await stream.length;
  // print('个数:$len');
}