fix(frontend): error handling

This commit is contained in:
Halit Aksoy 2025-02-22 20:45:01 +03:00
parent f775ddea55
commit 8b2046c107
2 changed files with 32 additions and 8 deletions

View File

@ -37,7 +37,7 @@ class _SensorScreenState extends State<SensorScreen> {
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
Provider.of<SensorProvider>(context, listen: false).fetchData(); Provider.of<SensorProvider>(context, listen: false).startAutoFetch(const Duration(seconds: 1));
}); });
} }
@ -49,8 +49,8 @@ class _SensorScreenState extends State<SensorScreen> {
child: Consumer<SensorProvider>( child: Consumer<SensorProvider>(
builder: (context, sensorProvider, child) { builder: (context, sensorProvider, child) {
if (sensorProvider.sensorData == null) { if (sensorProvider.sensorData == null) {
if (sensorProvider.error != null) { if (sensorProvider.exception != null) {
return Text('Error: ${sensorProvider.error}'); return Text('Error: ${sensorProvider.exception}');
} }
return const CircularProgressIndicator(); return const CircularProgressIndicator();
} else { } else {

View File

@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'sensor_data.dart'; import 'sensor_data.dart';
import 'sensor_service.dart'; import 'sensor_service.dart';
@ -6,18 +8,40 @@ class SensorProvider with ChangeNotifier {
final SensorService _service = SensorService(); final SensorService _service = SensorService();
SensorData? _sensorData; SensorData? _sensorData;
Error? _error; Exception? _exception;
SensorData? get sensorData => _sensorData; SensorData? get sensorData => _sensorData;
Error? get error => _error; Exception? get exception => _exception;
Timer? _timer;
Future<void> fetchData() async { Future<void> fetchData() async {
try { try {
_sensorData = await _service.fetchSensorData(); _sensorData = await _service.fetchSensorData();
} catch (e) { } on Exception catch (e) {
_error = e as Error; _exception = e;
_sensorData = null;
} }
notifyListeners(); 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();
}
}