fabriziog
fabriziog

Reputation: 419

Make a Stream in StreamBuilder only run once

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?

Upvotes: 2

Views: 2717

Answers (2)

fabriziog
fabriziog

Reputation: 419

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.

Upvotes: 1

Alexander Kwint
Alexander Kwint

Reputation: 136

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;
  }
}

Upvotes: 1

Related Questions