Flutter MVVM Application Architecture
Each year I try to learn a new language, framework or technology. This practice encourages me to continuously learn new skills and be a newbie again. This year, I’ve spent the past few months working on a mobile client for Docket . While the mobile web UI works well enough, I wanted to see if the UX could be smoother with a native application. I’ve never done any mobile development and this felt like a great opportunity for me to learn. I chose to go with Dart and Flutter for this exercise. Flutter’s goals are to provide a framework to build ahead of time compiled multi-platform applications from a single code base. This approach differs from technologies like react-native and electron in that there is no JavaScript code or engine present. Both the cross-platform build targets and native compilation were exciting to me. I have limited experience with both and would be learning a ton from this project.
Flutter is built by Google, and written in Dart (also built by google). Dart provides a type-safe and null-safe language with simple and safe concurrency primitives (async/await
and isolates
which are analogous to threads). While I’m generally skeptical of building on top of Google projects, I decided that if & when Google blows Flutter & Dart up I won’t have lost much. I’ve found Dart to be an excellent language.
Flutter is only a UI toolkit
I learned pretty quickly that Flutter is only a UI toolkit. Much like React, Flutter does not provide direction on how to structure your application. Instead Flutter assumes you’ll bring your own application architecture to manage local persistent state and do network calls.
Doing it the hard way
While there are several stable libraries that provide structure to Flutter applications, I wanted to use the smallest number of libraries possible. This would of course take longer and be more work, but one of my goals was to learn and building Docket ‘the hard way’ would force me to learn more of the basics. I did use provider to act as a gateway between the ‘application logic’ and Flutter. In addition to provider, I used a handful of other libraries for the drag and drop interactions, persistent localstorage, and task ‘mentions’.
My goals for the functionality of the mobile client were:
- Have similar UX to what the web app currently has.
- Support read operations when there is no network connection.
- Perform most sync operations behind the scenes but also provide ‘drag to refresh’.
Minimally viable architecture
After a failed design that attempted to normalize and de-duplicate data shared between views with an ORM like interface, my next pass looked like:
- lib/components
Contained reusable UI widgets. These widgets could use providers directly to create side-effects.
- lib/models
contained the entities in the application including factory methods to create entities from server responses. Early on I chose to make the local database format the same as the server API response. This worked out well and is an approach I would recommend for others.
- lib/providers
This directory contained the logic to read from the local database, make API requests, and prepare data needed by each screen.
- lib/screens
Contains the logic for each screen. In this first approach the screens contained a non-trivial amount of application logic.
While I was able to make an application that ‘worked’ with this design, it had several problems:
- Because I had made providers for each ‘kind’ of object, I didn’t have a good place to put loading and transformation logic that was specific to a single view. This resulted in verbose UI widgets that contained too much application logic.
- Testing the providers was straightforward, but testing all the logic embedded in the ‘screens’ was not. I spent a good amount of time playing whack-a-bug as I added features due to a lack of tests.
- Building out background sync and offline reads was challenging as my providers got complicated and bloated.
After doing more reading on Flutter application architectures I came across the MVVM pattern.
MVVM and ViewModels to the rescue
The MVVM (Model, View, ViewModel) pattern is similar to the MVC (Model, View, Controller) pattern I’ve used many times in server applications. In a Flutter context, Flutter Widgets form the View
. My ViewModel
classes would absorb most of the ‘provider’ logic I had built, and I would keep using my existing Model
classes.
Each ‘screen’ would get its own ViewModel, and in turn each ViewModel would have methods to handle the actions for the view, fetch data from the local database, do API requests to fetch data. ViewModels use the provider
library to signal when a screen needs to be re-rendered. The stripped down ViewModel for the today screen looks like:
- import 'package:flutter/material.dart';
- import 'package:docket/actions.dart' as actions;
- import 'package:docket/database.dart';
- import 'package:docket/models/project.dart';
- import 'package:docket/models/task.dart';
- import 'package:docket/components/tasksorter.dart';
- import 'package:docket/providers/session.dart';
- import 'package:docket/formatters.dart' as formatters;
- class TodayViewModel extends ChangeNotifier {
- late LocalDatabase _database;
- SessionProvider? session;
- /// Whether data is being refreshed from the server or local cache.
- bool _loading = false;
- // Whether we're doing a background reload.
- bool _silentLoading = false;
- /// Task list for the day/evening
- List<TaskSortMetadata> _taskLists = [];
- TodayViewModel(LocalDatabase database, this.session) {
- _taskLists = [];
- _database = database;
- _database.today.addListener(listener);
- }
- @override
- void dispose() {
- _database.today.removeListener(listener);
- super.dispose();
- }
- void listener() {
- loadData();
- }
- bool get loading => _loading && !_silentLoading;
- bool get loadError => _loadError;
- List<TaskSortMetadata> get taskLists => _taskLists;
- setSession(SessionProvider value) {
- session = value;
- }
- // Load data from the local database or refresh from server.
- Future<void> loadData() async {
- var taskView = await _database.today.get();
- if (taskView.isEmpty == false) {
- _buildTaskLists(taskView);
- }
- if (!_loading && taskView.isEmpty) {
- return refresh();
- }
- if (!_loading && !_database.today.isFresh()) {
- await refreshTasks();
- }
- }
- /// Refresh tasks from server state. Does not use loading
- /// state.
- Future<void> refreshTasks() async {
- _loading = _silentLoading = true;
- var taskView = await actions.fetchTodayTasks(session!.apiToken);
- _database.today.set(taskView);
- _loading = _silentLoading = false;
- _buildTaskLists(taskView);
- }
- /// Refresh from the server with loading state
- Future<void> refresh() async {
- _loading = true;
- await Future.wait([
- actions.fetchTodayTasks(session!.apiToken),
- actions.fetchProjects(session!.apiToken),
- ]).then((results) {
- var tasksView = results[0] as TaskViewData;
- var projects = results[1] as List<Project>;
- return Future.wait([
- _database.projectMap.replace(projects),
- _database.today.set(tasksView),
- ]).then((results) {
- _buildTaskLists(tasksView);
- });
- });
- }
- void _buildTaskLists(TaskViewData data) {
- // truncated for brevity
- }
- /// Reorder a task based on the protocol defined by
- /// the drag_and_drop_lists package.
- Future<void> reorderTask(int oldItemIndex, int oldListIndex, int newItemIndex, int newListIndex) async {
- var task = _taskLists[oldListIndex].tasks[oldItemIndex];
- // Get the changes that need to be made on the server.
- var updates = _taskLists[newListIndex].onReceive(task, newItemIndex);
- // Update local state assuming server will be ok.
- _taskLists[oldListIndex].tasks.removeAt(oldItemIndex);
- _taskLists[newListIndex].tasks.insert(newItemIndex, task);
- // Update the moved task and reload from server async
- await actions.moveTask(session!.apiToken, task, updates);
- _database.expireTask(task);
- }
- }
While this excerpt doesn’t include all of the logic it shows the data fetch and background refresh features that were challenging to build with general purpose providers. I decided to put ViewModels into their own directory – lib/viewmodel
.
Testing ViewModels
Another benefit of adopting the ViewModel pattern is ease of testing. Because ViewModels are basic Dart objects they are trivial to write tests for. Here are some tests for the today view model loading data.
- import 'dart:convert';
- import 'dart:io';
- import 'package:flutter/material.dart';
- import 'package:flutter_test/flutter_test.dart';
- import 'package:http/http.dart';
- import 'package:http/testing.dart';
- import 'package:docket/actions.dart' as actions;
- import 'package:docket/formatters.dart' as formatters;
- import 'package:docket/database.dart';
- import 'package:docket/models/task.dart';
- import 'package:docket/models/project.dart';
- import 'package:docket/providers/session.dart';
- import 'package:docket/viewmodel/today.dart';
- void main() {
- TestWidgetsFlutterBinding.ensureInitialized();
- var today = DateUtils.dateOnly(DateTime.now());
- var file = File('test_resources/tasks_today.json');
- final tasksTodayResponseFixture = file.readAsStringSync().replaceAll('__TODAY__', formatters.dateString(today));
- file = File('test_resources/project_list.json');
- final projectListResponseFixture = file.readAsStringSync();
- group('$TodayViewModel', () {
- var db = LocalDatabase(inTest: true);
- var session = SessionProvider(db, token: 'api-token');
- setUp(() async {
- await db.today.clear();
- });
- test('loadData() refreshes from server', () async {
- // Stub network requests to return fixture data.
- actions.client = MockClient((request) async {
- if (request.url.path == '/tasks/today') {
- return Response(tasksTodayResponseFixture, 200);
- }
- if (request.url.path == '/projects') {
- return Response(projectListResponseFixture, 200);
- }
- throw "Unexpected request to ${request.url.path}";
- });
- var viewmodel = TodayViewModel(db, session);
- expect(viewmodel.taskLists.length, equals(0));
- await viewmodel.loadData();
- expect(viewmodel.taskLists.length, equals(2));
- // Check today
- expect(viewmodel.taskLists[0].title, isNull);
- expect(viewmodel.taskLists[0].showButton, isNull);
- // Check evening
- expect(viewmodel.taskLists[1].title, equals('This Evening'));
- expect(viewmodel.taskLists[1].showButton, isTrue);
- });
- });
- }
In this test I’m using MockClient
to stub out any network requests that are made. I much prefer this path over using generated mock objects as it ensures more of the code I wrote is working than mocks would. I have really been enjoying how expressive and easy to read and write flutter’s testing libraries are.
While I don’t have a ton of experience with Flutter, I’ve greatly enjoyed the process of learning both Dart and Flutter. The development experience is really smooth and well built. Tools like linting, testing and running a development debugger are all built-in and work quite well. If you’re looking to build a cross-platform UI application I would recommend giving Flutter a try.
If you’re interested in reading more of the code, the full source is on GitHub
There are no comments, be the first!