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() {
super.initState();
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>(
builder: (context, sensorProvider, child) {
if (sensorProvider.sensorData == null) {
if (sensorProvider.error != null) {
return Text('Error: ${sensorProvider.error}');
if (sensorProvider.exception != null) {
return Text('Error: ${sensorProvider.exception}');
}
return const CircularProgressIndicator();
} else {

View File

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