Home > other >  What is the recommend practice around StreamProvider create construction and keeping state in Flutte
What is the recommend practice around StreamProvider create construction and keeping state in Flutte

Time:10-11

So one of the recommended practices for futures and streams is not to create them in a stateless's widget build function because they would be recreated anytime when the build function is called. An example is this video: Flutter Future Builder | The Right way However, there is the provider's create function, specifically in this context StreamProvider.

StreamProvider({
    Key? key,
    required Create<Stream<T>?> create,
    required T initialData,
    ErrorBuilder<T>? catchError,
    UpdateShouldNotify<T>? updateShouldNotify,
    bool? lazy,
    TransitionBuilder? builder,
    Widget? child,
  }) 

My question is if I am using the create constructor, can I create the stream for the provider in a stateless widget build function and expect the provider to know not to recreate the stream every time the build function is called?

Thank you for your time.

CodePudding user response:

Provider's create function can be used to create objects (including streams) and will correctly cache that value across rebuilds

That's kind of the whole point in fact. The Provider package was created in part because people forgot to cache their Futures/Streams/ChangeNotifiers. So using this create function, the Provider package dealt with caching for its users.

So yes. It is safe to create anything within the create function of a provider.

  • Related