I make app to read accelerometer but I have difficult to read accelerometer sensor log. Anyway, I used toggle switch. The problem is when I turned on toggle switch, the accelerometer only read once not my trial before by used button component. These the code below:
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:sensors_plus/sensors_plus.dart';
class WalkingApp extends StatefulWidget {
const WalkingApp({super.key});
@override
State<WalkingApp> createState() => _WalkingAppState();
}
class _WalkingAppState extends State<WalkingApp> {
bool isSwitched = false;
var _accel = 0.0;
var _currentAcc = 0.0;
var lastAccel = 0.0;
var stepCount = 0;
var x= 0.0, y=0.0, z=0.0;
late Timer timer;
void stop() {
setState(() {
isSwitched = false;
_accel = 0.0;
for (StreamSubscription<dynamic> subscription in _streamSubscriptions) {
subscription.cancel();
}
});
}
//walk
final _streamSubscriptions = <StreamSubscription<dynamic>>[];
@override
void initState() {
super.initState();
_streamSubscriptions.add(
accelerometerEvents.listen((AccelerometerEvent event) {
setState(() {
x = event.x;
y = event.y;
z = event.z;
});
})
);
}
void start() {
isSwitched = true;
setState(() {
hitungStep(x, y, z);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SwitchListTile(
title: const Text('Jalan',
style: TextStyle(color: Colors.black87, fontSize: 16.0)),
value: isSwitched,
onChanged: (value) {
setState(() {
(!isSwitched) ? start(): stop();
});
},
activeTrackColor: Colors.blueAccent,
activeColor: Colors.blue,
),
const SizedBox(height: 16),
Text('$stepCount',
style: const TextStyle(color: Colors.cyan, fontSize: 48.0)),
const SizedBox(height: 8),
const Text('Langkah',
style: TextStyle(color: Colors.black54, fontSize: 18.0)),
],
)),
);
}
void hitungStep(double x, double y, double z) {
_accel = 10;
_currentAcc = 9.8;
lastAccel = 9.8;
lastAccel = _currentAcc;
_currentAcc = sqrt((x*x)+(y*y)+(z*z));
var delta = _currentAcc - lastAccel;
_accel = delta.abs();
if(_accel > 1){
stepCount++;
}
if(kDebugMode){
print('nilai x :$x, nilai y: $y, nilai z: $z, accel: $_accel');
}
}
@override
void dispose() {
super.dispose();
for (final subscription in _streamSubscriptions) {
subscription.cancel();
}
}
}
My expectation is when turning on toggle and the phone still read accelerometer log like I pressed button. Would you like to help solve problem? what should I do?