Luke
Luke

Reputation: 387

How to get sensor data using timer in Flutter

I'm attempting to gather sensor data using a timer, in flutter, but it's not working correctly. When it reaches ten entries it should sort the list (I just sort so there's an action I can debug off), and this should be ten seconds. But it reaches this point after about three seconds and oddly has usually 16 entries. I think the listen event isn't reacting properly to the timer.

My code is:

List<SensorAccelerometer> accList;
  Timer timer;

  void startRecording() {
    accList = new List<SensorAccelerometer>();
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      accelerometerEvents.listen((AccelerometerEvent event) {
        SensorAccelerometer sensorAccelerometer =
            new SensorAccelerometer(event.x, event.y, event.z);
        accList.add(sensorAccelerometer);
      });
      if(accList.length > 10){
        accList.sort();
      }
    });
  }

And SensorAccelerometer is just an object holding the three doubles for x,y,z.

Can anyone help please?

Upvotes: 1

Views: 507

Answers (1)

Luke
Luke

Reputation: 387

Ah, silly me. So having the add within the listen was just adding like crazy. I removed it from there, placing it below, and it now works.

  void startRecording() {
    accList = new List<SensorAccelerometer>();
    SensorAccelerometer sensorAccelerometer;
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      accelerometerEvents.listen((AccelerometerEvent event) {
        sensorAccelerometer = new SensorAccelerometer(event.x, event.y, event.z);
      });
      accList.add(sensorAccelerometer);
      if(accList.length > 10){
        accList.sort();
      }
    });
  }

Upvotes: 2

Related Questions