Search code examples
flutterdartaccelerometersensors

Car Acceleration and Deceleration using Flutter


Hello I'm trying to get the car acceleration and deceleration with flutter, Also I'm using the userAccelerometerEvent to deduct the gravity, however, I'm getting errors under event

1) I want to know how to measure the acceleration and deceleration using flutter. 2) Why there is an error when I use userAccelerometerEvent

    @override
  void initState() {
    super.initState();

    userAccelerometerEvents.listen((UserAccelerometerEvent event) {
      if (event() >= 2 && event() < 5) {
        print('Between 2 and 5');
      }
      if (event() >= 10 ) {
        print('Greater Than 10');
      }
    });

Solution

  • What errors are you seeing?

    Looks like you are using the sensors package from Flutter, the README is located here and describes how to listen to different sensor changes: README

    Looking at your code, it looks like you are using the event parameter as a method event(). The event parameter is a UserAccelerometerEvent object with properties x, y, and z. You should access the x, y, and z values by doing: event.x or event.y or event.z instead.

    The flutter team has some sample code for how to use the sensors package here: Sample Code

    Some relevant code from the example page below.

      void initState() {
        super.initState();
        _streamSubscriptions
            .add(userAccelerometerEvents.listen((UserAccelerometerEvent event) {
          setState(() {
            _userAccelerometerValues = <double>[event.x, event.y, event.z];
          });
        }));
      }