FilledStacks / flutter-tutorials

The repo contains the source code for all the tutorials on the FilledStacks Youtube channel.
MIT License
4.76k stars 1.76k forks source link

Is creating HomeViewModel instance like this correct? #55

Closed aspiringant closed 4 years ago

aspiringant commented 4 years ago

https://github.com/FilledStacks/flutter-tutorials/blob/de32c20bc8573e549269be5d949e146acf8ed987/031-responsive-architecture-provider/02-final-state-implementation/lib/views/home/home_view.dart#L15

aspiringant commented 4 years ago

The issue I see here is that whenever the build of HomeView will be called, it can be that BaseWidget has to be recreated as it might be dirty, which would result in HomeViewModel instance also being created again and again.

Ideally, view models are initialized inside the builder method of ChangeNotifierProvider. The code you have will work fine, but if it is extended by others ( which happened to our teammate ) it would create complications.

FilledStacks commented 4 years ago

@aspiringant I usually use the singleton pattern for ViewModels that I don't want to be constructed everytime. This can be done by manually implementing the singleton pattern or using a singleton registration in get it and getting your viewmodel from there like i've shown in some other tutorials.