Dmitry Bubnenkov
Dmitry Bubnenkov

Reputation: 9859

Should I close Streams if I use Stateless Widget?

I did small stateless widget that use Streams. I have read that I always should close Streams to prevent memory leak. But Stateless widget do not have dispose() method.

So what I should to do? Do not use Streams in Stateless? Or it's ok?

Here is my code:

class HomePage extends StatelessWidget {
  Bloc _bloc = Bloc();

  @override
  Widget build(BuildContext context)
  {
    return Scaffold(
      appBar: AppBar(),
      body: Container(
        child: 
        StreamBuilder(
          stream: _bloc.counter,
          initialData: 0,
          builder: (BuildContext context, AsyncSnapshot<int> _snapshot)
          {
            return Column(
              children: <Widget>[
                Text("Pressed: ${_snapshot.data}"),
                RaisedButton(child: Text("inc"), onPressed: () => { _bloc.eventSink.add(IncrementEvent()) },),
                RaisedButton(child: Text("dec"), onPressed: () => { _bloc.eventSink.add(DecrementEvent()) },)
              ],
            );
          }

        )

      ),
    );

  }

}

My code base on example from here.

If memory-leaks please explain how it would be? Every click new object will be created? Or what?

Upvotes: 4

Views: 308

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 276957

In such a situation, you cannot use a StatelessWidget, otherwise you'll have memory leaks and may lose your state.

Convert your widget to a StatefulWidget and properly dispose your object.

Upvotes: 1

Related Questions