rrousselGit / provider

InheritedWidgets, but simple
https://pub.dev/packages/provider
MIT License
5.11k stars 512 forks source link

MaterialApp's builder function breaks provider. Home: does not #825

Closed feyokorenhof closed 1 year ago

feyokorenhof commented 1 year ago

Describe the bug

I have to use MaterialApp's builder function instead of home to ensure MediaQuery applies to nested routes. But for some reason this breaks provider and gives me a lot of ProviderNotFoundException. I am unsure if this is a bug in Provider, Flutter or a mistake I'm doing but I've tried a lot of variations with placing my MultiProvider above and below MaterialApp and placing widgets in-between them but nothing seems to work.

EDIT: it looks like the errors only show up when I use Navigator.push() I really don't understand why this would be the case when using builder instead of home.

To Reproduce

use MaterialApp's builder function instead of home parameter.

This does not crash:

MultiProvider(
    providers: [
        ChangeNotifierProvider(create: (_) => CarouselProvider()),
         ...
    ],
    child:
            MaterialApp(
                  home:
    Consumer<CarouselProvider>(builder: (context, csp, child) => ANestedWidget(context));
                  ));

This does:

MultiProvider(
    providers: [
        ChangeNotifierProvider(create: (_) => CarouselProvider()),
         ...
    ],
    child: MaterialApp(
                  builder: (context, child) {
                       // Nested widgets inside this consumer give a `ProviderNotFoundException`. Consumer itself does not.
                       return Consumer<CarouselProvider>(builder: (context, csp, child) => ANestedWidget(context));
                  }));

Expected behavior For provider to still work when using the builder function.

I'm sorry if this is a silly mistake or not a provider bug but I'm out of ideas. Any help is appreciated!!

rrousselGit commented 1 year ago

I don't understand your "This does not crash" code. There's no home parameter on MultiProvider

feyokorenhof commented 1 year ago

Ah, my bad I messed that up. Edited the code.

It's about the MaterialApp builder and home function.

rrousselGit commented 1 year ago

I'm not aware of a specific reason why that would happen. Could you make a complete reproducible example? Something executable that's also short

feyokorenhof commented 1 year ago

I'm going down quite the rabbit hole atm :p. It looks like It might actually be a problem of using the context used by pushing a new MaterialPageRoute with Navigator.of(context).push(). I'll do some more testing and come back to you.

Thanks for the quick responses!

feyokorenhof commented 1 year ago

We managed to fix our problem without using builder so this is no longer an issue for us. I'm still curious as to how this behavior happened to us so I might come back to it later just for fun.

But we can close this issue afaic :).