9. Auto-connect & Connection State

Reconnect to the last device automatically and read its state from any screen

Goals of this chapter

1

Remember the device

Save the chosen BLE device ID in shared_preferences

2

Connect automatically

Connect on launch and reconnect when dropped

3

From any screen

Read connection state and battery level with ref.watch

Overall flow

flowchart LR
  P[("shared_preferences<br/>bleDeviceId")] --> SEL["selectedBleDevice<br/>ID to use"]
  SEL --> DEV["imuDevice<br/>Fake / BLE"]
  DEV --> CON["imuConnection<br/>connection, battery"]
  CON -- "ref.watch" --> H["Home"]
  CON -- "ref.watch" --> M["Measurement"]
  CON -- "ref.watch" --> D["Device"]

  • If the saved ID is empty, use the fake sensor (no BLE communication); if present, connect to that device on launch
  • Connecting and reading the battery happen only inside imuConnection. Screens just read

Add the package

flutter pub add shared_preferences

SharedPreferencesAsync

await on every read. Fine for values read only occasionally

SharedPreferencesWithCache

Loads once at startup, then reads without await. Used in this chapter

The old SharedPreferences.getInstance()

The long-standing API is announced to be deprecated in the future. For new code, use Async / WithCache.

Reading the battery level (an assumption of this course)

Item Details
Service Standard Battery Service 0x180F
Characteristic Battery Level 0x2A19 (read; 1 byte, 0–100)

If the firmware has no Battery Service

Reading fails and the battery level isn’t shown (connecting and measuring are unaffected). Add the Battery Service to the firmware to display it.

The Repository that saves it

lib/repository/settings/device_settings_repository.dart
import 'package:shared_preferences/shared_preferences.dart';

// Settings stored on the device (BLE device ID of the sensor to use)
// Small values that don't warrant the DB are stored in shared_preferences
class DeviceSettingsRepository {
  DeviceSettingsRepository(this._prefs);

  final SharedPreferencesWithCache _prefs;
  static const deviceIdKey = 'bleDeviceId';

  // null if nothing is saved (= use the fake sensor)
  String? get deviceId => _prefs.getString(deviceIdKey);

  Future<void> saveDeviceId(String? deviceId) => deviceId == null
      ? _prefs.remove(deviceIdKey)
      : _prefs.setString(deviceIdKey, deviceId);
}
  • Small settings that don’t warrant the DB (drift) are saved in shared_preferences
  • Reads and writes are bundled in a Repository (same idea as Chapter 5)

Load before startup (main)

lib/main.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/app.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/repository/settings/device_settings_repository.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized(); // Required when awaiting before runApp
  // Load saved settings before startup → afterwards readable without await
  final prefs = await SharedPreferencesWithCache.create(
    cacheOptions: const SharedPreferencesWithCacheOptions(
      allowList: {DeviceSettingsRepository.deviceIdKey},
    ),
  );
  runApp(ProviderScope(
    overrides: [sharedPreferencesProvider.overrideWithValue(prefs)],
    child: const App(),
  ));
}
  • Only keys listed in allowList can be read/written (catches key typos)
  • overrideWithValue passes the loaded instance to the Provider

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/settings/device_settings_repository.dart';
import 'package:motion_app/repository/user/user_repository.dart';
import 'package:motion_app/service/imu/ble_scanner.dart';
import 'package:motion_app/service/imu/dual_gy521_device.dart';
import 'package:motion_app/service/imu/fake_imu_device.dart';
import 'package:motion_app/service/imu/imu_device.dart';
import 'package:shared_preferences/shared_preferences.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));

// Overridden with the instance loaded in main (throws so a missing override is noticed immediately)
@Riverpod(keepAlive: true)
SharedPreferencesWithCache sharedPreferences(Ref ref) =>
    throw UnimplementedError('main で overrideWithValue すること');

@Riverpod(keepAlive: true)
DeviceSettingsRepository deviceSettingsRepository(Ref ref) =>
    DeviceSettingsRepository(ref.watch(sharedPreferencesProvider));

// BLE device ID of the sensor to use. null means use the fake sensor
// The chosen ID is saved, and the app connects to that device on the next launch too
@Riverpod(keepAlive: true)
class SelectedBleDevice extends _$SelectedBleDevice {
  @override
  String? build() => ref.watch(deviceSettingsRepositoryProvider).deviceId;

