简体   繁体   English

如何在颤动中生成流

[英]How to generate stream in flutter

I am making some experiment with flutter stream.我正在用颤振流做一些实验。 I have a class for generating stream of int .我有一个用于生成int流的类。 Here is the class :这是课程:

class CounterRepository {
  int _counter = 123;

  void increment() {
    _counter++;
  }

  void decrement() {
    _counter--;
  }

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

I expect with the change of _counter , watchCounter() will yield updated counter value.我希望随着_counter的变化, watchCounter()将产生更新的counter值。 When I call increment() or decrement() from UI, it seems the value of _counter is changing but watchCounter doesn't yield the updated _counter value.当我从 UI 调用increment()decrement()时,似乎_counter的值正在改变,但watchCounter不会产生更新的_counter值。 How to yield updated _counter value here?如何在此处生成更新_counter值? I am using StreamBuilder from UI to get the streamed data.我正在使用 UI 中的StreamBuilder来获取流数据。

You have created your streams using -您已经使用 - 创建了您的streams

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

But to reflect the changes of your stream, you need to receive those stream events.但是要反映流的变化,您需要接收这些流事件。 You can control those stream events using a StreamController您可以使用StreamController控制这些流事件

Creating a stream创建流

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

Using that stream使用该流

stream.listen流听

Subscribes to the stream by calling the listen function and supplys it with a Function to call back to when there's a new value available.通过调用监听函数订阅流,并为它提供一个函数,以便在有新值可用时回调。

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

There are many other approaches to control and manage streams but for your particular question .listen will do the job.还有许多其他方法可以控制和管理流,但对于您的特定问题, .listen将完成这项工作。

You are missing an infinite while loop, it's a manual stream.你错过了一个无限的while循环,它是一个手动流。

Stream<dynamic> watchCounter() async* {
   while (true) {
      // you can change it to 5 seconds or higher
      await Future.delayed(const Duration(seconds: 1));
      yield _counter;
   }
}

And after that you just need to call listen:之后你只需要打电话听:

watchCounter().listen((value) {
  // hear can be empty if you want.
});

You can put it in your init state to run, don't put it in your widget build, please.你可以把它放在你的初始化状态运行,请不要把它放在你的小部件构建中。

This should work fine这应该可以正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM