7. Domain Layer

Separating business rules from the UI and the DB

Goals of this chapter

1

Write the rules

Computing peaks and detecting personal bests

2

Create a UseCase

A business operation combining analysis and saving

3

Slim down the ViewModel

Move the Chapter 6 computation out

What is the domain layer?

UI layer — how to show it

Display the measured value in large text

Domain layer — what to do

Compute the peak angular velocity and decide if it’s a personal best

Data layer — where to keep it

Save the session to SQLite

  • Rules that would be the same with paper and a stopwatch = the domain
  • Changing the screen design or the DB doesn’t change the rules

Analysis rules (pure computation)

lib/domain/motion_analyzer.dart
import 'package:motion_app/service/imu/imu_device.dart';

// Summary of one measurement
class MotionSummary {
  const MotionSummary({
    required this.durationSec,
    required this.sampleCount,
    required this.peakGyro1,
    required this.peakGyro2,
    required this.peakAcc1,
    required this.peakAcc2,
  });

  final double durationSec;
  final int sampleCount;
  final double peakGyro1; // [dps]
  final double peakGyro2;
  final double peakAcc1; // [g]
  final double peakAcc2;
}

// Motion analysis rules. Pure computation that depends on neither the UI nor the DB
abstract final class MotionAnalyzer {
  static const double sampleRateHz = 100; // The sensor sends data at 100Hz

  static MotionSummary summarize(List<ImuSample> samples) {
    double peak(double Function(ImuSample s) value) =>
        samples.fold(0, (max, s) => value(s) > max ? value(s) : max);
    return MotionSummary(
      durationSec: samples.length / sampleRateHz,
      sampleCount: samples.length,
      peakGyro1: peak((s) => s.gyro1.magnitude),
      peakGyro2: peak((s) => s.gyro2.magnitude),
      peakAcc1: peak((s) => s.acc1.magnitude),
      peakAcc2: peak((s) => s.acc2.magnitude),
    );
  }

  // Personal best = sensor 1's peak angular velocity exceeds every previous record
  static bool isPersonalBest(double peakGyro1, List<double> pastPeaks) =>
      pastPeaks.every((past) => peakGyro1 > past);
}
  • Depends on neither Flutter nor the DB → easy to unit-test (Chapter 11)
  • The computation that was in the ViewModel in Chapter 6 has moved here

UseCase

lib/domain/save_session_usecase.dart
import 'package:motion_app/domain/motion_analyzer.dart';
import 'package:motion_app/repository/session/session_repository.dart';
import 'package:motion_app/service/imu/imu_device.dart';

class SaveSessionResult {
  const SaveSessionResult({required this.summary, required this.isPersonalBest});

  final MotionSummary summary;
  final bool isPersonalBest;
}

// Analyze the measurement data, check for a personal best, and save (a business operation combining rules + saving)
class SaveSessionUseCase {
  SaveSessionUseCase({required SessionRepository sessionRepository})
      : _sessions = sessionRepository;

  final SessionRepository _sessions;

  Future<SaveSessionResult> call({
    required String userId,
    required List<ImuSample> samples,
  }) async {
    final summary = MotionAnalyzer.summarize(samples);
    final history = await _sessions.getByUser(userId);
    final isBest = MotionAnalyzer.isPersonalBest(
      summary.peakGyro1,
      [for (final s in history) s.peakGyro1],
    );
    await _sessions.add(
      userId: userId,
      durationSec: summary.durationSec,
      sampleCount: summary.sampleCount,
      peakGyro1: summary.peakGyro1,
      peakGyro2: summary.peakGyro2,
      peakAcc1: summary.peakAcc1,
      peakAcc2: summary.peakAcc2,
    );
    return SaveSessionResult(summary: summary, isPersonalBest: isBest);
  }
}

When to create a UseCase

  • Create one: it contains rules (computation/decisions) / spans multiple Repositories / is used from two or more places
  • Don’t: it would just call a Repository once (you’d only add pass-through classes)

Register it as a Provider

lib/provider/providers.dart
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/domain/save_session_usecase.dart';
import 'package:motion_app/infrastructure/database/app_database.dart';
import 'package:motion_app/repository/session/session_repository.dart';
import 'package:motion_app/repository/user/user_repository.dart';
import 'package:motion_app/service/imu/fake_imu_device.dart';
import 'package:motion_app/service/imu/imu_device.dart';

part 'providers.g.dart';

@Riverpod(keepAlive: true)
AppDatabase appDatabase(Ref ref) {
  final db = AppDatabase();
  ref.onDispose(db.close);
  return db;
}

@Riverpod(keepAlive: true)
UserRepository userRepository(Ref ref) =>
    UserRepository(ref.watch(appDatabaseProvider));

@Riverpod(keepAlive: true)
SessionRepository sessionRepository(Ref ref) =>
    SessionRepository(ref.watch(appDatabaseProvider));

// 6-axis sensor. Uses the fake for now (replaced with BLE in Chapter 8)
@Riverpod(keepAlive: true)
ImuDevice imuDevice(Ref ref) {
  final device = FakeImuDevice();
  ref.onDispose(device.dispose);
  return device;
}

// Make sensor data subscribable through Riverpod
@riverpod
Stream<ImuSample> imuSample(Ref ref) => ref.watch(imuDeviceProvider).samples;

@Riverpod(keepAlive: true)
SaveSessionUseCase saveSessionUseCase(Ref ref) => SaveSessionUseCase(
      sessionRepository: ref.watch(sessionRepositoryProvider),
    );

Slim down the ViewModel