  Future<void> select(String? deviceId) async {
    state = deviceId;
    await ref.read(deviceSettingsRepositoryProvider).saveDeviceId(deviceId);
  }
}

// 6-axis sensor. BLE if a device is selected, otherwise the fake
@Riverpod(keepAlive: true)
ImuDevice imuDevice(Ref ref) {
  final deviceId = ref.watch(selectedBleDeviceProvider);
  final ImuDevice device =
      deviceId == null ? FakeImuDevice() : DualGy521Device(deviceId);
  ref.onDispose(device.dispose);
  return device;
}

@Riverpod(keepAlive: true)
BleScanner bleScanner(Ref ref) => BleScanner();

// 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),
    );
  • sharedPreferencesProvider is overridden in main (forgetting causes an error)
  • The initial value is the saved ID → imuDevice is that device from the start

Add connecting to the sensor interface

lib/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
  Stream<bool> get connectionChanges; // Changes between connected (true) and disconnected (false)
  Future<void> connect();
  Future<void> disconnect();
  Future<int?> readBatteryLevel(); // battery level [%]. null if unreadable
  Future<void> start();
  Future<void> stop();
  Future<void> dispose();
}
  • Until now we connected inside start() → you couldn’t tell whether it connects until measuring started
  • Separate connecting (connect) from measuring (start)

The fake sensor

lib/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 _connection = StreamController<bool>.broadcast();
  final _random = Random();
  Timer? _timer;
  int _count = 0;
  int _battery = 100;

  @override
  Stream<ImuSample> get samples => _controller.stream;

  @override
  Stream<bool> get connectionChanges => _connection.stream;

  // It's a fake, so it connects immediately
  @override
  Future<void> connect() async => _connection.add(true);

  @override
  Future<void> disconnect() async => _connection.add(false);

  // A battery that drops by 1% on every read
  @override
  Future<int?> readBatteryLevel() async => _battery = max(0, _battery - 1);

  @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();
    await _connection.close();
  }
}
  • You can check the connection-state and battery displays even without hardware

The real sensor

lib/service/imu/dual_gy521_device.dart
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:universal_ble/universal_ble.dart';
import 'package:motion_app/service/imu/imu_device.dart';
import 'package:motion_app/service/imu/imu_packet.dart';

// DualGY521_M5Stamp (two 6-axis sensors, BLE)
// A single characteristic is used both for writing commands and for notifying measurement data
class DualGy521Device implements ImuDevice {
  DualGy521Device(this.deviceId) {
    // Track the state from OS notifications so disconnections (power off, out of range, etc.) aren't missed
    _connectionSub =
        UniversalBle.connectionStream(deviceId).listen((connected) {
      if (!connected) _connected = false;
    });
  }

  final String deviceId;
  static final _service =
      BleUuidParser.string('4fafc201-1fb5-459e-8fcc-c5c9c331914b');
  static final _chara =
      BleUuidParser.string('beb5483e-36e1-4688-b7f5-ea07361b26a8');
  // Standard Battery Service / Battery Level (1 byte, 0–100)
  static final _batteryService = BleUuidParser.string('180f');
  static final _batteryLevel = BleUuidParser.string('2a19');
  static final _startCommand = Uint8List.fromList([0x01, 0x00]); // start continuous measurement
  static final _stopCommand = Uint8List.fromList([0x01, 0x01]); // stop continuous measurement

  final _controller = StreamController<ImuSample>.broadcast();
  StreamSubscription<Uint8List>? _valueSub;
  late final StreamSubscription<bool> _connectionSub;
  bool _connected = false;

  @override
  Stream<ImuSample> get samples => _controller.stream;

  @override
  Stream<bool> get connectionChanges => UniversalBle.connectionStream(deviceId);

