To use a Provider
in a showModalBottomSheet
, I need to wrap my MaterialApp
with a ChangeNotifierProvider
. Is there any effect on performance if MaterialApp
is nested with multiple ChangeNotifierProviders
which are primarily meant to handle bottom sheets in particular screens? Is there any other efficient way to use a Provider
in a showModalBottomSheet
?
2
Answers
It is perfectly fine to add multiple providers or use
MultiProvider
aboveMaterialApp
, it’s actually the right thing to do for global dependencies.There is a documented potential performance hit if you’re using
MultiProvider
to nest a lot of dependencies. This is less to do with widget tree performance but the hit you’re taking with instantiating a lot of widgets at once.As the documentation explains, there are ways around this including splitting your dependencies up and loading them based on state or simply avoiding
MultiProvider
. Your question specifically asks about wrapping yourMaterialApp
with multipleChangeNotifierProvider
s instead of usingMultiProvider
so I think you’re good in that regard.A more thorough explanation to your question is that your
Provider
s need to be inserted above aNavigator
for new routes that you push on the stack, either withNavigator.push
,showModalBottomSheet
, or by modifyingNavigator.pages
depending on which navigation style your using, to be able to access thoseProvider
s through the context.MaterialApp
builds your "root"Navigator
which is why they need to be aboveMaterialApp
. If you’re using the pattern of nested navigation, something we employee a lot in apps I work on, you’ll need to make sure anyProvider
s you want in that particular nestedNavigator
are above thatNavigator
. Besides being able to reuse these "inner journey", you can tailor the dependencies (Provider
s or otherInheritedWidget
s) needed for these navigation trees, allowing you to only inject what is needed where.You don’t need, and shouldn’t, wrap the entire app with your provider just to be able to use it in modals (any). Just use the
.value
constructor of a provider and provide the already created provider to the new widget tree (context) applicable to the modal.There are several examples of this posted here on SO, as well as examples and explanations of why you shouldn’t wrap your entire MaterialApp unnecessarily with a bunch of providers.