FilledStacks / provider_architecture

A set of widgets to help with the implementation of the Provider architecture as shown by FilledStacks
86 stars 15 forks source link

Reusing ViewModel with ChangeNotifierProvider.value constructor #10

Open mindthefish opened 4 years ago

mindthefish commented 4 years ago

Hi, first of all, thank you very much for this fantastic package, it makes my MVVM life much easier.

I am holding my data models in a List inside of my view model. I do not want to dispose the view model and recreate my data every time I navigate away and back to a certain screen, which is why I hold my view model as a lazy singleton using get_it. This works fine but throws an error when the ChangeNotifierProvider constructor is called within the ViewModelProvider built function with a reused view model.

What I am currently doing is a reimplementation of the ViewModelProvider class where I call the ChangeNotifierProvider.value constructor inside the built function, which gives me the opportunity to reuse my view model.

  @override
  Widget build(BuildContext context) {
    if (widget.providerType == _ProviderType.WithoutConsumer) {
      return ChangeNotifierProvider.value(
        value: _model,
        child: widget.builder(context, _model, null),
      );
    }

    return ChangeNotifierProvider.value(
      value: _model,
      child: Consumer(
        builder: widget.builder,
        child: widget.staticChild,
      ),
    );
  }

My suggestion is to provide an additional parameter in the ViewModelProvider.withConsumer and .withoutConsumer constructor bool reuse = false, which will be looked for in the build function. If reuse == true, the alternative ChangeNotifierProvider.value constructor could be called.

Or, alternatively, what would be the disadvantage of always using the .value constructor?

Thank you very much for your feedback!

mindthefish commented 4 years ago

This has a strong overlap with Issue #7 but instead is using the ViewModel and not the ViewModelProvider as a singleton.

FilledStacks commented 4 years ago

Has this been added yet? If not could you add it and push the code for it?

mindthefish commented 4 years ago

Finally found some minutes to do so! https://github.com/FilledStacks/provider_architecture/pull/13