Do you have to manually dispose streams from a streamprovider in Flutter?

Issue

I can’t find this in the official documentation for the provider package, does streamprovider automatically handle disposing of streams they are providing or do you have to do this manually? If so, what is the best practice of where to dispose a stream exposed using stream provider?

Solution

No, it is not necessary to manually clean up streams when using StreamProvider.

StreamProvider extends DeferredInheritedProvider, whose documentation states that the object being listened to will be automatically disposed of when the DeferredInheritedProvider is removed from the tree.

Actually, assuming that you’re not making the Stream yourself, then there is not much you can do in terms of cleaning up the actual Stream, as explained in this GitHub comment. The library providing the Stream should clean up the Stream. If, for example, I am listening to a Stream from the Firebase Auth plugin about users signing in and signing out of my app, it is the responsibility of that plugin to clear up that stream.

However, the thing listening to a Stream (StreamProvider in this case) does have a responsibility to clean up its StreamSubscription to that Stream, which StreamProvider does.

You can see in the Provider’s source code here that when creating an instance of DeferredStartListening, listen is called against the stream, which returns a StreamSubscription. At the end of the method, cancel is invoked against that subscription, which cleans up the StreamSubscription.

Answered By – Wes1324

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.