  @override
  Future<void> connect() async {
    if (_connected) return;
    // Give up after 10 s so we don't wait long when it isn't found (default is 60 s)
    await UniversalBle.connect(deviceId, timeout: const Duration(seconds: 10));
    await UniversalBle.discoverServices(deviceId); // required before enabling notifications
    if (Platform.isAndroid) {
      // Enlarge the transfer size (MTU) so 52 bytes arrive in one go (automatic on iOS/macOS)
      await UniversalBle.requestMtu(deviceId, 128);
    }
    await _valueSub?.cancel();
    _valueSub = UniversalBle.characteristicValueStream(deviceId, _chara)
        .listen(_onValue);
    // The link is encrypted, so the first time enter the PIN (123456) in the OS pairing dialog
    await UniversalBle.subscribeNotifications(deviceId, _service, _chara);
    _connected = true;
  }

  @override
  Future<void> disconnect() async {
    await _valueSub?.cancel();
    _valueSub = null;
    _connected = false;
    await UniversalBle.disconnect(deviceId);
  }

  @override
  Future<int?> readBatteryLevel() async {
    if (!_connected) return null;
    try {
      final value =
          await UniversalBle.read(deviceId, _batteryService, _batteryLevel);
      return value.isEmpty ? null : value[0];
    } catch (_) {
      return null; // Cannot be read on devices without the Battery Service
    }
  }

  @override
  Future<void> start() async {
    await connect(); // connect here if not connected yet
    await UniversalBle.write(deviceId, _service, _chara, _startCommand);
  }

  void _onValue(Uint8List value) {
    final sample = ImuPacket.tryParse(value);
    if (sample != null) _controller.add(sample);
  }

  @override
  Future<void> stop() async {
    if (!_connected) return;
    await UniversalBle.write(deviceId, _service, _chara, _stopCommand);
  }

  @override
  Future<void> dispose() async {
    await _connectionSub.cancel();
    await _valueSub?.cancel();
    if (_connected) await UniversalBle.disconnect(deviceId);
    await _controller.close();
  }
}

Key points of the real sensor

  • connectionStream lets you receive disconnections caused by power-off or loss of signal
  • Connection timeout is 10 seconds (with the default 60 seconds, you’d wait long when no device is around)
  • start() also calls connect(), so measuring works even if auto-connect hasn’t finished
  • If the battery can’t be read, return null instead of throwing (it simply isn’t shown)

Caveats about the saved ID

Android

The ID is the device’s MAC address. The same from any phone

iOS / macOS

A UUID assigned by the OS. Differs per host device, so it can’t be carried to another device. On the same device, it connects directly without rescanning

  • Right after launch, the OS Bluetooth permission or PIN dialog may appear → connect in the background without blocking the UI

One connection state for the whole app

lib/provider/imu_connection.dart
import 'dart:async';

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/provider/providers.dart';

part 'imu_connection.g.dart';
part 'imu_connection.freezed.dart';

enum ImuConnectionStatus { disconnected, connecting, connected }

@freezed
abstract class ImuConnectionState with _$ImuConnectionState {
  const factory ImuConnectionState({
    @Default(ImuConnectionStatus.disconnected) ImuConnectionStatus status,
    int? batteryLevel, // battery level [%]. null if not read yet
    @Default(false) bool hasError, // could not connect after all retries
  }) = _ImuConnectionState;
}

// Connection state and battery level of the sensor. One for the whole app
// Readable from any screen via ref.watch(imuConnectionProvider)
@Riverpod(keepAlive: true)
class ImuConnection extends _$ImuConnection {
  static const _retryCount = 3;
  static const _retryDelay = Duration(seconds: 3);
  static const _batteryInterval = Duration(seconds: 30);
  Timer? _batteryTimer;

  @override
  ImuConnectionState build() {
    // When the device changes, this restarts from here (the old device is disconnected)
    final device = ref.watch(imuDeviceProvider);
    final sub = device.connectionChanges.listen(_onConnectionChanged);
    ref.onDispose(() {
      sub.cancel();
      _batteryTimer?.cancel();
    });
    // state can't be changed inside build, so start connecting automatically after build finishes
    Future.microtask(connect);
    return const ImuConnectionState();
  }

  Future<void> connect() async {
    if (!ref.mounted || state.status != ImuConnectionStatus.disconnected) return;
    final device = ref.read(imuDeviceProvider);
    state = const ImuConnectionState(status: ImuConnectionStatus.connecting);
    // If it can't connect (powered off, too far, etc.), wait a bit and retry only a few times
    for (var i = 0; i < _retryCount; i++) {
      try {
        await device.connect();
        if (!ref.mounted) return;
        _onConnected();
        return;
      } catch (_) {
        await Future<void>.delayed(_retryDelay);
        if (!ref.mounted) return;
      }
    }
    state = const ImuConnectionState(hasError: true);
  }

