skip to Main Content

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


  1. It is perfectly fine to add multiple providers or use MultiProvider above MaterialApp, 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 your MaterialApp with multiple ChangeNotifierProviders instead of using MultiProvider so I think you’re good in that regard.

    A more thorough explanation to your question is that your Providers need to be inserted above a Navigator for new routes that you push on the stack, either with Navigator.push, showModalBottomSheet, or by modifying Navigator.pages depending on which navigation style your using, to be able to access those Providers through the context.

    MaterialApp builds your "root" Navigator which is why they need to be above MaterialApp. 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 any Providers you want in that particular nested Navigator are above that Navigator. Besides being able to reuse these "inner journey", you can tailor the dependencies (Providers or other InheritedWidgets) needed for these navigation trees, allowing you to only inject what is needed where.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search