flutter_bloc/provider RepositoryProvider vs Provider

Issue

Im new to flutter and currently figuring out DI.
I am using flutter_bloc and provider packages.

flutter_bloc ships with a RepositoryProvider, the question im asking myself now is whats the diffrence to Provider from provider?

Is there anything special to RepositoryProvider repositories or is it just a naming strategy?

Solution

  • RepositoryProvider does not handle updates.
    You cannot "change" the repository at runtime.
  • Provider does handle updates (using Provider.value). This means if you change the object at runtime, then the widgets which use it will rebuild.

The impact of this difference is on life-cycles like initState:

Using Provider, you have to explicitly not listen to the object changes:

void initState() {
  super.initState();
  // will fail if listen: false is not specified
  Provider.of<MyObject>(context, listen: false);
}

Using RepositoryProvider, you don’t have to care:

void initState() {
  super.initState();
  RepositoryProvider.of<MyObject>(context);
}

So this is only a difference in verbosity.

In fact, since Provider version 4.1.0, you can use context.read<MyObject>() instead of Provider.of<MyObject>(context, listen: false) – which reduces the verbosity difference

Answered By – Rémi Rousselet

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *