[Open source] There may be only one Flutter MVVM distance from web-side development to app-side development

As a developer, choosing a handy development framework is especially important for improving productivity and a pleasant coding experience. In the past two years, I have shifted from back-end development to web-side development, and the focus of development has also changed from the previous data level to the current presentation level. There are many excellent development frameworks on the web side. Vue.js, React, Angular, Ember.js, etc. are all deeply loved by the majority of web-side development, and they are all very good choices. Choose from many development frameworks. Angular.

 

Angular

I only choose Angular because many concepts in Angular are not unfamiliar to a former back-end developer, and even have a bit of kindness, Module, Dependency Injection, Guard, Provider, etc., each of which is so familiar . However, in addition to these, it is her elegant data binding function that attracts me the most. Angular's data binding "syntax" is very concise and clear, even a novice can understand it at a glance. It is also very convenient to use, almost like manipulating js native objects, simple and easy to understand.

Data Binding in Angular

<h2>{{ title }}</h2>
<div *ngIf="status === 1">hello world!</div>

Data binding is the core of Angular, it can greatly simplify the complexity of the developer's control of the page DOM tree, so that we can be freed from the original complex page manipulation. In fact, not only Angular, but also Vue.js, React, Ember.js and other frameworks have similar implementations. The industry calls this mode of driving view changes through data binding MVVM( https://zh.wikipedia.org/wiki /MVVM ).

 

Flutter

I am learning Flutter recently. To build a Flutter app, most of the work is to build various widget trees (UI). The widget tree structure is actually very similar to the DOM tree in HTML, which is not difficult for web developers to understand. But after getting started, you will find that the manipulation of the widget tree seems to return to the getElementById era in html, even a very simple widget change operation requires developers to manually manage a lot of logic code. If you encounter a complex scenario where multiple widgets are changed, the developer must be faced with a heavier workload. If I want to write Flutter code in this way all day long, it is estimated that I can't last for three days, which is unacceptable for a lazy Angular developer like me! ~

Implementing widget changes in Flutter probably requires the following steps

  1. Create a StatefulWidgetclass that inherits from
  2. Create Widgeta state class
  3. Write widget change logic and finally use setState() to update to UI

 

Flutter MVVM

Since the widget tree in Flutter is very similar to the dom tree in html, and the major web frameworks can use data binding (MVVM) to simplify the control operation of the can Flutter be like a web framework? What about simplifying the manipulation of the widget tree through data binding (MVVM)? With this question in mind, I tried to implement a Flutter MVVM in the early morning before my second dog woke up.

 

It can probably help you solve the following problems in the development process of Flutter

  • I have difficulty choosing, and I don't want to choose between StatelessWidget or StatefulWidget.
  • I'm a lazy person, when I change the widget (UI display), I don't want to manually setState every time
  • I have a habit of cleanliness, and when I develop features, I want the functions of each link to be more clear.
  • Most importantly, I wish I could be freed from the complex control of the widget tree structure.

 

 

What? Having said that, why not look at a few lines of code?

 

Using her in the project requires the following steps

1. Add dependencies to the project

Find the pubspec.yamlfile , and dependenciesadd the following to the section

mvvm: ^0.1.3

 

2. Add package reference

add in code page

import 'package:mvvm/mvvm.dart';

 

3. Create a ViewModel (ViewModel)

The view model class needs to inherit from the ViewModelclass and use the propertyValuemethod in the constructor to create properties that need binding support

import 'package:mvvm/mvvm.dart';
import 'dart:async';

// define ViewModel
class Demo1ViewModel extends ViewModel {
  Demo1ViewModel() {
    // define bindable
    propertyValue<DateTime>("time", initial: DateTime.now());
    // start timer
    start();
  }

  start() {
    Timer.periodic(const Duration(seconds: 1), (_) {
      // call setValue
      setValue<DateTime>("time", DateTime.now());
    });
  }
}

propertyValueThere are also similar methods of creating properties propertyAdaptive. propertyAsyncFor usage, see the example in the source code

 

4. Create a View (View)

The view class needs to inherit from the Viewclass and specify to use the view model just created. Override the Widget BuildCore(BuildContext)method and use the $(ViewContext) and $Model(ViewModel) helper properties inside the method to build the viewWidget

import 'package:mvvm/mvvm.dart';
import 'package:flutter/widgets.dart';

// define View
class Demo1 extends View<Demo1ViewModel> {

  // call super
  Demo1() : super(Demo1ViewModel());

  @override
  Widget buildCore(BuildContext context) {
    return Container(
        margin: EdgeInsets.symmetric(vertical: 100),
        padding: EdgeInsets.all(40),

        child: Column(children: [
          // binding
          $.watchFor("time",
              builder: $.builder1((t) => Text(
                  "${t.hour}:${t.minute}:${t.second}",
                  textDirection: TextDirection.ltr))),
          // binding
          $.$ifFor("time",
              builder: $.builder0(
                  () => Text("hello world!", textDirection: TextDirection.ltr)),
              valueHandle: (t) => t.second % 2 == 0)
        ]));
  }
}

$.watchFor(..)Similar to $.watch(..), $.if(..), $.cond(..), , $.condFor(..), $.switch(..), $.switchFor(..)etc., and more can be expanded in the future. For usage, please refer to the example in the source code

 

5. Application View

// run
void main() => runApp(Demo1());

 

Do the friends who develop on the web side feel that the $.watchFor(..)grammar $.ifFor(..)can be more friendly? In fact, these are similar implementations of the data binding syntax mentioned earlier.

In this MVVM implementation of Flutter, we split the original mixed widget tree and logical data into two parts: view logic (ViewModel) and view display (View), and establish an association between the two through data binding , and finally use the view logic (ViewModel) combined with the data binder to drive the view (widget tree) changes. It can be seen in the example that we can focus more on the view display in the Viewclass . All data operations related to the view logic are ViewModelmanaged by , and there are clear divisions in responsibilities.

 

finally

The MVVM pattern has a long history, has been applied in many presentation layer frameworks, and is deeply loved by developers. The implementation of this Flutter is still very simple, and there is still a lot of room for expansion, but I believe she can be more and more perfect, and I hope she can bring you the joy of coding, thank you for reading!

 

Can she shorten the distance between you and app development? Come and try it, looking forward to your answer. .

 

Related Links

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324124267&siteId=291194637