Implement Model-View-ViewModel architecture ⚙⛓ #760
rutvik11062000
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Steps to implement MVVM ✔:
Aim: The main idea to implement this is to separate the UI code and the functions from the file.
Assumption: working on
xzypage.dart
Make a new file in
/view_model/page_view_model/
foldera. Name the file to "xyz_view_model.dart".
b. Make a class extends BaseModel.
Eg.
class XYZViewModel extends BaseModel{}
Register XYZViewModel in
locator.dart
as a factory.a. Rename the file to xyz_view.dart
b. If the file is a stateful widget make it stateless.(We will be maintaining state through XYZViewModel.dart)
c. Wrap the widget (i.e scaffold) that we're returning with BaseView.
return BaseView<XYZViewModel>( builder: (context, model, child) => Scaffold(), ),
d. Import the files that are required.
Congrats🎉, connection of UI (xyz_view.dart) and function file (xyz_view_model.dart) is done at this point.
How to use this Architecture?
Know about Getters and Setters:
a. Make setters for only those variables which are going to be exposed in the UI (xyz_view.dart) file.
b. Setter function must start with "set" eg. setSomeVariable().
Use notifyListeners():
a. Similar to setState() where we update some variable value.
b. use it wisely as it will re-render the entire widget. Use it only when there is change in the variables which are exposed in the UI file.
Don't make isLoading type of variable to keep track of loading state.
a. Use setState(ViewState.idle) or setState(ViewState.busy).
b. To use the state in the UI file check
model.state
For the template / example implementation see this PR changes
Beta Was this translation helpful? Give feedback.
All reactions