lib/ui/measurement/view_model/measurement_view_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/domain/save_session_usecase.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/service/imu/imu_device.dart';

part 'measurement_view_model.g.dart';
part 'measurement_view_model.freezed.dart';

@freezed
abstract class MeasurementState with _$MeasurementState {
  const factory MeasurementState({
    @Default(false) bool isMeasuring,
    @Default(0) double gyro1, // sensor 1 current angular velocity magnitude [dps]
    @Default(0) double gyro2, // sensor 2 current angular velocity magnitude [dps]
    @Default(0) int sampleCount,
  }) = _MeasurementState;
}

@riverpod
class MeasurementViewModel extends _$MeasurementViewModel {
  final _samples = <ImuSample>[]; // all samples received during the measurement

  @override
  MeasurementState build(String userId) {
    // Receive sensor data. Riverpod unsubscribes automatically
    ref.listen(imuSampleProvider, (previous, next) {
      final sample = next.value;
      if (sample != null) _onSample(sample);
    });
    // Stop measuring when the screen closes (ref can't be used inside onDispose, so get it first)
    final device = ref.read(imuDeviceProvider);
    ref.onDispose(device.stop);
    return const MeasurementState();
  }

  void _onSample(ImuSample sample) {
    if (!state.isMeasuring) return;
    _samples.add(sample);
    // Redrawing the screen at 100Hz is heavy, so update the state only once every 5 samples (20Hz)
    if (_samples.length % 5 != 0) return;
    state = state.copyWith(
      gyro1: sample.gyro1.magnitude,
      gyro2: sample.gyro2.magnitude,
      sampleCount: _samples.length,
    );
  }

  Future<void> start() async {
    _samples.clear();
    state = const MeasurementState(isMeasuring: true);
    await ref.read(imuDeviceProvider).start();
  }

  // Stop and save. null if there is no data
  Future<SaveSessionResult?> stopAndSave() async {
    if (_samples.isEmpty) return null;
    // Get what we need up front so ref isn't used after await
    final saveSession = ref.read(saveSessionUseCaseProvider);
    final device = ref.read(imuDeviceProvider);
    state = state.copyWith(isMeasuring: false);
    await device.stop();
    // Analysis (peaks, personal-best check) and saving are left to the UseCase
    return saveSession(userId: userId, samples: List.of(_samples));
  }
}
  • The ViewModel now just calls the UseCase and returns the result

Announcing a personal best

lib/ui/measurement/view/measurement_page.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/ui/measurement/view_model/measurement_view_model.dart';

class MeasurementPage extends ConsumerWidget {
  const MeasurementPage({super.key, required this.userId});

  final String userId;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(measurementViewModelProvider(userId));
    final notifier = ref.read(measurementViewModelProvider(userId).notifier);
    final big = Theme.of(context).textTheme.displaySmall;

    return Scaffold(
      appBar: AppBar(title: const Text('測定')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('センサ1  ${state.gyro1.toStringAsFixed(0)} dps', style: big),
            Text('センサ2  ${state.gyro2.toStringAsFixed(0)} dps', style: big),
            const SizedBox(height: 8),
            Text('${(state.sampleCount / 100).toStringAsFixed(1)} 秒'),
            const SizedBox(height: 32),
            state.isMeasuring
                ? FilledButton.icon(
                    icon: const Icon(Icons.stop),
                    label: const Text('停止して保存'),
                    onPressed: () async {
                      final result = await notifier.stopAndSave();
                      if (result == null || !context.mounted) return;
                      if (result.isPersonalBest) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('自己ベスト更新!')),
                        );
                      }
                      context.pop(true);
                    },
                  )
                : FilledButton.icon(
                    icon: const Icon(Icons.play_arrow),
                    label: const Text('測定開始'),
                    onPressed: notifier.start,
                  ),
          ],
        ),
      ),
    );
  }
}
  • Even if you call context.pop(true) right after showSnackBar, the SnackBar stays visible on the previous screen (next slide)

ScaffoldMessenger vs Fluttertoast: pros

Two common ways to show a short message are the built-in ScaffoldMessenger (SnackBar) and the Fluttertoast package.

ScaffoldMessenger (SnackBar)

  • Built into Flutter. No extra package needed
  • Same look and behaviour on every OS. Theme colours apply
  • Can have a button such as “Undo” (SnackBarAction)
  • Owned by MaterialApp, so it stays even when the screen closes
  • Can be checked in widget tests with find.text(...)

Fluttertoast

  • Shown with just Fluttertoast.showToast(msg: ...)
  • Callable from anywhere, without a context
  • Looks like a native Toast on Android / iOS

ScaffoldMessenger vs Fluttertoast: cons

ScaffoldMessenger (SnackBar)

  • Needs a context. Can’t be shown directly from a ViewModel (after await, check context.mounted)
  • Appears at the bottom, so it may overlap bottom buttons
  • Consecutive messages queue up (use hideCurrentSnackBar() to switch immediately)

Fluttertoast

  • Requires adding a package
  • showToast works only on Android / iOS / Web. Not shown on macOS / Windows (FToast works but needs a context)
  • No buttons. On Android 11+ colour settings etc. have no effect
  • Hard to verify in widget tests. UI code tends to creep into the ViewModel

This course uses SnackBar

  • We also run on macOS, so we use SnackBar, which behaves the same on every OS
  • The View shows it; the ViewModel only returns the result “is it a personal best” → no UI code in the ViewModel tests
  • Consider Fluttertoast for Android/iOS-only apps when you want a lightweight notice from a place without a context

Checkpoint

CHECK 0 / 3