我有一个流从Web api返回值,而小部件则提供一个值(使用FutureBuilder)。用户可以使用一个简单的下一个按钮迭代这些值。我不想提前加载所有值,但我不想在按下下一个按钮时加载每个值。
我当前的代码是:
Queue<Item> itemQueue = Queue<Item>();
Future<Item> curItem;
Future<Item> getItem() async {
while (itemQueue.isEmpty)
await Future.delayed(Duration(milliseconds: 250));
return itemQueue.removeFirst();
}
@override
void initState() {
// ...
final sub = stream.listen((item) async {
itemQueue.add(item);
});
// ...
}
@override
Widget build(BuildContext context) {
// ...
ItemWidget(curItem)
// ...
RaisedButton(child: Text("next"),
onPressed: (){
setState(() {
curItem = getItem();
});
},)
// ...
}
这有效,但感觉这不是最正确/最优雅的方法。
还有更好的方法吗?
谢谢!
您应该能够使用Stream.asBroadcastStream和Stream.take来做到这一点。
您的代码将如下所示:
final myStream = Stream.fromIterable([1,2,3,4,5]);
// We need to be able to listen to the stream multiple times.
final stream = myStream.asBroadcastStream();
for (int i = 0; i < 5; ++i) {
// Creates a new Stream with 1 element which we can call Stream.first on
// This also changes the contents of stream.
print(await stream.take(1).first);
}
将输出:
1
2
3
4
5