首页 > 建站教程 > dart >  dart笔记16:stream流创建的另外三种方法正文

dart笔记16:stream流创建的另外三种方法

dart笔记16:stream流创建的另外三种方法:除了之前的periodic创建计时流之外,还有通过future创建以及通过List创建:
import 'dart:async';
import 'dart:io';

void main() {
  createStreamFromFuture();
  createStreamFromFutures();
  createStreamFromIterable();
}

//通过单个Future创建Stream流
createStreamFromFuture() async {
  Future<String> future = Future(() {
    return '异步任务';
  });

  Stream<String> stream = Stream<String>.fromFuture(future);

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

//通过多个Future创建Stream流
createStreamFromFutures() async {
  Future<String> future1 = Future(() {
    return '异步任务1';
  });

  Future<String> future2 = Future(() {
    sleep(Duration(seconds: 5));
    return '异步任务2';
  });

  Future<String> future3 = Future(() {
    return '异步任务3';
  });

  Stream<String> stream =
      Stream<String>.fromFutures([future1, future2, future3]);

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

//通过fromIterable进行创建
createStreamFromIterable() async {
  Stream<int> stream = Stream<int>.fromIterable([1, 2, 3, 4, 5]);
  await for (var i in stream) {
    print(i);
  }
}