What's the proper way to dependecy inject with Provider?

Issue

I’m building an app and want to use Provider as my to-go DI tool.

I want to build an app with a following architecture:

  • Views
  • ViewModels
  • Sevices

Views are plain simple UIs, supported by viewmodels for (almost) every view. And these viewmodels are dependent on values, which are held by services.

Viewmodels are extended with ChangeNotifierProvider to reflect changes in the UI, and this works okay. But what should I use to be responsive to the changes in the services. Single service can be used in multiple viewmodels and, sure, I need to keep all of them up to date.

I’ve looked up some tutorials, dugged in Flutter Provider v3 Architecture using ProxyProvider for Injection, but it really doesn’t explain to me this kind of this or I don’t get it.

ProxyProvider is used for other cases there. Viewmodel makes requests to the service, but it’s values are consumed directly in the UI.

What’s the proper way to make this kind of connection work? Should I use ChangeNotifierProxyProvider for such case? Should I use streams?

Solution

To use di as you say there is ProxyProvider; ProxyProvider can be as app scoped (declared on top of App widget so he can be accessed anywhere in-app For example AuthService) or widget (screen) scoped for example your ViewModel

In this example, A is ViewModel of MyWidget and B is Service
Ps. you should provide another Provider with B class on top of this hierarchy so ProxyProvider can access it to “provide”┬áto A class

ProxyProvider<B, A>(
        create: (_) => A(),
        update: (_, b, a) => a..bClassVariable = b,
        dispose: (_, a) => a.dispose(), //if you use streams
        child: MyWidget(

        ),
      )

About your last answer there is no answer) only you should decide which approach is better for your needs, If you familiar with ViewVievModel you can stay with it, or learn something new like BloC

Ps. If you use ViewModel ChangeNotifierProxyProvider will work fine
and if you use bloc streams should be used

Answered By – Philip Dolenko

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.