we try to develop a flutter app and we create a stateful widget as a page .
we want to separate build function from other state variable and state function in 2 different fi
I suggest moving your ViewModel code into a separate class that does not extend State
. Keep the ViewModel platform independent.
Your Widgets state can have an instance of the viewModel and interact with it.
You can find a more detailed example here
If child Widgets need to access your ViewModel you can use a Inherited Widget as suggested by @Rémi Rousselet. I quickly implemented this for you:
class ViewModelProvider extends InheritedWidget {
final ViewModel viewModel;
ViewModelProvider({Key key, @required this.viewModel, Widget child})
: super(key: key, child: child);
@override
bool updateShouldNotify(InheritedWidget oldWidget) => true;
static ViewModel of(BuildContext context) =>
(context.inheritFromWidgetOfExactType(ViewModelProvider) as
ViewModelProvider).viewModel;
}
Child widgets can grab the ViewModel by calling
var viewModel = ViewModelProvider.of(context);
Let me know if you have any questions :)