diff --git a/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart b/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart index 9d5ca6d..660489e 100644 --- a/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart +++ b/lib/screens/monitoring/evaporasi/blocs/evaporasi_bloc.dart @@ -105,17 +105,39 @@ class EvaporasiBloc extends Bloc { await _subscription?.cancel(); _subscription = _repository - .getSensorStream('Monitoring', (json) => Evaporasi.fromJson(json)) + .getSensorStream('Monitoring/History', _latestHistoryEntry) .listen((data) => add(_EvaporasiRealtimeUpdated(data))); } + Evaporasi _latestHistoryEntry(Map json) { + if (json.isEmpty) return Evaporasi.empty; + + final entries = json.values + .whereType>() + .map((item) => Evaporasi.fromJson(item)) + .toList(); + + if (entries.isEmpty) return Evaporasi.empty; + + entries.sort((a, b) => a.timestamp.compareTo(b.timestamp)); + return entries.last; + } + void _onRealtimeUpdated( _EvaporasiRealtimeUpdated event, Emitter emit, ) { - // Hindari update dobel: jika timestamp event sama dengan yang terakhir, jangan ubah bucket. - final previous = - state.history.isNotEmpty ? state.history.last.timestamp : null; + final updatedHistory = List.from(state.history); + final duplicateIndex = updatedHistory.indexWhere( + (item) => item.timestamp.toUtc() == event.data.timestamp.toUtc(), + ); + + if (duplicateIndex >= 0) { + updatedHistory[duplicateIndex] = event.data; + } else { + updatedHistory.add(event.data); + } + updatedHistory.sort((a, b) => a.timestamp.compareTo(b.timestamp)); // Update bucket berdasarkan timestamp event (bukan jam lokal sekarang). final updated = List.from(state.dailyValues); @@ -140,6 +162,8 @@ class EvaporasiBloc extends Bloc { _emitEvaporasiAlert(status, rain, event.data.evaporasi); emit(state.copyWith( + history: updatedHistory, + listData: updatedHistory, currentValue: event.data.evaporasi, temperature: event.data.suhu, waterLevel: event.data.tinggiAir, diff --git a/lib/screens/monitoring/evaporasi/views/evaporasi_screen.dart b/lib/screens/monitoring/evaporasi/views/evaporasi_screen.dart index be79b65..fec813a 100644 --- a/lib/screens/monitoring/evaporasi/views/evaporasi_screen.dart +++ b/lib/screens/monitoring/evaporasi/views/evaporasi_screen.dart @@ -290,20 +290,15 @@ class _EvaporasiScreenState extends State { /// 🧾 LIST DATA EVAPORASI /// ========================= Widget _evaporasiList(EvaporasiState state) { - final allData = [...state.history]; - if (state.currentData != null) { - allData.add(state.currentData!); - } - final data = (state.viewMode == EvaporasiViewMode.customDate && state.selectedDate != null - ? allData + ? state.history .where((e) => e.timestamp.year == state.selectedDate!.year && e.timestamp.month == state.selectedDate!.month && e.timestamp.day == state.selectedDate!.day) .toList() - : List.of(allData)) + : List.of(state.history)) ..sort((a, b) => b.timestamp.compareTo(a.timestamp)); if (data.isEmpty) {