Solved: Which is better when using provider instance in a new widget?

Question

Asked by Jinsub K on December 14, 2021 (source).

Let's say I've written my code as below. I've got a provider called SampleProvider, and I'm using it in my main widget.

class SampleProvider extends ChangeNotifier {}

class MainWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SampleProvider provider = Provider.of<SampleProvider>(context);
  }
}

And then, I want to make a new widget and use this provider in the new widget. There will be two choices. First, I just instantiate another provider in the new widget as below.

class NewWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    SampleProvider provider = Provider.of<SampleProvider>(context);
  }
}

Or, I can send it from the main widget to the new widget as a constructor parameter. Like this:

class NewWidget extends StatelessWidget {
  final SampleProvider provider;
  NewWidget(this.provider);

  @override
  Widget build(BuildContext context) {
  }
}

I guess the first option is better because flutter draws a widget based on its build context, but I'm not sure. I've googled it quite long, but there was no success. Can anybody tell me whether I am right or wrong? Or Do they have no difference?

Answer

Question answered by 聂超群 (source).

Prefer the first solution, it's easier to refactor.

Suppose you need move NewWidget in your widget tree, you also need to modify the "paramter pass" code if you choose second solution, which is not necessary with first solution.

One of Provider pacakage's purpose is avoid passing parameter deep in the widget tree by the way.

DART FLUTTER FLUTTER-DEPENDENCIES FLUTTER-PROVIDER
SHARE: