A Flutter MVVM (Model-View-ViewModel) implementation

unicreators
1 min readSep 7, 2019

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<String>(#time,
builder: $.builder1((t) =>
Text(t, textDirection: TextDirection.ltr))));
}
}

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

--

--