gyroscopeStream property

  1. @override
Stream<MotionEvent>? get gyroscopeStream
override

The gyroscope stream, if available.

Implementation

@override
Stream<MotionEvent>? get gyroscopeStream {
  if (_gyroscopeStreamController == null) {
    _gyroscopeStreamController = StreamController();

    if (_isGyroscopeApiAvailable) {
      _featureDetected(
        () {
          final gyroscope = Gyroscope(SensorOptions(frequency: _frequency));

          gyroscope.onreading = (Event event) {
            _gyroscopeStreamController?.add(
              MotionEvent(
                type: MotionType.gyroscope,
                x: gyroscope.x,
                y: gyroscope.y,
                z: gyroscope.z,
              ),
            );
          }.toJS;

          gyroscope.start();

          gyroscope.onerror = (Event e) {
            developer.log(
                'The gyroscope API is supported but something is wrong!',
                error: e);
          }.toJS;
        },
        apiName: 'Gyroscope()',
        permissionName: 'gyroscope',
        onError: () {
          web.console.warn(
              'Error: Gyroscope() is not supported by the User Agent.'.toJS);
          _gyroscopeStreamController!
              .add(const MotionEvent.zero(type: MotionType.gyroscope));
        },
      );
    } else if (_isDeviceMotionApiAvailable) {
      /// If unavailable, fallback on the [DeviceMotionEvent] API.
      _featureDetected(
          () {
            web.window
                .addEventListener('ondevicemotion', onDeviceMotion.toJS);
          },
          apiName: 'DeviceMotionEvent()',
          permissionName: 'DeviceMotionEvent',
          onError: () {
            web.console.warn(
                'The DeviceMotionEvent API is not available either.'.toJS);
            web.window
                .removeEventListener('ondevicemotion', onDeviceMotion.toJS);
            _gyroscopeStreamController!
                .add(const MotionEvent.zero(type: MotionType.gyroscope));
          });
    }
    _gyroscopeStream = _gyroscopeStreamController!.stream.asBroadcastStream();
  }

  return _gyroscopeStream;
}