useViewModel<T extends BaseViewModel> function

T useViewModel<T extends BaseViewModel>(
  1. WidgetRef ref,
  2. T buildModel()
)

Registers a class extending BaseViewModel inside of the locator. This can be called inside any view extending HookWidget, causing lifecycle events to be pushed to the view model.

Note: A view model can only be registered once. If a new instance of a page is made, the same view model will be used.

Implementation

T useViewModel<T extends BaseViewModel>(WidgetRef ref, T Function() buildModel) {
  final bool hasOverridenViewModel = GetIt.instance.isRegistered<T>();
  T model;

  if (hasOverridenViewModel) {
    model = inqvine.getFromLocator<T>();
  } else {
    model = buildModel();
    GetIt.instance.registerSingleton(model);
  }

  useLifecycleHook(model);
  ref.watch(ChangeNotifierProvider<T>((_) => model));

  return model;
}