A Flutter MVVM (Model-View-ViewModel) implementation

237 views
Skip to first unread message

unicreators

unread,
Sep 7, 2019, 4:53:56 AM9/7/19
to Flutter Development (flutter-dev)

A Flutter MVVM (Model-View-ViewModel) implementation. It uses property-based data binding to establish a connection between the ViewModel and the View, and drives the View changes through the ViewModel.





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

// ViewModel
class Demo1ViewModel extends ViewModel {

  Demo1ViewModel() {
      // define bindable property
      propertyValue<String>(#time, initial: "");
      // timer
      start();
  }

  start() {
      Timer.periodic(const Duration(seconds: 1), (_) {
        var now = DateTime.now();
        // call setValue
        setValue<String>(#time, "${now.hour}:${now.minute}:${now.second}");
      });
  }
}

// View
class Demo1 extends View<Demo1ViewModel> {
  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());
Reply all
Reply to author
Forward
0 new messages