1

我正在用颤振流做一些实验。我有一个生成流的类int。这是课程:

class CounterRepository {
  int _counter = 123;

  void increment() {
    _counter++;
  }

  void decrement() {
    _counter--;
  }

  Stream<int> watchCounter() async* {
    yield _counter;
  }
}

我希望随着 的变化_counterwatchCounter()将产生更新的counter值。当我调用increment()decrement()从 UI 调用时,它的值似乎_counter正在改变,但watchCounter不会产生更新的_counter值。如何在_counter这里产生更新的价值?我正在使用StreamBuilderUI 来获取流数据。

4

1 回答 1

1

您已经创建了您的streams使用 -

Stream<int> watchCounter() async* {
    yield _counter;
}

但是要反映流的变化,您需要接收这些流事件。您可以使用StreamController控制这些流事件

创建流

Future<void> main() async {
  var stream = watchCounter();
}

使用该流

流听

通过调用监听函数订阅流,并为它提供一个函数,以便在有新值可用时回调。

stream.listen((value) {   
print('Value from controller: $value');
}); 

还有许多其他方法可以控制和管理流,但是对于您的特定问题.listen,它们可以胜任。

于 2021-06-30T06:44:05.053 回答