805 lines
26 KiB
Dart
805 lines
26 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:fl_chart/fl_chart.dart';
|
|
import 'package:firebase_database/firebase_database.dart';
|
|
import 'package:monitoring_repository/monitoring_repository.dart';
|
|
import '../blocs/atmospheric_conditions_bloc.dart';
|
|
import '../../shared/utils/excel/excel_export_service.dart';
|
|
import '../../shared/widgets/export_excel_button.dart';
|
|
|
|
String formatUptimeShort(int timeMs) {
|
|
final duration = Duration(milliseconds: timeMs);
|
|
final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
|
|
final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
|
|
return "$minutes:$seconds";
|
|
}
|
|
|
|
String formatUptimeLong(int timeMs) {
|
|
final duration = Duration(milliseconds: timeMs);
|
|
final hours = duration.inHours.toString().padLeft(2, '0');
|
|
final minutes = duration.inMinutes.remainder(60).toString().padLeft(2, '0');
|
|
final seconds = duration.inSeconds.remainder(60).toString().padLeft(2, '0');
|
|
return "$hours:$minutes:$seconds";
|
|
}
|
|
|
|
String formatClockTime(DateTime timestamp) {
|
|
final h = timestamp.hour.toString().padLeft(2, '0');
|
|
final m = timestamp.minute.toString().padLeft(2, '0');
|
|
final s = timestamp.second.toString().padLeft(2, '0');
|
|
return "$h:$m:$s";
|
|
}
|
|
|
|
String _monthName(int month) {
|
|
const months = [
|
|
'Jan',
|
|
'Feb',
|
|
'Mar',
|
|
'Apr',
|
|
'Mei',
|
|
'Jun',
|
|
'Jul',
|
|
'Agu',
|
|
'Sep',
|
|
'Okt',
|
|
'Nov',
|
|
'Des',
|
|
];
|
|
return months[month - 1];
|
|
}
|
|
|
|
String formatDateTimeReadable(DateTime timestamp) {
|
|
final day = timestamp.day.toString().padLeft(2, '0');
|
|
final month = _monthName(timestamp.month);
|
|
return '$day $month ${timestamp.year}, ${formatClockTime(timestamp)}';
|
|
}
|
|
|
|
class _HumidityStatus {
|
|
final String title;
|
|
final String description;
|
|
|
|
const _HumidityStatus({required this.title, required this.description});
|
|
}
|
|
|
|
_HumidityStatus _getHumidityStatus(double humidity) {
|
|
if (humidity < 40.0) {
|
|
return const _HumidityStatus(
|
|
title: 'Terlalu kering',
|
|
description: 'Risiko: tanaman cepat transpirasi, stres, daun menggulung.',
|
|
);
|
|
}
|
|
|
|
if (humidity < 60.0) {
|
|
return const _HumidityStatus(
|
|
title: 'Cukup ideal (umum)',
|
|
description: 'Biasanya nyaman untuk banyak tanaman (tergantung suhu).',
|
|
);
|
|
}
|
|
|
|
if (humidity <= 80.0) {
|
|
return const _HumidityStatus(
|
|
title: 'Lembap',
|
|
description: 'Mulai naik risiko jamur/penyakit daun bila sirkulasi udara buruk.',
|
|
);
|
|
}
|
|
|
|
return const _HumidityStatus(
|
|
title: 'Terlalu lembap / rawan penyakit',
|
|
description: 'Risiko: embun di daun, cendawan (powdery mildew/botrytis), bakteri.',
|
|
);
|
|
}
|
|
|
|
class AtmosphericScreen extends StatefulWidget {
|
|
const AtmosphericScreen({super.key});
|
|
|
|
@override
|
|
State<AtmosphericScreen> createState() => _AtmosphericScreenState();
|
|
}
|
|
|
|
class _AtmosphericScreenState extends State<AtmosphericScreen> {
|
|
DateTime? _selectedDate;
|
|
final DatabaseReference _sendControlRef = FirebaseDatabase.instance.ref('/sensor/control/send_enabled');
|
|
|
|
String get _dateFilterLabel {
|
|
final date = _selectedDate;
|
|
if (date == null) {
|
|
return 'Semua tanggal';
|
|
}
|
|
|
|
return formatDateOnlyReadable(date);
|
|
}
|
|
|
|
Future<void> _pickDate() async {
|
|
final now = DateTime.now();
|
|
final initialDate = _selectedDate ?? now;
|
|
|
|
final picked = await showDatePicker(
|
|
context: context,
|
|
initialDate: initialDate,
|
|
firstDate: DateTime(2020),
|
|
lastDate: now,
|
|
);
|
|
|
|
if (!mounted || picked == null) {
|
|
return;
|
|
}
|
|
|
|
setState(() {
|
|
_selectedDate = DateTime(picked.year, picked.month, picked.day);
|
|
});
|
|
}
|
|
|
|
void _clearDateFilter() {
|
|
setState(() {
|
|
_selectedDate = null;
|
|
});
|
|
}
|
|
|
|
List<AtmosphericConditions> _filteredHistory(List<AtmosphericConditions> history) {
|
|
final selectedDate = _selectedDate;
|
|
if (selectedDate == null) {
|
|
return history;
|
|
}
|
|
|
|
return history.where((item) => _isSameDay(item.timestamp, selectedDate)).toList();
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
backgroundColor: Colors.grey.shade100,
|
|
appBar: AppBar(
|
|
title: const Text(
|
|
"Kelembapan",
|
|
style: TextStyle(fontWeight: FontWeight.bold),
|
|
),
|
|
centerTitle: true,
|
|
backgroundColor: Colors.transparent,
|
|
elevation: 0,
|
|
foregroundColor: Colors.black,
|
|
),
|
|
body: BlocBuilder<AtmosphericConditionsBloc, AtmosphericConditionsState>(
|
|
builder: (context, state) {
|
|
if (state.isLoading) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
}
|
|
|
|
final filteredHistory = _filteredHistory(state.history);
|
|
final latestHistory = state.history.isNotEmpty ? state.history.last : null;
|
|
|
|
return SingleChildScrollView(
|
|
padding: const EdgeInsets.all(20),
|
|
child: Column(
|
|
children: [
|
|
_statusErrorCard(state),
|
|
if (_shouldShowStatusError(state)) const SizedBox(height: 16),
|
|
_sendControlCard(),
|
|
const SizedBox(height: 16),
|
|
_mainHumidity(state, latestHistory),
|
|
const SizedBox(height: 12),
|
|
_humidityStatusCard(state, latestHistory),
|
|
const SizedBox(height: 24),
|
|
_historyFilterCard(filteredHistory.length),
|
|
const SizedBox(height: 16),
|
|
_historyChart(filteredHistory),
|
|
const SizedBox(height: 24),
|
|
_HistoryTableCard(history: filteredHistory),
|
|
const SizedBox(height: 24),
|
|
ExportExcelButton(
|
|
onExport: () {
|
|
final historyData = filteredHistory
|
|
.map((e) => {
|
|
'timeMs': e.timeMs,
|
|
'humidity': e.humidity,
|
|
'timestamp': e.timestamp,
|
|
})
|
|
.toList();
|
|
|
|
return ExcelExportService.atmospheric(
|
|
humidity: latestHistory?.humidity ?? state.humidity,
|
|
timeMs: latestHistory?.timeMs ?? state.timeMs,
|
|
timestamp: filteredHistory.isNotEmpty ? filteredHistory.last.timestamp : DateTime.now(),
|
|
historyData: historyData,
|
|
);
|
|
},
|
|
label: _selectedDate == null ? 'Export Excel Semua Histori' : 'Export Excel Tanggal Ini',
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
bool _isSameDay(DateTime a, DateTime b) {
|
|
return a.year == b.year && a.month == b.month && a.day == b.day;
|
|
}
|
|
|
|
Widget _historyFilterCard(int filteredCount) {
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
'Filter Histori',
|
|
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
|
),
|
|
const SizedBox(height: 6),
|
|
Text(
|
|
'Tampilan: $_dateFilterLabel',
|
|
style: const TextStyle(fontSize: 12, color: Colors.black54),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
'Data terlihat: $filteredCount',
|
|
style: const TextStyle(fontSize: 12, color: Colors.black54),
|
|
),
|
|
const SizedBox(height: 12),
|
|
Wrap(
|
|
spacing: 8,
|
|
runSpacing: 8,
|
|
children: [
|
|
ElevatedButton.icon(
|
|
onPressed: _pickDate,
|
|
icon: const Icon(Icons.calendar_month, size: 18),
|
|
label: const Text('Pilih Tanggal'),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.blue.shade600,
|
|
foregroundColor: Colors.white,
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(14),
|
|
),
|
|
),
|
|
),
|
|
OutlinedButton.icon(
|
|
onPressed: _selectedDate == null ? null : _clearDateFilter,
|
|
icon: const Icon(Icons.filter_alt_off, size: 18),
|
|
label: const Text('Semua Tanggal'),
|
|
style: OutlinedButton.styleFrom(
|
|
foregroundColor: Colors.black87,
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(14),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
bool _shouldShowStatusError(AtmosphericConditionsState state) {
|
|
final hasAnyStatus = state.statusLastSeenUnixMs > 0 || state.statusLastAvgUploadUnixMs > 0 || state.statusLastError.isNotEmpty;
|
|
if (!hasAnyStatus) {
|
|
return false;
|
|
}
|
|
|
|
final now = DateTime.now();
|
|
|
|
final lastSeen = state.statusLastSeenUnixMs > 1000000000000 ? DateTime.fromMillisecondsSinceEpoch(state.statusLastSeenUnixMs).toLocal() : null;
|
|
|
|
final lastUpload = state.statusLastAvgUploadUnixMs > 1000000000000 ? DateTime.fromMillisecondsSinceEpoch(state.statusLastAvgUploadUnixMs).toLocal() : null;
|
|
|
|
final offline = lastSeen != null && now.difference(lastSeen) > const Duration(seconds: 35);
|
|
final historyStale = lastUpload != null && now.difference(lastUpload) > const Duration(minutes: 70);
|
|
|
|
return offline || historyStale || state.statusLastError.isNotEmpty;
|
|
}
|
|
|
|
Widget _sendControlCard() {
|
|
return StreamBuilder<DatabaseEvent>(
|
|
stream: _sendControlRef.onValue,
|
|
builder: (context, snapshot) {
|
|
final value = snapshot.data?.snapshot.value;
|
|
final enabled = value is bool
|
|
? value
|
|
: value is num
|
|
? value != 0
|
|
: value is String
|
|
? value == '1' || value.toLowerCase() == 'true'
|
|
: true;
|
|
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
border: Border.all(color: enabled ? Colors.green.shade300 : Colors.red.shade300),
|
|
),
|
|
child: Row(
|
|
children: [
|
|
Icon(
|
|
enabled ? Icons.cloud_upload_outlined : Icons.cloud_off_outlined,
|
|
color: enabled ? Colors.green.shade700 : Colors.red.shade700,
|
|
),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
enabled ? 'Mode kirim aktif' : 'Mode kirim dimatikan',
|
|
style: const TextStyle(fontWeight: FontWeight.bold),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
enabled
|
|
? 'Alat boleh upload data ke Firebase dari HP.'
|
|
: 'Alat tetap baca sensor, tapi tidak akan kirim data.',
|
|
style: const TextStyle(fontSize: 12, color: Colors.black54),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
Switch(
|
|
value: enabled,
|
|
onChanged: (nextValue) async {
|
|
await _sendControlRef.set(nextValue ? 1 : 0);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
Widget _statusErrorCard(AtmosphericConditionsState state) {
|
|
if (!_shouldShowStatusError(state)) {
|
|
return const SizedBox.shrink();
|
|
}
|
|
|
|
final now = DateTime.now();
|
|
|
|
final lastSeen = state.statusLastSeenUnixMs > 1000000000000 ? DateTime.fromMillisecondsSinceEpoch(state.statusLastSeenUnixMs).toLocal() : null;
|
|
|
|
final lastUpload = state.statusLastAvgUploadUnixMs > 1000000000000 ? DateTime.fromMillisecondsSinceEpoch(state.statusLastAvgUploadUnixMs).toLocal() : null;
|
|
|
|
final offline = lastSeen != null && now.difference(lastSeen) > const Duration(seconds: 35);
|
|
final historyStale = lastUpload != null && now.difference(lastUpload) > const Duration(minutes: 70);
|
|
|
|
String headline;
|
|
if (offline) {
|
|
headline = 'Device OFFLINE (status tidak update)';
|
|
} else if (historyStale) {
|
|
headline = 'Histori tidak update';
|
|
} else if (state.statusLastError.isNotEmpty) {
|
|
headline = 'Firebase Error';
|
|
} else {
|
|
headline = 'Status Error';
|
|
}
|
|
|
|
final details = <String>[];
|
|
if (lastSeen != null) {
|
|
details.add('Last seen: ${formatClockTime(lastSeen)}');
|
|
}
|
|
if (lastUpload != null) {
|
|
details.add('Last upload: ${formatClockTime(lastUpload)}');
|
|
}
|
|
if (state.statusLastError.isNotEmpty) {
|
|
details.add('Error: ${state.statusLastError}');
|
|
}
|
|
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
border: Border.all(color: Colors.red.shade300),
|
|
),
|
|
child: Row(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Icon(Icons.error_outline, color: Colors.red.shade600),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(
|
|
headline,
|
|
style: TextStyle(
|
|
fontWeight: FontWeight.bold,
|
|
color: Colors.red.shade700,
|
|
),
|
|
),
|
|
if (details.isNotEmpty) ...[
|
|
const SizedBox(height: 6),
|
|
Text(
|
|
details.join('\n'),
|
|
style: const TextStyle(fontSize: 12, color: Colors.black87),
|
|
),
|
|
]
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// =========================
|
|
/// 🔵 HUMIDITY (HERO CARD)
|
|
/// =========================
|
|
Widget _mainHumidity(AtmosphericConditionsState state, AtmosphericConditions? latestHistory) {
|
|
final humidityValue = latestHistory?.humidity ?? state.humidity;
|
|
final latestTimestamp = latestHistory?.timestamp ?? state.latestTimestamp;
|
|
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.symmetric(vertical: 40),
|
|
decoration: BoxDecoration(
|
|
gradient: LinearGradient(
|
|
colors: [
|
|
const Color.fromARGB(255, 38, 255, 222),
|
|
const Color.fromARGB(255, 53, 132, 229)
|
|
],
|
|
),
|
|
borderRadius: BorderRadius.circular(25),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: const Color.fromARGB(255, 0, 191, 255).withOpacity(0.3),
|
|
blurRadius: 20,
|
|
offset: const Offset(0, 10),
|
|
)
|
|
],
|
|
),
|
|
child: Column(
|
|
children: [
|
|
const Icon(Icons.water_drop, color: Colors.white, size: 50),
|
|
const SizedBox(height: 6),
|
|
const SizedBox(height: 10),
|
|
Text(
|
|
humidityValue.toStringAsFixed(1),
|
|
style: const TextStyle(
|
|
fontSize: 70,
|
|
fontWeight: FontWeight.bold,
|
|
color: Colors.white,
|
|
),
|
|
),
|
|
const Text(
|
|
"%",
|
|
style: TextStyle(color: Colors.white70, fontSize: 18),
|
|
),
|
|
if (latestTimestamp != null) ...[
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
formatDateTimeReadable(latestTimestamp),
|
|
textAlign: TextAlign.center,
|
|
style: const TextStyle(color: Colors.white70, fontSize: 13),
|
|
),
|
|
],
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _humidityStatusCard(AtmosphericConditionsState state, AtmosphericConditions? latestHistory) {
|
|
if (state.history.isEmpty) {
|
|
return _emptyCard('Status kelembapan belum ada data histori');
|
|
}
|
|
|
|
final status = _getHumidityStatus(latestHistory?.humidity ?? state.humidity);
|
|
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
'Status Kelembapan',
|
|
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
|
),
|
|
const SizedBox(height: 6),
|
|
Text(
|
|
status.title,
|
|
style: const TextStyle(fontWeight: FontWeight.w600),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
status.description,
|
|
style: const TextStyle(fontSize: 12, color: Colors.black87),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _historyChart(List<AtmosphericConditions> history) {
|
|
if (history.isEmpty) {
|
|
return _emptyCard("Grafik histori kelembapan belum ada data untuk tanggal ini");
|
|
}
|
|
|
|
final points = <FlSpot>[];
|
|
double minY = history.first.humidity;
|
|
double maxY = history.first.humidity;
|
|
|
|
for (int i = 0; i < history.length; i++) {
|
|
final humidity = history[i].humidity;
|
|
points.add(FlSpot(i.toDouble(), humidity));
|
|
|
|
if (humidity < minY) {
|
|
minY = humidity;
|
|
}
|
|
if (humidity > maxY) {
|
|
maxY = humidity;
|
|
}
|
|
}
|
|
|
|
final range = (maxY - minY).abs();
|
|
final padding = range < 1 ? 0.5 : range * 0.15;
|
|
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
"Grafik Histori Kelembapan",
|
|
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
_selectedDate == null ? 'Menampilkan semua tanggal' : 'Tanggal: $_dateFilterLabel',
|
|
style: const TextStyle(fontSize: 12, color: Colors.black54),
|
|
),
|
|
const SizedBox(height: 12),
|
|
SizedBox(
|
|
height: 220,
|
|
child: LineChart(
|
|
LineChartData(
|
|
minX: 0,
|
|
maxX: (history.length - 1).toDouble(),
|
|
minY: minY - padding,
|
|
maxY: maxY + padding,
|
|
gridData: FlGridData(show: true),
|
|
borderData: FlBorderData(show: false),
|
|
titlesData: FlTitlesData(
|
|
topTitles: AxisTitles(
|
|
sideTitles: SideTitles(showTitles: false),
|
|
),
|
|
rightTitles: AxisTitles(
|
|
sideTitles: SideTitles(showTitles: false),
|
|
),
|
|
leftTitles: AxisTitles(
|
|
sideTitles: SideTitles(
|
|
showTitles: true,
|
|
reservedSize: 44,
|
|
interval: range < 1 ? 0.5 : null,
|
|
getTitlesWidget: (value, meta) => Text(
|
|
value.toStringAsFixed(1),
|
|
style: const TextStyle(fontSize: 10),
|
|
),
|
|
),
|
|
),
|
|
bottomTitles: AxisTitles(
|
|
sideTitles: SideTitles(
|
|
showTitles: true,
|
|
interval: history.length > 6 ? (history.length / 5).ceilToDouble() : 1,
|
|
getTitlesWidget: (value, meta) {
|
|
final index = value.toInt();
|
|
if (index < 0 || index >= history.length) {
|
|
return const SizedBox.shrink();
|
|
}
|
|
return Padding(
|
|
padding: const EdgeInsets.only(top: 6),
|
|
child: Text(
|
|
formatClockTime(history[index].timestamp),
|
|
style: const TextStyle(fontSize: 10),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
),
|
|
lineBarsData: [
|
|
LineChartBarData(
|
|
spots: points,
|
|
isCurved: true,
|
|
color: Colors.blue,
|
|
barWidth: 3,
|
|
dotData: FlDotData(show: history.length <= 10),
|
|
belowBarData: BarAreaData(
|
|
show: true,
|
|
color: Colors.blue.withOpacity(0.15),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _emptyCard(String text) {
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(20),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
),
|
|
child: Text(
|
|
text,
|
|
style: const TextStyle(color: Colors.grey),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _HistoryTableCard extends StatefulWidget {
|
|
final List<AtmosphericConditions> history;
|
|
|
|
const _HistoryTableCard({required this.history});
|
|
|
|
@override
|
|
State<_HistoryTableCard> createState() => _HistoryTableCardState();
|
|
}
|
|
|
|
class _HistoryTableCardState extends State<_HistoryTableCard> {
|
|
static const int _rowsPerPage = 10;
|
|
int _currentPage = 0;
|
|
|
|
@override
|
|
void didUpdateWidget(covariant _HistoryTableCard oldWidget) {
|
|
super.didUpdateWidget(oldWidget);
|
|
|
|
final totalPages = _totalPages;
|
|
if (totalPages > 0 && _currentPage >= totalPages) {
|
|
_currentPage = totalPages - 1;
|
|
}
|
|
}
|
|
|
|
int get _totalPages {
|
|
if (widget.history.isEmpty) {
|
|
return 0;
|
|
}
|
|
return (widget.history.length / _rowsPerPage).ceil();
|
|
}
|
|
|
|
List<AtmosphericConditions> get _pageItems {
|
|
final reversedHistory = widget.history.reversed.toList();
|
|
final start = _currentPage * _rowsPerPage;
|
|
final end = (start + _rowsPerPage).clamp(0, reversedHistory.length);
|
|
return reversedHistory.sublist(start, end);
|
|
}
|
|
|
|
void _goToPreviousPage() {
|
|
if (_currentPage > 0) {
|
|
setState(() => _currentPage--);
|
|
}
|
|
}
|
|
|
|
void _goToNextPage() {
|
|
if (_currentPage < _totalPages - 1) {
|
|
setState(() => _currentPage++);
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (widget.history.isEmpty) {
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(20),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
),
|
|
child: const Text(
|
|
"Tabel histori kelembapan belum ada data untuk tanggal ini",
|
|
style: TextStyle(color: Colors.grey),
|
|
),
|
|
);
|
|
}
|
|
|
|
final pageItems = _pageItems;
|
|
final hasMultiplePages = _totalPages > 1;
|
|
|
|
return Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(20),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Text(
|
|
"Tabel Histori Kelembapan",
|
|
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
|
|
),
|
|
const SizedBox(height: 4),
|
|
Text(
|
|
"Halaman ${_currentPage + 1} dari $_totalPages · ${widget.history.length} data · ${_dateLabel}",
|
|
style: const TextStyle(color: Colors.grey, fontSize: 12),
|
|
),
|
|
const SizedBox(height: 12),
|
|
SingleChildScrollView(
|
|
scrollDirection: Axis.horizontal,
|
|
child: DataTable(
|
|
columns: const [
|
|
DataColumn(label: Text("No")),
|
|
DataColumn(label: Text("Tanggal/Waktu")),
|
|
DataColumn(label: Text("Kelembapan")),
|
|
],
|
|
rows: List<DataRow>.generate(pageItems.length, (index) {
|
|
final item = pageItems[index];
|
|
final absoluteIndex = (_currentPage * _rowsPerPage) + index + 1;
|
|
return DataRow(
|
|
cells: [
|
|
DataCell(Text(absoluteIndex.toString())),
|
|
DataCell(Text(formatDateTimeReadable(item.timestamp))),
|
|
DataCell(Text("${item.humidity.toStringAsFixed(1)} %")),
|
|
],
|
|
);
|
|
}),
|
|
),
|
|
),
|
|
if (hasMultiplePages) ...[
|
|
const SizedBox(height: 12),
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
TextButton.icon(
|
|
onPressed: _currentPage == 0 ? null : _goToPreviousPage,
|
|
icon: const Icon(Icons.chevron_left),
|
|
label: const Text('Sebelumnya'),
|
|
),
|
|
TextButton.icon(
|
|
onPressed: _currentPage >= _totalPages - 1 ? null : _goToNextPage,
|
|
icon: const Icon(Icons.chevron_right),
|
|
label: const Text('Berikutnya'),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
String get _dateLabel {
|
|
if (widget.history.isEmpty) {
|
|
return 'tidak ada data';
|
|
}
|
|
|
|
final first = widget.history.first.timestamp;
|
|
final last = widget.history.last.timestamp;
|
|
|
|
if (first.year == last.year && first.month == last.month && first.day == last.day) {
|
|
return formatDateOnlyReadable(first);
|
|
}
|
|
|
|
return '${formatDateOnlyReadable(first)} - ${formatDateOnlyReadable(last)}';
|
|
}
|
|
}
|
|
|
|
String formatDateOnlyReadable(DateTime timestamp) {
|
|
final day = timestamp.day.toString().padLeft(2, '0');
|
|
final month = _monthName(timestamp.month);
|
|
return '$day $month ${timestamp.year}';
|
|
}
|