Mvvm Design Pattern In Flutter
Solution 1:
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:
classViewModelProviderextendsInheritedWidget {
final ViewModel viewModel;
ViewModelProvider({Key key, @requiredthis.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 :)
Solution 2:
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);
classMyStateextendsStatefulWidget {
final MyStateState builder;
const MyState({this.builder}) : assert(builder != null);
@override
MyStateState createState() => newMyStateState();
}
classMyStateStateextendsState<MyState> {
String name;
@override
Widget build(BuildContext context) {
return widget.builder(context, this);
}
}
Solution 3:
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
Solution 4:
The mvvm package, A Flutter MVVM (Model-View-ViewModel) implementation.
import'package:flutter/widgets.dart';
import'package:mvvm/mvvm.dart';
import'dart:async';
// ViewModelclassDemo1ViewModelextendsViewModel {
Demo1ViewModel() {
// define bindable property
propertyValue<String>(#time, initial: "");
// timerstart();
}
start() {
Timer.periodic(constDuration(seconds: 1), (_) {
var now = DateTime.now();
// call setValue
setValue<String>(#time, "${now.hour}:${now.minute}:${now.second}");
});
}
}
// ViewclassDemo1extendsView<Demo1ViewModel> {
Demo1() : super(Demo1ViewModel());
@overrideWidgetbuildCore(BuildContext context) {
returnContainer(
margin: EdgeInsets.symmetric(vertical: 100),
padding: EdgeInsets.all(40),
// bindingchild: $.watchFor(#time,
builder: $.builder1((t) =>Text(t, textDirection: TextDirection.ltr))));
}
}
// runvoidmain() => runApp(Demo1());
Post a Comment for "Mvvm Design Pattern In Flutter"