mercury/mercury_frontend/lib/sensor_provider.dart

47 lines
950 B
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'sensor_data.dart';
import 'sensor_service.dart';
class SensorProvider with ChangeNotifier {
final SensorService _service = SensorService();
SensorData? _sensorData;
Exception? _exception;
SensorData? get sensorData => _sensorData;
Exception? get exception => _exception;
Timer? _timer;
Future<void> fetchData() async {
try {
_sensorData = await _service.fetchSensorData();
} on Exception catch (e) {
_exception = e;
_sensorData = null;
}
notifyListeners();
}
void startAutoFetch(Duration interval) {
_timer = Timer.periodic(interval, (timer) async {
await fetchData();
});
}
// Stop auto-fetching
void stopAutoFetch() {
_timer?.cancel();
_timer = null;
}
// Dispose the timer when the provider is disposed
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}