MVVM Design Pattern in Flutter

后端 未结 4 1008
时光说笑
时光说笑 2021-02-06 05:26

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

4条回答
  •  走了就别回头了
    2021-02-06 06:16

    The mvvm package, A Flutter MVVM (Model-View-ViewModel) implementation.

    import 'package:flutter/widgets.dart';
    import 'package:mvvm/mvvm.dart';
    import 'dart:async';
    
    // ViewModel
    class Demo1ViewModel extends ViewModel {
    
      Demo1ViewModel() {
          // define bindable property
          propertyValue(#time, initial: "");
          // timer
          start();
      }
    
      start() {
          Timer.periodic(const Duration(seconds: 1), (_) {
            var now = DateTime.now();
            // call setValue
            setValue(#time, "${now.hour}:${now.minute}:${now.second}");
          });
      }
    }
    
    // View
    class Demo1 extends View {
      Demo1() : super(Demo1ViewModel());
    
      @override
      Widget buildCore(BuildContext context) {
        return Container(
            margin: EdgeInsets.symmetric(vertical: 100),
            padding: EdgeInsets.all(40),
    
            // binding
            child: $.watchFor(#time, 
                builder: $.builder1((t) => 
                  Text(t, textDirection: TextDirection.ltr))));
      }
    }
    
    // run
    void main() => runApp(Demo1());
    

    full example

提交回复
热议问题