Make a Stream in StreamBuilder only run once

2,094

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;
  }
}
Share:
2,094
fabriziog
Author by

fabriziog

Updated on December 12, 2022

Comments

  • fabriziog
    fabriziog over 1 year

    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?