Separating business rules from the UI and the DB
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
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
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);
}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);
}
}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),
);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));
}
}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,
),
],
),
),
);
}
}context.pop(true) right after showSnackBar, the SnackBar stays visible on the previous screen (next slide)Two common ways to show a short message are the built-in ScaffoldMessenger (SnackBar) and the Fluttertoast package.
ScaffoldMessenger (SnackBar)
SnackBarAction)MaterialApp, so it stays even when the screen closesfind.text(...)Fluttertoast
Fluttertoast.showToast(msg: ...)contextScaffoldMessenger (SnackBar)
context. Can’t be shown directly from a ViewModel (after await, check context.mounted)hideCurrentSnackBar() to switch immediately)Fluttertoast
showToast works only on Android / iOS / Web. Not shown on macOS / Windows (FToast works but needs a context)contextCHECK 0 / 3
Motion Note Hands-on