  // Disconnect deliberately (no automatic reconnect)
  Future<void> disconnect() async {
    final device = ref.read(imuDeviceProvider);
    _batteryTimer?.cancel();
    state = const ImuConnectionState(); // Mark as disconnected first to prevent reconnecting
    await device.disconnect();
  }

  void _onConnected() {
    state = const ImuConnectionState(status: ImuConnectionStatus.connected);
    // Read the battery level periodically here, once, rather than per screen
    _readBattery();
    _batteryTimer?.cancel();
    _batteryTimer = Timer.periodic(_batteryInterval, (_) => _readBattery());
  }

  Future<void> _readBattery() async {
    final level = await ref.read(imuDeviceProvider).readBatteryLevel();
    if (!ref.mounted || state.status != ImuConnectionStatus.connected) return;
    state = state.copyWith(batteryLevel: level);
  }

  void _onConnectionChanged(bool connected) {
    // Reconnect only when a live connection dropped (power off / out of range)
    if (connected || state.status != ImuConnectionStatus.connected) return;
    _batteryTimer?.cancel();
    state = const ImuConnectionState();
    connect();
  }
}

Key points of ImuConnection

  • keepAlive: true → the connection is kept even when screens close. One for the whole app
  • ref.watch(imuDeviceProvider) → choosing another device restarts from build (the old device is disconnected)
  • If it can’t connect, retry up to 3 times every 3 seconds. Never retry forever (battery drain, OS limits)
  • After a deliberate disconnect, don’t reconnect (set state to disconnected first)
  • The battery level is read here every 30 seconds, not per screen → one transfer no matter how many screens are open

Start connecting at launch

lib/app.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/router/router.dart';

class App extends ConsumerWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Start connecting to the sensor right after launch (keeps the connection whichever screen is open)
    ref.listen(imuConnectionProvider, (_, _) {});
    return MaterialApp.router(
      title: 'Motion Note',
      theme: ThemeData(colorSchemeSeed: Colors.teal),
      routerConfig: ref.watch(routerProvider),
    );
  }
}
  • Providers are created when someone uses them. Listening in App makes it be created right after launch
  • Because it’s listen, App isn’t redrawn when the connection state changes

Read it from any screen

lib/ui/common/connection_status_chip.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/provider/providers.dart';

// Sensor connection state and battery level. Can be placed in any screen's AppBar
class ConnectionStatusChip extends ConsumerWidget {
  const ConnectionStatusChip({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final connection = ref.watch(imuConnectionProvider);
    final isFake = ref.watch(selectedBleDeviceProvider) == null;
    final battery = connection.batteryLevel;

    final (icon, label) = switch (connection.status) {
      ImuConnectionStatus.connected => (
          Icons.bluetooth_connected,
          '${isFake ? '偽物' : '接続済み'}${battery == null ? '' : '  電池 $battery%'}',
        ),
      ImuConnectionStatus.connecting => (Icons.bluetooth_searching, '接続中...'),
      ImuConnectionStatus.disconnected => (
          Icons.bluetooth_disabled,
          connection.hasError ? '接続できません' : '未接続',
        ),
    };
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: Chip(avatar: Icon(icon, size: 18), label: Text(label)),
    );
  }
}
  • It only calls ref.watch. This Widget doesn’t connect or read the battery

Place it on the home screen

lib/ui/home/view/home_page.dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:motion_app/router/router.dart';
import 'package:motion_app/ui/common/connection_status_chip.dart';

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Motion Note'),
        actions: const [ConnectionStatusChip()],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          Card(
            child: ListTile(
              leading: const Icon(Icons.people),
              title: const Text('ユーザー'),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.users),
            ),
          ),
          Card(
            child: ListTile(
              leading: const Icon(Icons.bluetooth),
              title: const Text('デバイス'),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.push(Routes.device),
            ),
          ),
        ],
      ),
    );
  }
}

