flowchart LR D["6-axis sensor<br/>(Fake / BLE)"] -- "Stream<ImuSample><br/>100Hz" --> SP["imuSampleProvider<br/>(StreamProvider)"] SP -- "ref.listen" --> VM["MeasurementViewModel"] VM -- "state (20Hz)" --> V["Measurement screen"]
Receiving sensor data with Riverpod
1
Sensor interface
Handle the fake and the real one the same way
2
Subscribe to a Stream
StreamProvider and ref.listen
3
Measurement screen
Real-time display and saving
flowchart LR D["6-axis sensor<br/>(Fake / BLE)"] -- "Stream<ImuSample><br/>100Hz" --> SP["imuSampleProvider<br/>(StreamProvider)"] SP -- "ref.listen" --> VM["MeasurementViewModel"] VM -- "state (20Hz)" --> V["Measurement screen"]
ref.listen. Riverpod unsubscribes automaticallylib/service/imu/imu_device.dart
import 'dart:math';
// 3-axis value (x, y, z)
class Vec3 {
const Vec3(this.x, this.y, this.z);
final double x;
final double y;
final double z;
// Vector magnitude (how strong, regardless of direction)
double get magnitude => sqrt(x * x + y * y + z * z);
}
// One sample from the two 6-axis sensors (arrives at 100Hz)
// Do not override == (so Riverpod doesn't drop repeated identical values)
class ImuSample {
const ImuSample({
required this.count,
required this.acc1,
required this.gyro1,
required this.acc2,
required this.gyro2,
});
final int count; // packet number
final Vec3 acc1; // sensor 1 acceleration [g]
final Vec3 gyro1; // sensor 1 angular velocity [dps]
final Vec3 acc2; // sensor 2 acceleration [g]
final Vec3 gyro2; // sensor 2 angular velocity [dps]
}
// Interface to the 6-axis sensor. Lets the fake and the real BLE device be handled the same way
abstract interface class ImuDevice {
Stream<ImuSample> get samples; // Data arriving during measurement
Future<void> start();
Future<void> stop();
Future<void> dispose();
}ImuDevice, so screens needn’t care whichlib/service/imu/fake_imu_device.dart
import 'dart:async';
import 'dart:math';
import 'package:motion_app/service/imu/imu_device.dart';
// A fake 6-axis sensor that works without real hardware
// After start(), emits values at 100Hz that mimic a "swing" every 1.5 s
class FakeImuDevice implements ImuDevice {
final _controller = StreamController<ImuSample>.broadcast();
final _random = Random();
Timer? _timer;
int _count = 0;
@override
Stream<ImuSample> get samples => _controller.stream;
@override
Future<void> start() async {
_timer?.cancel();
_count = 0;
_timer = Timer.periodic(const Duration(milliseconds: 10), (_) {
final t = _count / 100; // elapsed seconds
// Strength of a "swing" that changes sharply 0 → 1 → 0 with a 1.5 s period
final swing = pow(sin(pi * (t % 1.5) / 1.5), 8).toDouble();
double noise() => (_random.nextDouble() - 0.5) * 4;
_controller.add(ImuSample(
count: _count,
acc1: Vec3(0, 0, 1 + 3 * swing), // 1g of gravity at rest
gyro1: Vec3(noise(), noise(), 800 * swing + noise()),
acc2: Vec3(0, 0, 1 + 2 * swing),
gyro2: Vec3(noise(), noise(), 500 * swing + noise()),
));
_count++;
});
}
@override
Future<void> stop() async {
_timer?.cancel();
_timer = null;
}
@override
Future<void> dispose() async {
await stop();
await _controller.close();
}
}broadcast() allows subscribing from multiple placeslib/provider/providers.dart
import 'package:riverpod_annotation/riverpod_annotation.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;imuSample returns a Stream, so it becomes a StreamProvider@riverpod (no keepAlive) → automatically stops the subscription once nobody uses itlib/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/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. true if saved
Future<bool> stopAndSave() async {
if (_samples.isEmpty) return false;
// Get what we need up front so ref isn't used after await
final repository = ref.read(sessionRepositoryProvider);
final device = ref.read(imuDeviceProvider);
state = state.copyWith(isMeasuring: false);
await device.stop();
// Compute the peaks (moved to the domain layer in Chapter 7)
double peakGyro1 = 0, peakGyro2 = 0, peakAcc1 = 0, peakAcc2 = 0;
for (final s in _samples) {
if (s.gyro1.magnitude > peakGyro1) peakGyro1 = s.gyro1.magnitude;
if (s.gyro2.magnitude > peakGyro2) peakGyro2 = s.gyro2.magnitude;
if (s.acc1.magnitude > peakAcc1) peakAcc1 = s.acc1.magnitude;
if (s.acc2.magnitude > peakAcc2) peakAcc2 = s.acc2.magnitude;
}
await repository.add(
userId: userId,
durationSec: _samples.length / 100, // 100Hz
sampleCount: _samples.length,
peakGyro1: peakGyro1,
peakGyro2: peakGyro2,
peakAcc1: peakAcc1,
peakAcc2: peakAcc2,
);
return true;
}
}ref.watch re-runs build and the state is lost → use listenbuild (calling it inside a method keeps adding subscriptions)stopAndSave (lines 63–70) computes the peak values, but this is a business rule. Chapter 7 moves it to the domain layerref after await, what’s needed is obtained beforehandlib/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 saved = await notifier.stopAndSave();
if (saved && context.mounted) context.pop(true);
},
)
: FilledButton.icon(
icon: const Icon(Icons.play_arrow),
label: const Text('測定開始'),
onPressed: notifier.start,
),
],
),
),
);
}
}lib/router/router.dart
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/ui/home/view/home_page.dart';
import 'package:motion_app/ui/measurement/view/measurement_page.dart';
import 'package:motion_app/ui/user_detail/view/user_detail_page.dart';
import 'package:motion_app/ui/user_list/view/user_list_page.dart';
part 'router.g.dart';
// Keep paths as constants to prevent typos in strings
abstract final class Routes {
static const home = '/';
static const users = '/users';
static String userDetail(String userId) => '/users/$userId';
static String measurement(String userId) => '/users/$userId/measure';
}
@Riverpod(keepAlive: true)
GoRouter router(Ref ref) {
return GoRouter(
initialLocation: Routes.home,
routes: [
GoRoute(
path: Routes.home,
builder: (context, state) => const HomePage(),
routes: [
GoRoute(
path: 'users', // child routes have no leading /
builder: (context, state) => const UserListPage(),
routes: [
GoRoute(
path: ':userId',
builder: (context, state) => UserDetailPage(
userId: state.pathParameters['userId']!,
),
routes: [
GoRoute(
path: 'measure',
builder: (context, state) => MeasurementPage(
userId: state.pathParameters['userId']!,
),
),
],
),
],
),
],
),
],
);
}lib/ui/user_detail/view/user_detail_page.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/ui/user_detail/view_model/user_detail_view_model.dart';
class UserDetailPage extends ConsumerWidget {
const UserDetailPage({super.key, required this.userId});
final String userId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(userDetailViewModelProvider(userId));
return Scaffold(
appBar: AppBar(title: Text(state.user?.name ?? '')),
floatingActionButton: FloatingActionButton.extended(
icon: const Icon(Icons.sensors),
label: const Text('測定する'),
onPressed: () async {
// The measurement screen returns true after saving, so reload the history
final saved = await context.push<bool>(Routes.measurement(userId));
if (saved == true) {
ref.read(userDetailViewModelProvider(userId).notifier).load();
}
},
),
body: state.isLoading
? const Center(child: CircularProgressIndicator())
: ListView(
padding: const EdgeInsets.all(16),
children: [
const Text('測定履歴'),
if (state.sessions.isEmpty) const Text('まだ測定していません'),
for (final s in state.sessions)
ListTile(
leading: const Icon(Icons.timeline),
title: Text('最大角速度 ${s.peakGyro1.toStringAsFixed(0)} / '
'${s.peakGyro2.toStringAsFixed(0)} dps'),
subtitle: Text(
'${DateFormat('yyyy/MM/dd HH:mm').format(s.recordedAt)}'
' ${s.durationSec.toStringAsFixed(1)}秒'),
),
],
),
);
}
}true, so the history is reloadedCHECK 0 / 4
Motion Note Hands-on