MVVM Design Pattern in Flutter
I have been using this plugin maintaining large scale application for flutter.mvvm_flutter
https://pub.dev/packages/mvvm_flutter
it's very light and easy to use check some example . its very easy to maintain ui away from business logic's
That's not the proper approach. You shouldn't split State<T>
and it's build
method.
The thing is, don't extend widgets. Compose them.
A correct way to achieve something similar is to use InheritedWidget
. These will hold you data but do nothing else. And it's children will be able to request those datas using a MyInherited.of(context)
.
You could also create a builder
. Something like :
typedef Widget MyStateBuilder(BuildContext context, MyStateState state);
class MyState extends StatefulWidget {
final MyStateState builder;
const MyState({this.builder}) : assert(builder != null);
@override
MyStateState createState() => new MyStateState();
}
class MyStateState extends State<MyState> {
String name;
@override
Widget build(BuildContext context) {
return widget.builder(context, this);
}
}
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 :)