Skip to main content

Reuse ViewModels

Extend a ViewModelโ€‹

To share logic between multiple ViewModels, create a separate ViewModel with the shared logic. Be sure to include the generic type T in the ViewModel class definition.

import 'package:code_on_the_rocks/code_on_the_rocks.dart';
import 'package:flutter/foundation.dart';

class CounterViewModel<T> extends ViewModel<T> {
ValueNotifier<int> counter = ValueNotifier(0);

void increment() {
setState(() {
counter.value = counter.value + 1;
});
}
}

Then, extend the ViewModel in your other ViewModels. Pass the ViewModel type as the generic type T.

class OneViewModel extends CounterViewModel<OneViewModel> {
static OneViewModel of_(BuildContext context) => getModel<OneViewModel>(context);
}

This approach is useful when the shared logic is simple and is only used in a few ViewModels.

ViewModel Mixinsโ€‹

If you want more granular control over the which shared logic each ViewModel can use, Mixins are a better approach. Create a mixin for each piece of shared logic (again, remember to include the generic type T in the mixin class definition):

mixin ColorMixin<T> on ViewModel<T>{
ValueNotifier<Color> color = ValueNotifier(Colors.blue);

void setColor(Color val){
color.value = val;
}
}

Then, extend the ViewModel and include the mixins you want to use.

class TwoViewModel extends CounterViewModel<TwoViewModel> with ColorMixin{
static TwoViewModel of_(BuildContext context) => getModel<TwoViewModel>(context);
}