Measurement screen: select only the needed value

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/provider/imu_connection.dart';
import 'package:motion_app/ui/common/connection_status_chip.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);
    // Pick only the needed value with select → no redraw when the battery level changes
    final isConnected = ref.watch(imuConnectionProvider
        .select((s) => s.status == ImuConnectionStatus.connected));
    final big = Theme.of(context).textTheme.displaySmall;

    return Scaffold(
      appBar: AppBar(
        title: const Text('測定'),
        actions: const [ConnectionStatusChip()],
      ),
      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: isConnected ? notifier.start : null, // disabled until connected
                  ),
          ],
        ),
      ),
    );
  }
}
  • select → redraw only when “is it connected” changes (not when the battery level changes)

What to ref.watch and what to avoid

OK to ref.watch

  • Values that change occasionally, such as connection state and battery level
  • They change once every few to few tens of seconds

Avoid ref.watch

  • Measurements arriving at 100Hz
  • Every screen watching them would redraw 100 times per second
  • As in Chapter 6, receive them with ref.listen, thin them out, then put them in state

Device screen

lib/ui/device/view/device_page.dart
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/ui/common/connection_status_chip.dart';
import 'package:motion_app/ui/device/view_model/device_view_model.dart';

class DevicePage extends ConsumerWidget {
  const DevicePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final state = ref.watch(deviceViewModelProvider);
    final notifier = ref.read(deviceViewModelProvider.notifier);
    final selectedId = ref.watch(selectedBleDeviceProvider);
    final connection = ref.watch(imuConnectionProvider);
    // A device that is saved but not in this scan's results
    final isSavedOnly = selectedId != null &&
        state.devices.every((d) => d.deviceId != selectedId);

    return Scaffold(
      appBar: AppBar(
        title: const Text('デバイス'),
        actions: const [ConnectionStatusChip()],
      ),
      floatingActionButton: FloatingActionButton.extended(
        icon: const Icon(Icons.bluetooth_searching),
        label: Text(state.isScanning ? '検索中...' : '検索'),
        onPressed: state.isScanning ? null : notifier.scan,
      ),
      body: RadioGroup<String?>(
        groupValue: selectedId,
        onChanged: notifier.select,
        child: ListView(
          children: [
            const RadioListTile<String?>(
              value: null,
              title: Text('偽物のセンサ(実機なし)'),
            ),
            if (isSavedOnly)
              RadioListTile<String?>(
                value: selectedId,
                title: const Text('保存されているデバイス'),
                subtitle: Text(selectedId),
              ),
            if (connection.hasError)
              ListTile(
                leading: const Icon(Icons.error_outline),
                title: const Text('接続できませんでした'),
                trailing: TextButton(
                  onPressed: notifier.reconnect,
                  child: const Text('再接続'),
                ),
              ),
            if (state.errorMessage != null)
              ListTile(title: Text(state.errorMessage!)),
            for (final device in state.devices)
              RadioListTile<String?>(
                value: device.deviceId,
                title: Text(device.name ?? ''),
                subtitle: Text('${device.deviceId}  RSSI ${device.rssi ?? '-'}'),
              ),
          ],
        ),
      ),
    );
  }
}
  • The saved device is listed even if this scan didn’t find it (so you can see it’s selected)

Device screen ViewModel

lib/ui/device/view_model/device_view_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:universal_ble/universal_ble.dart';

part 'device_view_model.g.dart';
part 'device_view_model.freezed.dart';

@freezed
abstract class DeviceState with _$DeviceState {
  const factory DeviceState({
    @Default([]) List<BleDevice> devices,
    @Default(false) bool isScanning,
    String? errorMessage,
  }) = _DeviceState;
}

@riverpod
class DeviceViewModel extends _$DeviceViewModel {
  @override
  DeviceState build() => const DeviceState();

  Future<void> scan() async {
    state = state.copyWith(isScanning: true, errorMessage: null);
    try {
      final devices = await ref.read(bleScannerProvider).scan();
      state = state.copyWith(devices: devices, isScanning: false);
    } catch (e) {
      state = state.copyWith(isScanning: false, errorMessage: '$e');
    }
  }

  // The chosen device is saved and connected automatically
  Future<void> select(String? deviceId) =>
      ref.read(selectedBleDeviceProvider.notifier).select(deviceId);

  // Try again when the connection failed
  Future<void> reconnect() => ref.read(imuConnectionProvider.notifier).connect();
}

Checkpoint

CHECK 0 / 5