从流一一获得期货

问题描述 投票:0回答:1

我有一个流从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();
          });
        },)
  // ...
}

这有效,但感觉这不是最正确/最优雅的方法。

还有更好的方法吗?

谢谢!

flutter dart
1个回答
0
投票

您应该能够使用Stream.asBroadcastStreamStream.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
© www.soinside.com 2019 - 2024. All rights reserved.