title: Flutter- Understanding the lifecycle of Provider, Bloc and when to dispose the stream
body: <p>Need to understand when we should Bloc pattern and life cycle of Bloc (how to release objects holding memory)</p>
  
  <p>I have a screen where I am fetching the data from the server and data will be used for a single screen only. I am using Bloc pattern to show the data. </p>
  
  <p>When using the Bloc pattern, I have a screen where I am using StatelessWidget. I am trying to dispose of the stream on 'WillPopScope'. Once disposed of, the stream cannot be used anymore. Because visiting the same screen result in a crash as I have wrapped my MaterialApp with the Bloc. </p>
  
  <ol>
  <li>created a stream</li>
  </ol>
  
  <pre><code>    final _leaderBoardList = StreamController&lt;List&lt;dynamic&gt;&gt;.broadcast();
  </code></pre>
  
  <ol start="2">
  <li>disposing stream</li>
  </ol>
  
  <pre><code>    dispose() {
        print('_leaderBoardList disposed');
        _leaderBoardList.close();
      }
  </code></pre>
  
  <ol start="3">
  <li>wrapping Material App within the provider:</li>
  </ol>
  
  <pre><code>    LeaderBoardProvider(
          child: MaterialApp(
          title: 'Table View Fetch',
          theme: ThemeData(
            primarySwatch: Colors.teal,
          ),
          home: HomeScreen(),
        ),
        );
  </code></pre>
  
  <ol start="4">
  <li>Statelesswidget 'WillPopScope', I have commented dispose of code as currently bloc is created once as I understood:</li>
  </ol>
  
  <pre><code>  Widget build(BuildContext context) {
  
      print(' ListView fetch Build called');
      final bloc = LeaderBoardProvider.of(context);
      bloc.fetchLeaderBoards();
      return WillPopScope(
        onWillPop: () async {
          //bloc.dispose();
          return true;
        },
        child: bodyStack(context, bloc),
      );
    }
  </code></pre>
  
  <p><b>The first Question</b>, Suppose I create a broadcast stream and remove dispose of code in 'WillPopScope', then everything works as expected but I think, this way, my Bloc hold a memory for app lifetime.</p>
  
  <p><b>Second Question</b>, How to handle such cases in which data is used within a screen. Is Bloc pattern recommended for this situation? </p>