如何在颤振中生成流

问题描述

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

class CounterRepository {
  int _counter = 123;

  void increment() {
    _counter++;
  }

  void decrement() {
    _counter--;
  }

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

我预计随着 _counter 的变化,watchCounter() 将产生更新的 counter 值。当我从 UI 调用 increment()decrement() 时,似乎 _counter 的值正在改变,但 watchCounter 不会产生更新的 _counter 值。如何在此处生成更新的 _counter 值?我正在使用 UI 中的 StreamBuilder获取流数据。

解决方法

您已使用 -

创建了您的 streams
Stream<int> watchCounter() async* {
    yield _counter;
}

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

控制这些流事件

创建信息流

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

使用该流

stream.listen

通过调用listen函数订阅流并提供它 当有新值可用时回调函数。

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

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