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); } }
部分素材资源来源网站,本站提供免费下载,如有侵权请联系站长马上删除!