build method

  1. @override
Widget build(
  1. BuildContext context,
  2. WidgetRef ref
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context, WidgetRef ref) {
  const identifier = 'D20EC122';
  final logs = useState<List<String>>(['Service started']);
  final polar = ref.read(polarProvider);
  final deviceInfo = useState<HeartRateDeviceInfo?>(null);
  PolarExerciseEntry? exerciseEntry;
  final adapter = ref
      .read(heartRateAdapterProvider(HeartRateDeviceType.polarH10).notifier);

  void streamWhenReady() async {
    await adapter.startHeartRateAcquisition();
    await adapter.startEcgAcquisition();
    await adapter.startBatteryLevelAcquisition();
  }

  useEffect(() {
    late StreamSubscription<HeartRateDeviceInfo> searchSubscription;
    late StreamSubscription<HeartRateDeviceEvent> deviceEventSubscription;

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // BLEの許諾を求める
      final isGranted = await ref
          .read(permissionHandlerProvider)
          .requestBluetoothPermission();
      if (kDebugMode) {
        print('BLE permission is granted: $isGranted');
      }
      searchSubscription = adapter.searchForDevice().listen((e) {
        deviceInfo.value = e;
        logs.value = [...logs.value, 'Found device in scan: ${e.deviceId}'];
      });
      deviceEventSubscription = adapter.deviceEventStream.listen((e) {
        e.whenOrNull(
          connecting: (_) {
            logs.value = [...logs.value, 'Device connecting'];
          },
          connected: (_) {
            logs.value = [...logs.value, 'Device connected'];
            streamWhenReady();
          },
          disconnect: (_) {
            logs.value = [...logs.value, 'Device disconnected'];
          },
          heartRate: (e) {
            for (var element in e) {
              logs.value = [
                ...logs.value,
                'Heart rate data heart rate: ${element.heartRate}, rrMs: ${element.rrsMs}'
              ];
            }
          },
          ecg: (e) {
            for (var element in e) {
              logs.value = [
                ...logs.value,
                'ECG data timestamp: ${element.timeStamp}, voltage: ${element.voltage}'
              ];
            }
          },
          batteryLevel: (e) {
            logs.value = [...logs.value, 'Battery level: ${e.batteryLevel}'];
          },
        );
      }, onError: (e, s) {
        if (e is HeartRateAdapterException) {
          switch (e.deviceEventStreamErrorType) {
            case HeartRateDeviceEventStreamErrorType.connectingError:
              logs.value = [...logs.value, 'Device connecting error: $e'];
              break;
            case HeartRateDeviceEventStreamErrorType.connectedError:
              logs.value = [...logs.value, 'Device connected error: $e'];
              break;
            case HeartRateDeviceEventStreamErrorType.disconnectError:
              logs.value = [...logs.value, 'Device disconnected error: $e'];
              break;
            case HeartRateDeviceEventStreamErrorType.unknown:
              logs.value = [...logs.value, 'Device unknown error: $e'];
              break;
            case HeartRateDeviceEventStreamErrorType.heartRateError:
              logs.value = [...logs.value, 'Heart rate error: $e'];
              break;
            case HeartRateDeviceEventStreamErrorType.ecgError:
              logs.value = [...logs.value, 'ECG error: $e'];
              break;
            case HeartRateDeviceEventStreamErrorType.batteryLevelError:
              logs.value = [...logs.value, 'Battery level error: $e'];
              break;
          }
        }
        logs.value = [...logs.value, 'Error: $e'];
      });
    });
    return () {
      searchSubscription.cancel();
      deviceEventSubscription.cancel();
    };
  }, []);

  Future<void> handleRecordingAction(RecordingAction action) async {
    switch (action) {
      case RecordingAction.start:
        logs.value = [...logs.value, 'Starting recording'];
        await polar.startRecording(
          identifier,
          exerciseId: const Uuid().v4(),
          interval: RecordingInterval.interval_1s,
          sampleType: SampleType.rr,
        );
        logs.value = [...logs.value, 'Started recording'];
        break;
      case RecordingAction.stop:
        logs.value = [...logs.value, 'Stopping recording'];
        await polar.stopRecording(identifier);
        logs.value = [...logs.value, 'Stopped recording'];
        break;
      case RecordingAction.status:
        logs.value = [...logs.value, 'Getting recording status'];
        final status = await polar.requestRecordingStatus(identifier);
        logs.value = [...logs.value, 'Recording status: $status'];
        break;
      case RecordingAction.list:
        logs.value = [...logs.value, 'Listing recordings'];
        final entries = await polar.listExercises(identifier);
        logs.value = [...logs.value, 'Recordings: $entries'];
        // H10 can only store one recording at a time
        exerciseEntry = entries.first;
        break;
      case RecordingAction.fetch:
        logs.value = [...logs.value, 'Fetching recording'];
        if (exerciseEntry == null) {
          logs.value = [...logs.value, 'Exercises not yet listed'];
          await handleRecordingAction(RecordingAction.list);
        }
        final entry = await polar.fetchExercise(identifier, exerciseEntry!);
        logs.value = [...logs.value, 'Fetched recording: $entry'];
        break;
      case RecordingAction.remove:
        logs.value = [...logs.value, 'Removing recording'];
        if (exerciseEntry == null) {
          logs.value = [
            ...logs.value,
            'No exercise to remove. Try calling list first.'
          ];
          return;
        }
        await polar.removeExercise(identifier, exerciseEntry!);
        logs.value = [...logs.value, 'Removed recording'];
        break;
    }
  }

  return Scaffold(
      appBar: AppBar(
        title: const Text('DebugPolar'),
        actions: [
          PopupMenuButton(
            itemBuilder: (context) => RecordingAction.values
                .map((e) => PopupMenuItem(value: e, child: Text(e.name)))
                .toList(),
            onSelected: handleRecordingAction,
            child: const IconButton(
              icon: Icon(Icons.fiber_manual_record),
              disabledColor: Colors.black,
              onPressed: null,
            ),
          ),
          IconButton(
            icon: const Icon(Icons.stop),
            onPressed: () {
              logs.value = [
                ...logs.value,
                'Disconnecting from device: $identifier'
              ];
              adapter.disconnectFromDevice();
            },
          ),
          IconButton(
            icon: const Icon(Icons.play_arrow),
            onPressed: () {
              logs.value = [
                ...logs.value,
                'Connecting to device: $identifier'
              ];
              adapter.connectToDevice(deviceInfo: deviceInfo.value!);
              // streamWhenReady();
            },
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        shrinkWrap: true,
        children: logs.value.reversed.map((e) => Text(e)).toList(),
      ));
}