Access Data
There are several ways to access the ViewModel now that its added to your widget tree.
1. Use the provided "model" object:โ
return Scaffold(
body: HomeViewModelBuilder(
builder: (context, model) {
return Text(model.title); // Add a title String to your ViewModel
},
),
);
2. Use the getModel<T> helper function:โ
Under the hood, the getModel function uses dependOnInheritedWidgetOfExactType to get the type you specify in the generic parameter T.
return Scaffold(
body: HomeViewModelBuilder(
builder: (context, model) {
return Text(getModel<HomeViewModel>(context).title); // Add a title String to your ViewModel
},
),
);
3. Use the ModelWidget widget:โ
This package includes a ModelWidget
widget. This widget is similar to a Builder
widget with the added benefit that it finds the nearest ViewModel
in the subtree and includes it in the builder function:
ModelWidget<ScreenTwoViewModel>(
builder: (context, model) {
return Text(model.counter.value.toString());
},
),
4. Use the .of(context) method:โ
Each ViewModel has a built in .of() method. This is useful if you break your widget tree up and need to access the model in a different widget:
return Scaffold(
body: HomeViewModelBuilder(
builder: (context, model) {
return Text(HomeViewModel().of(context).title); // Add a title String to your ViewModel
},
),
);
The .of(context) method only works on an instance of your ViewModel since static members can't reference type parameters of a class.
If you want to save yourself the time it takes to type the extra parenthesis, add a separate method directly in your View Model (classes can't have instance and static methods with the same name, hence the ".of_" vs ".of")
class HomeViewModel extends ViewModel<HomeViewModel> {
// Add this
static HomeViewModel of_(BuildContext context) => getModel<HomeViewModel>(context);
}