'Provider, what's the difference between assigning it to a variable and using it directly?

I have multiple extracted widgets that need to access the provider that is already declared in their parent widget.

I'm trying to access the provider directly using this Provider.of<MyProvider>(context).getSomething(), and it doesn't work. But when I assign it to a variable on top of the build method var provider = Provider.of<MyProvider>(context) then use the method like this provider.getSomething(), it works, why is that?

Will there be a problem if I put this var provider = Provider.of<MyProvider>(context) on every build method of my extracted widgets? or should I just add the provider as a constructor so the parent widget will just pass the provider for every extracted child widget?



Solution 1:[1]

In the first one you are only declaring it with that type, as a result the value will be nothing and nothing is assigned to what you declared and so the object is empty and do not have access to the functions or so on. In the second case you are assigning to that object so it will have access to all functions and so on.

no it's ok and it's a common pattern to use.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Benyamin