2

I have which cycles a heavy function X times. If I put this stream in a StreamBuilder, the Stream runs again and again forever, but I only need it to run once (do the X cycles) and the stop.

To solve this problem for future functions I used an AsyncMemoizer, but I cannot use it for stream functions.

How can I do it?

fabriziog
  • 399
  • 6
  • 16

2 Answers2

1

If you are sure, your widget should not be rebuilt, than try sth like this code below. The _widget will be created once in initState, then the 'cached' widget will be returned in the build method.

class MyStreamWidget extends StatefulWidget {
  @override
  _MyStreamWidgetState createState() => _MyStreamWidgetState();
}

class _MyStreamWidgetState extends State<MyStreamWidget> {
  StreamBuilder _widget;
  // TODO your stream
  var myStream;

  @override
  void initState() {
    super.initState();
    _widget = StreamBuilder(
      stream: myStream,
        builder: (context, snapshot) {
          // TODO create widget
          return Container();
        })
  }

  @override
  Widget build(BuildContext context) {
    return _widget;
  }
}
0

As Rémi Rousselet suggested, the StreamBuilder should be used in a Widget Tree where the state is well managed. I was calling setState((){}) in the Stream which caused the UI to update every time, making the StreamBuilder rebuild so restarting the stream.

fabriziog
  • 399
  • 6
  • 16