The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1208 lines
48 KiB
Dart
1208 lines
48 KiB
Dart
// Weather (as the dashboard's weather page, plugins/weather): straight from Open-Meteo (free, no key) —
|
||
// the same fields as weather.py asks for. The title is the place picker: "Weather · <place> ▾" (Current location — the phone's
|
||
// coarse location, its town from OpenStreetMap — the dashboard's places, which stay, added ones, ✕ removes,
|
||
// and "Add a place…", Open-Meteo's place search); added places are kept on this phone until the app has synced settings;
|
||
// Each
|
||
// place's last answer is kept too (store meta), so it shows offline ("saved · …"); fetched again after
|
||
// 15 minutes, or pull down. One "now" card (icon + values, details on tap), the sun's arc, the next
|
||
// 48 hours, 14 days; icons = the dashboard's.
|
||
import 'dart:convert';
|
||
import 'dart:math';
|
||
|
||
import 'package:flutter/material.dart';
|
||
import 'package:http/http.dart' as http;
|
||
|
||
import '../app/location.dart';
|
||
import '../app/sync_service.dart';
|
||
import '../app/theme.dart';
|
||
import 'stations.dart';
|
||
|
||
class Place {
|
||
const Place(this.name, this.lat, this.lon);
|
||
final String name;
|
||
final double lat, lon;
|
||
}
|
||
|
||
/// The places built in (home first): --dart-define=HOME_PLACES="Home, XX|47.17|24.06;Town, YY|46.77|23.6"
|
||
/// (tool/publish.env) — none in a plain build: Current location + the ones added here. Added / removed
|
||
/// ones are kept on this phone (store meta wx_places).
|
||
final defaultPlaces = [
|
||
for (final p in const String.fromEnvironment('HOME_PLACES').split(';'))
|
||
if (p.split('|') case [final name, final lat, final lon] when double.tryParse(lat) != null && double.tryParse(lon) != null)
|
||
Place(name.trim(), double.parse(lat), double.parse(lon)),
|
||
];
|
||
|
||
const _forecast = 'https://api.open-meteo.com/v1/forecast';
|
||
const _airUrl = 'https://air-quality-api.open-meteo.com/v1/air-quality';
|
||
const _hourly =
|
||
'temperature_2m,apparent_temperature,relative_humidity_2m,dew_point_2m,precipitation_probability,'
|
||
'precipitation,snowfall,weather_code,cloud_cover,visibility,wind_speed_10m,wind_gusts_10m,wind_direction_10m,'
|
||
'uv_index,is_day,pressure_msl';
|
||
const _daily =
|
||
'weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,'
|
||
'sunrise,sunset,daylight_duration,uv_index_max,precipitation_sum,precipitation_probability_max,precipitation_hours,'
|
||
'wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant';
|
||
const _current =
|
||
'temperature_2m,apparent_temperature,relative_humidity_2m,dew_point_2m,weather_code,is_day,cloud_cover,'
|
||
'pressure_msl,wind_speed_10m,wind_gusts_10m,wind_direction_10m,precipitation,visibility,uv_index';
|
||
const _airCurrent = 'european_aqi,pm10,pm2_5,ozone,nitrogen_dioxide';
|
||
const _geocode = 'https://geocoding-api.open-meteo.com/v1/search';
|
||
const refreshAfter = Duration(minutes: 15);
|
||
|
||
/// weather.WMO: code → (icon code: assets/weather/<code>d|n.png, description)
|
||
const wmo = {
|
||
0: ('01', 'Clear sky'),
|
||
1: ('02', 'Mainly clear'),
|
||
2: ('03', 'Partly cloudy'),
|
||
3: ('04', 'Overcast'),
|
||
45: ('50', 'Fog'),
|
||
48: ('50', 'Rime fog'),
|
||
51: ('09', 'Light drizzle'),
|
||
53: ('09', 'Drizzle'),
|
||
55: ('09', 'Dense drizzle'),
|
||
56: ('09', 'Freezing drizzle'),
|
||
57: ('09', 'Freezing drizzle'),
|
||
61: ('10', 'Light rain'),
|
||
63: ('10', 'Rain'),
|
||
65: ('10', 'Heavy rain'),
|
||
66: ('10', 'Freezing rain'),
|
||
67: ('10', 'Freezing rain'),
|
||
71: ('13', 'Light snow'),
|
||
73: ('13', 'Snow'),
|
||
75: ('13', 'Heavy snow'),
|
||
77: ('13', 'Snow grains'),
|
||
80: ('09', 'Light showers'),
|
||
81: ('09', 'Showers'),
|
||
82: ('09', 'Violent showers'),
|
||
85: ('13', 'Snow showers'),
|
||
86: ('13', 'Heavy snow showers'),
|
||
95: ('11', 'Thunderstorm'),
|
||
96: ('11', 'Thunderstorm, hail'),
|
||
99: ('11', 'Thunderstorm, heavy hail'),
|
||
};
|
||
|
||
String wmoText(num? code) => wmo[(code ?? 0).toInt()]?.$2 ?? '—';
|
||
|
||
Widget wxIcon(num? code, {bool day = true, double size = 40}) =>
|
||
Image.asset('assets/weather/${wmo[(code ?? 0).toInt()]?.$1 ?? '03'}${day ? 'd' : 'n'}.png', width: size, height: size);
|
||
|
||
/// panel.temp_colour: by band, in °C
|
||
Color tempColour(num c) => c < 20
|
||
? const Color(0xFF6E9CFF)
|
||
: c < 23
|
||
? good
|
||
: c < 26
|
||
? accent
|
||
: c < 29
|
||
? const Color(0xFFFF9D5C)
|
||
: const Color(0xFFFF5F5F);
|
||
|
||
/// The dashboard's wind arrow (page.html: polygon 0,-9 6,7 0,3 -6,7 turned deg + 180): points where it
|
||
/// blows; [r] = half its height.
|
||
void paintWindArrow(Canvas c, Offset o, double deg, double r, {Color color = muted}) {
|
||
final a = (deg + 180) * pi / 180, k = r / 9;
|
||
Offset p(double x, double y) => o + Offset(x * cos(a) - y * sin(a), x * sin(a) + y * cos(a)) * k;
|
||
c.drawPath(Path()..addPolygon([p(0, -9), p(6, 7), p(0, 3), p(-6, 7)], true), Paint()..color = color);
|
||
}
|
||
|
||
class _Arrow extends CustomPainter {
|
||
_Arrow(this.deg);
|
||
final double deg;
|
||
@override
|
||
void paint(Canvas c, Size size) => paintWindArrow(c, size.center(Offset.zero), deg, size.height / 2 - 1);
|
||
@override
|
||
bool shouldRepaint(covariant _Arrow old) => old.deg != deg;
|
||
}
|
||
|
||
const _compass = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
|
||
String compass(num deg) => _compass[(deg / 45).round() % 8];
|
||
const _aqiBands = [
|
||
(20, 'Good', Color(0xFF50F0E6)),
|
||
(40, 'Fair', Color(0xFF50CCAA)),
|
||
(60, 'Moderate', Color(0xFFF0E641)),
|
||
(80, 'Poor', Color(0xFFFF5050)),
|
||
(100, 'Very poor', Color(0xFFC0305A)),
|
||
(1 << 30, 'Extremely poor', Color(0xFF9B3EA0)),
|
||
];
|
||
const _uvBands = [(3, 'low'), (6, 'moderate'), (8, 'high'), (11, 'very high'), (99, 'extreme')];
|
||
const _dows = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
|
||
String _ordinal(int d) => '$d${d % 100 >= 11 && d % 100 <= 13 ? 'th' : const {1: 'st', 2: 'nd', 3: 'rd'}[d % 10] ?? 'th'}';
|
||
|
||
class WeatherPage extends StatefulWidget {
|
||
const WeatherPage({super.key, required this.sync, this.actions = const []});
|
||
final SyncService sync;
|
||
final List<Widget> actions; // the shell's (sync icon)
|
||
@override
|
||
State<WeatherPage> createState() => _WeatherPageState();
|
||
}
|
||
|
||
class _WeatherPageState extends State<WeatherPage> {
|
||
late List<Place> places = _loadPlaces();
|
||
late int at = max(0, min(widget.sync.store.meta('wx_place'), places.length - 1)); // the last city picked
|
||
late bool here = widget.sync.store.meta('wx_here') == 1 || places.isEmpty; // Current location selected (no places: always)
|
||
String? hereName = ''; // the town where the phone is (reverse geocoding)
|
||
String? noFix; // Current location found none (not allowed / off / no fix): why — the error banner; home is shown
|
||
final pickKey = GlobalKey();
|
||
Map<String, dynamic>? data; // {fc, air, at (ms)}
|
||
(String, Map<String, dynamic>)? standIn; // nothing saved for this place yet: another place's, shown meanwhile
|
||
String? error;
|
||
bool loading = false;
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_show();
|
||
}
|
||
|
||
/// The places that stay: the dashboard's (Settings ▸ Weather, synced as "weather.place": home first), then
|
||
/// the build's HOME_PLACES; the ones added on this phone after them.
|
||
int fixed = 0;
|
||
|
||
List<Place> _loadPlaces() {
|
||
final synced = [
|
||
for (final r in widget.sync.store.rows('weather.place')..sort((a, b) => ((a['ord'] as num?) ?? 0).compareTo((b['ord'] as num?) ?? 0)))
|
||
if (r['name'] is String && r['lat'] is num && r['lon'] is num)
|
||
Place(r['name'] as String, (r['lat'] as num).toDouble(), (r['lon'] as num).toDouble()),
|
||
];
|
||
final base = [...synced, ...defaultPlaces.where((d) => !synced.any((p) => p.name == d.name))];
|
||
fixed = base.length;
|
||
final t = widget.sync.store.metaText('wx_places');
|
||
final added = [
|
||
for (final p in (t == null ? const [] : jsonDecode(t) as List))
|
||
Place(p['name'] as String, (p['lat'] as num).toDouble(), (p['lon'] as num).toDouble()),
|
||
].where((p) => !base.any((d) => d.name == p.name));
|
||
return [...base, ...added]; // the dashboard's / built-in places first, always
|
||
}
|
||
|
||
void _savePlaces() => widget.sync.store.setMetaText(
|
||
'wx_places',
|
||
jsonEncode([
|
||
for (final p in places.skip(fixed)) {'name': p.name, 'lat': p.lat, 'lon': p.lon},
|
||
]),
|
||
);
|
||
|
||
String get _placeName => here ? (hereName?.isNotEmpty ?? false ? hereName! : 'Current location') : places[at].name.split(',').first;
|
||
|
||
/// The town at those coordinates (OpenStreetMap's Nominatim, the coordinates rounded to ~1 km; kept per spot).
|
||
Future<void> _townOf(double lat, double lon) async {
|
||
final k = 'wx_town:${lat.toStringAsFixed(2)},${lon.toStringAsFixed(2)}';
|
||
var name = widget.sync.store.metaText(k);
|
||
if (name == null) {
|
||
try {
|
||
final r = await http
|
||
.get(
|
||
Uri.parse(
|
||
'https://nominatim.openstreetmap.org/reverse?format=jsonv2&zoom=10&accept-language=en'
|
||
'&lat=${lat.toStringAsFixed(2)}&lon=${lon.toStringAsFixed(2)}',
|
||
),
|
||
headers: {'User-Agent': 'dashPi-app/1 (personal weather)'},
|
||
)
|
||
.timeout(const Duration(seconds: 15));
|
||
final a = ((jsonDecode(r.body) as Map)['address'] as Map?) ?? const {};
|
||
name = (a['city'] ?? a['town'] ?? a['village'] ?? a['municipality'] ?? a['county']) as String?;
|
||
if (name != null) widget.sync.store.setMetaText(k, name);
|
||
} catch (_) {}
|
||
}
|
||
widget.sync.store.setMetaText('wx_here_name', name);
|
||
if (mounted) setState(() => hereName = name);
|
||
}
|
||
|
||
String get _key => here ? 'wx:@here' : 'wx:${places[at].name}';
|
||
|
||
void _show() {
|
||
hereName = widget.sync.store.metaText('wx_here_name');
|
||
final t = widget.sync.store.metaText(_key);
|
||
data = t == null ? null : jsonDecode(t) as Map<String, dynamic>;
|
||
error = null;
|
||
standIn = null;
|
||
if (data == null) {
|
||
// never a dark page: the last city's (or any) saved weather meanwhile
|
||
for (final p in [if (here && places.isNotEmpty) places[at], ...places]) {
|
||
final o = widget.sync.store.metaText('wx:${p.name}');
|
||
if (o != null) {
|
||
standIn = (p.name.split(',').first, jsonDecode(o) as Map<String, dynamic>);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
final fc0 = data?['fc'] as Map?;
|
||
if (here && (hereName ?? '').isEmpty && fc0 != null) { // the town of the saved forecast (its coordinates)
|
||
_townOf((fc0['latitude'] as num).toDouble(), (fc0['longitude'] as num).toDouble());
|
||
}
|
||
final age = data == null ? null : DateTime.now().difference(DateTime.fromMillisecondsSinceEpoch(data!['at'] as int));
|
||
if (age == null || age > refreshAfter) _fetch();
|
||
}
|
||
|
||
/// Where the phone is (Android's own location — app/location.dart; the town is enough). None found (not allowed,
|
||
/// switched off, no fix) → home (the first place), and the error banner on top says why (noFix).
|
||
Future<Place> _here() async {
|
||
var why = '';
|
||
final at = await whereAmI(none: (w) => why = w);
|
||
if (mounted) setState(() => noFix = at == null ? why : null);
|
||
if (at != null) return Place('Current location', at.lat, at.lon);
|
||
if (places.isEmpty) throw 'no location and no place added';
|
||
final home = places.first;
|
||
if (mounted) setState(() => hereName = home.name.split(',').first);
|
||
return home;
|
||
}
|
||
|
||
/// Current location found none: an error banner on top — why, what to do, and that home is shown instead.
|
||
Widget _noFixBanner(String why) {
|
||
final (what, todo) = switch (why) {
|
||
'location not allowed' => ('Location isn\'t allowed for this app', 'Android settings ▸ Apps ▸ dashPi ▸ Permissions ▸ Location.'),
|
||
'location off' => ('Location is switched off on this phone', 'Switch it on in the quick settings, then pull down.'),
|
||
_ => ('The phone couldn\'t tell where it is', 'Pull down to try again.'),
|
||
};
|
||
return Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 6, 12, 0),
|
||
child: Container(
|
||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
|
||
decoration: BoxDecoration(
|
||
color: bad.withValues(alpha: .16),
|
||
border: Border.all(color: bad.withValues(alpha: .7)),
|
||
borderRadius: BorderRadius.circular(10),
|
||
),
|
||
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||
const Icon(Icons.location_off, size: 20, color: bad),
|
||
const SizedBox(width: 10),
|
||
Expanded(
|
||
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||
Text(what, style: const TextStyle(fontWeight: FontWeight.bold, color: bad)),
|
||
Text(todo, style: const TextStyle(fontSize: 13)),
|
||
Text(places.isEmpty ? 'Add a place with the location button to see one instead.'
|
||
: 'Showing ${places.first.name.split(',').first} (home) instead.',
|
||
style: const TextStyle(fontSize: 13, color: muted)),
|
||
]),
|
||
),
|
||
]),
|
||
),
|
||
);
|
||
}
|
||
|
||
Future<void> _fetch() async {
|
||
final key = _key;
|
||
setState(() => loading = true);
|
||
try {
|
||
final p = here ? await _here() : places[at];
|
||
if (here && p.name == 'Current location') _townOf(p.lat, p.lon);
|
||
final q = 'latitude=${p.lat}&longitude=${p.lon}&timezone=auto';
|
||
final fc = await http
|
||
.get(Uri.parse('$_forecast?$q&hourly=$_hourly&daily=$_daily¤t=$_current&forecast_days=16&wind_speed_unit=ms'))
|
||
.timeout(const Duration(seconds: 20));
|
||
if (fc.statusCode != 200) throw 'Open-Meteo: ${fc.statusCode}';
|
||
Map<String, dynamic>? air;
|
||
try {
|
||
final a = await http.get(Uri.parse('$_airUrl?$q¤t=$_airCurrent')).timeout(const Duration(seconds: 20));
|
||
if (a.statusCode == 200) air = jsonDecode(a.body) as Map<String, dynamic>;
|
||
} catch (_) {} // the air quality is optional (as on the dashboard)
|
||
final d = {'fc': jsonDecode(fc.body), 'air': air, 'at': DateTime.now().millisecondsSinceEpoch};
|
||
widget.sync.store.setMetaText(key, jsonEncode(d));
|
||
if (mounted && _key == key) {
|
||
setState(() {
|
||
data = d;
|
||
standIn = null;
|
||
error = null;
|
||
});
|
||
}
|
||
} catch (e) {
|
||
debugPrint('weather: $e');
|
||
if (mounted && _key == key) {
|
||
setState(() => error = 'offline');
|
||
}
|
||
} finally {
|
||
if (mounted) setState(() => loading = false);
|
||
}
|
||
}
|
||
|
||
void _select({bool? toHere, int? city}) {
|
||
if (city != null) {
|
||
at = city;
|
||
widget.sync.store.setMeta('wx_place', city);
|
||
}
|
||
here = toHere ?? false;
|
||
widget.sync.store.setMeta('wx_here', here ? 1 : 0);
|
||
setState(_show);
|
||
}
|
||
|
||
/// The location chip → Current location, the dashboard's places (stay), the added ones (✕ removes).
|
||
Future<void> _pick() async {
|
||
final box = pickKey.currentContext!.findRenderObject() as RenderBox;
|
||
final o = box.localToGlobal(Offset(0, box.size.height + 4));
|
||
Widget item(String name, bool on, {IconData? icon, VoidCallback? remove}) => Row(
|
||
children: [
|
||
if (icon != null) ...[Icon(icon, size: 18, color: on ? accent : Colors.white), const SizedBox(width: 8)],
|
||
Expanded(
|
||
child: Text(
|
||
name,
|
||
style: TextStyle(color: on ? accent : null, fontWeight: on ? FontWeight.bold : null),
|
||
),
|
||
),
|
||
if (remove != null)
|
||
IconButton(
|
||
tooltip: 'Remove',
|
||
visualDensity: VisualDensity.compact,
|
||
onPressed: remove,
|
||
icon: const Icon(Icons.close, size: 18, color: muted),
|
||
),
|
||
],
|
||
);
|
||
final pick = await showMenu<int>(
|
||
context: context,
|
||
color: card2,
|
||
position: RelativeRect.fromLTRB(o.dx, o.dy, o.dx + 1, o.dy + 1),
|
||
items: [
|
||
PopupMenuItem(
|
||
value: -1,
|
||
child: item(hereName?.isNotEmpty ?? false ? 'Current location · $hereName' : 'Current location', here, icon: Icons.my_location),
|
||
),
|
||
const PopupMenuDivider(),
|
||
for (var i = 0; i < places.length; i++)
|
||
PopupMenuItem(
|
||
value: i,
|
||
child: item(
|
||
places[i].name,
|
||
!here && i == at,
|
||
remove: i < fixed
|
||
? null
|
||
: () {
|
||
Navigator.pop(context);
|
||
_remove(i);
|
||
},
|
||
),
|
||
),
|
||
const PopupMenuDivider(),
|
||
PopupMenuItem(value: -2, child: item('Add a place…', false, icon: Icons.add)),
|
||
],
|
||
);
|
||
if (pick == -2) return _add();
|
||
if (pick == -1) return here ? _fetch() : _select(toHere: true);
|
||
if (pick != null) _select(city: pick);
|
||
}
|
||
|
||
/// + → search a place by name (Open-Meteo's geocoding, as the dashboard's Settings) → added and selected.
|
||
Future<void> _add() async {
|
||
final p = await showModalBottomSheet<Place>(
|
||
context: context,
|
||
isScrollControlled: true,
|
||
backgroundColor: card,
|
||
builder: (_) => const _PlaceSearch(),
|
||
);
|
||
if (p == null) return;
|
||
var i = places.indexWhere((x) => x.name == p.name);
|
||
if (i < 0) {
|
||
places.add(p);
|
||
_savePlaces();
|
||
i = places.length - 1;
|
||
}
|
||
_select(city: i);
|
||
}
|
||
|
||
void _remove(int i) {
|
||
widget.sync.store.setMetaText('wx:${places[i].name}', null);
|
||
places.removeAt(i);
|
||
_savePlaces();
|
||
_select(toHere: here || places.isEmpty, city: i == at ? 0 : (i < at ? at - 1 : at));
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final title = Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
const Text('Weather'),
|
||
const Text(' · ', style: TextStyle(color: muted)),
|
||
Flexible(
|
||
child: InkWell(
|
||
key: pickKey,
|
||
onTap: _pick,
|
||
borderRadius: BorderRadius.circular(8),
|
||
child: Row(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
if (here)
|
||
const Padding(
|
||
padding: EdgeInsets.only(right: 4),
|
||
child: Icon(Icons.my_location, size: 18, color: Colors.white),
|
||
),
|
||
Flexible(
|
||
child: Text(
|
||
_placeName,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: const TextStyle(color: Colors.white),
|
||
),
|
||
),
|
||
const Icon(Icons.arrow_drop_down, color: Colors.white),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
],
|
||
);
|
||
final shown = data ?? standIn?.$2;
|
||
final fc = shown?['fc'] as Map<String, dynamic>?;
|
||
// what the page shows while it's not this place's fresh weather — a slim banner on top
|
||
final what = data == null
|
||
? (standIn == null ? null : 'Showing ${standIn!.$1}')
|
||
: here
|
||
? 'Showing your last location'
|
||
: null;
|
||
final offline = error == 'offline';
|
||
final banner = what == null || (!loading && error == null)
|
||
? null
|
||
: '$what — ${loading
|
||
? (here ? 'finding where you are…' : 'trying to update…')
|
||
: offline
|
||
? 'no connection, pull down to try again'
|
||
: error!}';
|
||
return Scaffold(
|
||
appBar: AppBar(title: title, actions: [
|
||
IconButton(
|
||
tooltip: 'At home (the stations)',
|
||
icon: const Icon(Icons.home_outlined, color: accent),
|
||
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => StationsPage(sync: widget.sync))),
|
||
),
|
||
...widget.actions,
|
||
]),
|
||
body: RefreshIndicator(
|
||
onRefresh: _fetch,
|
||
child: ListView(
|
||
physics: const AlwaysScrollableScrollPhysics(),
|
||
padding: const EdgeInsets.only(top: 4, bottom: 24),
|
||
children: [
|
||
if (here && noFix != null) _noFixBanner(noFix!),
|
||
if (banner != null)
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 6, 12, 0),
|
||
child: Container(
|
||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||
decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(10)),
|
||
child: Row(
|
||
children: [
|
||
if (loading)
|
||
const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2))
|
||
else
|
||
const Icon(Icons.info_outline, size: 16, color: muted),
|
||
const SizedBox(width: 10),
|
||
Expanded(child: Text(banner, style: const TextStyle(fontSize: 13))),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
if (fc == null && loading)
|
||
const Padding(
|
||
padding: EdgeInsets.all(40),
|
||
child: Center(child: CircularProgressIndicator()),
|
||
),
|
||
if (fc == null && !loading && error != null)
|
||
Padding(
|
||
padding: const EdgeInsets.all(24),
|
||
child: Text(
|
||
offline ? 'No weather saved for this place yet — no connection. Pull down to try again.' : error!,
|
||
style: const TextStyle(color: muted),
|
||
),
|
||
),
|
||
if (fc != null) ..._page(fc, shown!['air'] as Map<String, dynamic>?, DateTime.fromMillisecondsSinceEpoch(shown['at'] as int)),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
List<Widget> _page(Map<String, dynamic> fc, Map<String, dynamic>? air, DateTime fetched) {
|
||
final cur = (fc['current'] as Map).cast<String, dynamic>(), d = (fc['daily'] as Map).cast<String, dynamic>();
|
||
num n(Map m, String k, [int? i]) => ((i == null ? m[k] : (m[k] as List)[i]) as num?) ?? 0;
|
||
final uv = n(cur, 'uv_index'), vis = cur['visibility'] as num?, deg = n(cur, 'wind_direction_10m');
|
||
final t = '${fetched.hour.toString().padLeft(2, '0')}:${fetched.minute.toString().padLeft(2, '0')}';
|
||
final a = (air?['current'] as Map?)?.cast<String, dynamic>();
|
||
final rows = [
|
||
[
|
||
_Stat(
|
||
CustomPaint(size: const Size(16, 16), painter: _Arrow(deg.toDouble())),
|
||
'${n(cur, 'wind_speed_10m').round()} m/s',
|
||
'Wind ${compass(deg)}, gusts ${n(cur, 'wind_gusts_10m').round()} m/s — the arrow points where it blows',
|
||
),
|
||
_Stat(
|
||
const Icon(Icons.water_drop_outlined, size: 16, color: Color(0xFF5CC8FF)),
|
||
'${n(cur, 'relative_humidity_2m').round()}%',
|
||
'Humidity',
|
||
),
|
||
_Stat(const Icon(Icons.speed, size: 16, color: muted), '${n(cur, 'pressure_msl').round()}', 'Pressure, hPa'),
|
||
_Stat(
|
||
const Icon(Icons.wb_sunny_outlined, size: 16, color: accent),
|
||
'UV ${uv.round()}',
|
||
'UV index ${uv.round()} — ${_uvBands.firstWhere((b) => uv < b.$1).$2} (today\'s top ${n(d, 'uv_index_max', 0).round()})',
|
||
),
|
||
],
|
||
[
|
||
_Stat(const Icon(Icons.cloud_outlined, size: 16, color: muted), '${n(cur, 'cloud_cover').round()}%', 'Cloud cover'),
|
||
_Stat(
|
||
const Icon(Icons.visibility_outlined, size: 16, color: muted),
|
||
vis == null ? '—' : '${(vis / 1000).round()} km',
|
||
'Visibility',
|
||
),
|
||
_Stat(
|
||
const Icon(Icons.umbrella_outlined, size: 16, color: Color(0xFF5CC8FF)),
|
||
'${n(d, 'precipitation_sum', 0).toStringAsFixed(1)} mm',
|
||
'Rain today · chance ${n(d, 'precipitation_probability_max', 0).round()}%',
|
||
),
|
||
_Stat(const Icon(Icons.thermostat, size: 16, color: muted), '${n(cur, 'dew_point_2m').round()}°', 'Dew point'),
|
||
],
|
||
];
|
||
return [
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
|
||
child: Card(
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Row(
|
||
children: [
|
||
wxIcon(cur['weather_code'] as num?, day: n(cur, 'is_day') == 1, size: 92),
|
||
const SizedBox(width: 14),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(
|
||
'${n(cur, 'temperature_2m').round()}°',
|
||
style: TextStyle(
|
||
fontSize: 48,
|
||
fontWeight: FontWeight.bold,
|
||
height: 1.0,
|
||
color: tempColour(n(cur, 'temperature_2m')),
|
||
),
|
||
),
|
||
Text(wmoText(cur['weather_code'] as num?), style: const TextStyle(fontSize: 16)),
|
||
Text(
|
||
'feels ${n(cur, 'apparent_temperature').round()}° · '
|
||
'↑ ${n(d, 'temperature_2m_max', 0).round()}° ↓ ${n(d, 'temperature_2m_min', 0).round()}°',
|
||
style: const TextStyle(color: muted),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
),
|
||
const SizedBox(height: 14),
|
||
for (final r in rows)
|
||
Padding(
|
||
padding: const EdgeInsets.only(bottom: 8),
|
||
child: Row(children: [for (final st in r) Expanded(child: st)]),
|
||
),
|
||
Text(
|
||
loading
|
||
? 'updating…'
|
||
: error == 'offline'
|
||
? 'saved · $t (offline)'
|
||
: 'updated $t',
|
||
textAlign: TextAlign.right,
|
||
style: const TextStyle(color: muted, fontSize: 11.5),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
),
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 0),
|
||
child: IntrinsicHeight(
|
||
child: Row(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
Expanded(
|
||
child: _SunCard(
|
||
sunrise: (d['sunrise'] as List)[0] as String,
|
||
sunset: (d['sunset'] as List)[0] as String,
|
||
now: (cur['time'] as String?) ?? '',
|
||
daylight: n(d, 'daylight_duration', 0).toDouble(),
|
||
),
|
||
),
|
||
if (a?['european_aqi'] != null) ...[const SizedBox(width: 10), Expanded(child: _AirCard(a: a!))],
|
||
],
|
||
),
|
||
),
|
||
),
|
||
Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 0),
|
||
child: Card(
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(0, 12, 0, 8),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
const Padding(
|
||
padding: EdgeInsets.only(left: 14, bottom: 4),
|
||
child: Text('Next 48 hours', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
|
||
),
|
||
_Hours(fc: fc),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
),
|
||
Padding(padding: const EdgeInsets.fromLTRB(12, 10, 12, 0), child: _days(d)),
|
||
];
|
||
}
|
||
|
||
Widget _days(Map<String, dynamic> d) {
|
||
final count = min(14, (d['time'] as List).length);
|
||
List<num> col(String k) => [for (var i = 0; i < count; i++) ((d[k] as List)[i] as num?) ?? 0];
|
||
final hi = col('temperature_2m_max'), lo = col('temperature_2m_min');
|
||
final dmin = lo.reduce(min) - 1, dmax = hi.reduce(max) + 1;
|
||
return Card(
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 6),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
const Text('14 days', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
|
||
const SizedBox(height: 4),
|
||
for (var i = 0; i < count; i++)
|
||
Builder(
|
||
builder: (context) {
|
||
final day = DateTime.parse((d['time'] as List)[i] as String);
|
||
final weekend = day.weekday >= 6;
|
||
return Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
message:
|
||
'${wmoText(col('weather_code')[i])} · rain ${col('precipitation_sum')[i].toStringAsFixed(1)} mm · '
|
||
'wind ${col('wind_speed_10m_max')[i].round()} m/s ${compass(col('wind_direction_10m_dominant')[i])} · '
|
||
'UV ${col('uv_index_max')[i].round()}',
|
||
child: Padding(
|
||
padding: const EdgeInsets.symmetric(vertical: 3),
|
||
child: Row(
|
||
children: [
|
||
SizedBox(
|
||
width: 62,
|
||
child: Text(
|
||
i == 0 ? 'Today' : '${_dows[day.weekday - 1]} ${_ordinal(day.day)}',
|
||
style: TextStyle(color: weekend ? accent : null, fontWeight: i == 0 ? FontWeight.bold : null),
|
||
),
|
||
),
|
||
wxIcon(col('weather_code')[i], size: 34),
|
||
SizedBox(
|
||
width: 44,
|
||
child: Text(
|
||
'${col('precipitation_probability_max')[i].round()}%',
|
||
textAlign: TextAlign.right,
|
||
style: TextStyle(
|
||
color: col('precipitation_probability_max')[i] >= 50 ? const Color(0xFF5CC8FF) : muted,
|
||
fontSize: 13,
|
||
),
|
||
),
|
||
),
|
||
const SizedBox(width: 10),
|
||
SizedBox(
|
||
width: 30,
|
||
child: Text(
|
||
'${lo[i].round()}°',
|
||
textAlign: TextAlign.right,
|
||
style: TextStyle(color: tempColour(lo[i])),
|
||
),
|
||
),
|
||
Expanded(
|
||
child: LayoutBuilder(
|
||
builder: (context, box) {
|
||
final w = box.maxWidth - 16;
|
||
final a = (lo[i] - dmin) / (dmax - dmin) * w, b = (hi[i] - dmin) / (dmax - dmin) * w;
|
||
return Container(
|
||
height: 6,
|
||
margin: const EdgeInsets.symmetric(horizontal: 8),
|
||
decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(3)),
|
||
child: Stack(
|
||
children: [
|
||
Positioned(
|
||
left: a,
|
||
width: max(4, b - a),
|
||
top: 0,
|
||
bottom: 0,
|
||
child: Container(
|
||
decoration: BoxDecoration(
|
||
borderRadius: BorderRadius.circular(3),
|
||
gradient: LinearGradient(colors: [tempColour(lo[i]), tempColour(hi[i])]),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
},
|
||
),
|
||
),
|
||
SizedBox(
|
||
width: 30,
|
||
child: Text(
|
||
'${hi[i].round()}°',
|
||
style: TextStyle(color: tempColour(hi[i]), fontWeight: FontWeight.bold),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// The next 48 hours from the current hour (the place's own time): temperature (+ feels-like dashed),
|
||
/// rain chance bars (darker from 0.1 mm), every 3 hours the hour, icon, temperature and wind — scrolls sideways.
|
||
class _Hours extends StatelessWidget {
|
||
const _Hours({required this.fc});
|
||
final Map<String, dynamic> fc;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final h = (fc['hourly'] as Map).cast<String, dynamic>();
|
||
final cur = (fc['current'] as Map).cast<String, dynamic>();
|
||
final times = (h['time'] as List).cast<String>();
|
||
final stamp = '${((cur['time'] as String?) ?? times.first).substring(0, 13)}:00';
|
||
final i0 = max(0, times.indexWhere((t) => t.compareTo(stamp) >= 0));
|
||
final idx = [for (var i = i0; i < min(i0 + 48, times.length); i++) i];
|
||
num v(String k, int i) => ((h[k] as List)[i] as num?) ?? 0;
|
||
const step = 20.0, ml = 16.0;
|
||
final width = ml * 2 + step * (idx.length - 1);
|
||
return SingleChildScrollView(
|
||
scrollDirection: Axis.horizontal,
|
||
child: SizedBox(
|
||
width: width,
|
||
height: 172,
|
||
child: Stack(
|
||
children: [
|
||
CustomPaint(size: Size(width, 172), painter: _HoursPainter(h, idx, step, ml)),
|
||
for (var k = 0; k < idx.length; k += 3)
|
||
Positioned(
|
||
left: ml + k * step - 14,
|
||
top: 17,
|
||
width: 28,
|
||
child: wxIcon(v('weather_code', idx[k]), day: v('is_day', idx[k]) == 1, size: 28),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
class _HoursPainter extends CustomPainter {
|
||
_HoursPainter(this.h, this.idx, this.step, this.ml);
|
||
final Map<String, dynamic> h;
|
||
final List<int> idx;
|
||
final double step, ml;
|
||
|
||
@override
|
||
void paint(Canvas c, Size size) {
|
||
num v(String k, int i) => ((h[k] as List)[i] as num?) ?? 0;
|
||
final temps = [for (final i in idx) v('temperature_2m', i).toDouble()];
|
||
final feels = [for (final i in idx) v('apparent_temperature', i).toDouble()];
|
||
final lo = [...temps, ...feels].reduce(min) - 1, hi = [...temps, ...feels].reduce(max) + 1;
|
||
const top = 66.0, bottom = 100.0, barTop = 112.0, barH = 24.0;
|
||
double x(int k) => ml + k * step;
|
||
double y(double t) => top + (hi - t) / (hi - lo) * (bottom - top);
|
||
void label(String s, Offset o, {Color color = muted, double size = 11, FontWeight? w}) {
|
||
final tp = TextPainter(
|
||
text: TextSpan(
|
||
text: s,
|
||
style: TextStyle(color: color, fontSize: size, fontWeight: w),
|
||
),
|
||
textDirection: TextDirection.ltr,
|
||
)..layout();
|
||
tp.paint(c, o - Offset(tp.width / 2, 0));
|
||
}
|
||
|
||
// day separators
|
||
for (var k = 1; k < idx.length; k++) {
|
||
final t = (h['time'] as List)[idx[k]] as String;
|
||
if (t.substring(11, 13) == '00') {
|
||
c.drawLine(
|
||
Offset(x(k), 0),
|
||
Offset(x(k), size.height),
|
||
Paint()
|
||
..color = card2
|
||
..strokeWidth = 1,
|
||
);
|
||
final d = DateTime.parse(t);
|
||
final tp = TextPainter(
|
||
text: TextSpan(
|
||
text: '${_dows[d.weekday - 1]} ${_ordinal(d.day)}',
|
||
style: const TextStyle(color: accent, fontSize: 11),
|
||
),
|
||
textDirection: TextDirection.ltr,
|
||
)..layout();
|
||
tp.paint(c, Offset(x(k) + 3, 46));
|
||
}
|
||
}
|
||
// rain chance bars
|
||
final bw = step * 0.7;
|
||
for (var k = 0; k < idx.length; k++) {
|
||
final p = v('precipitation_probability', idx[k]).toDouble(), mm = v('precipitation', idx[k]).toDouble();
|
||
final hh = p / 100 * barH;
|
||
if (hh > 0) {
|
||
c.drawRect(
|
||
Rect.fromLTWH(x(k) - bw / 2, barTop + barH - hh, bw, hh),
|
||
Paint()..color = const Color(0xFF5CC8FF).withValues(alpha: mm >= 0.1 ? .85 : .35),
|
||
);
|
||
}
|
||
}
|
||
// feels-like (dashed) + temperature
|
||
final fp = Paint()
|
||
..color = muted
|
||
..strokeWidth = 1.2
|
||
..style = PaintingStyle.stroke;
|
||
for (var k = 0; k + 1 < idx.length; k++) {
|
||
if (k.isEven) c.drawLine(Offset(x(k), y(feels[k])), Offset(x(k + 1), y(feels[k + 1])), fp);
|
||
}
|
||
final path = Path()..moveTo(x(0), y(temps[0]));
|
||
for (var k = 1; k < idx.length; k++) {
|
||
path.lineTo(x(k), y(temps[k]));
|
||
}
|
||
c.drawPath(
|
||
path,
|
||
Paint()
|
||
..color = accent
|
||
..strokeWidth = 2.2
|
||
..style = PaintingStyle.stroke
|
||
..strokeJoin = StrokeJoin.round,
|
||
);
|
||
// every 3 hours: hour, temperature, rain %, wind
|
||
for (var k = 0; k < idx.length; k += 3) {
|
||
final i = idx[k];
|
||
label(((h['time'] as List)[i] as String).substring(11, 13), Offset(x(k), 1), color: Colors.white, size: 11.5);
|
||
c.drawCircle(Offset(x(k), y(temps[k])), 3, Paint()..color = accent);
|
||
label('${temps[k].round()}°', Offset(x(k), y(temps[k]) - 16), color: tempColour(temps[k]), size: 11.5, w: FontWeight.bold);
|
||
final p = v('precipitation_probability', i).round();
|
||
if (p > 0) label('$p%', Offset(x(k), barTop + barH - p / 100 * barH - 12), color: const Color(0xFF5CC8FF), size: 9.5);
|
||
// wind: an arrow pointing where it blows, + speed
|
||
final o = Offset(x(k), barTop + barH + 12);
|
||
paintWindArrow(c, o, v('wind_direction_10m', i).toDouble(), 6.5);
|
||
label('${v('wind_speed_10m', i).round()}', Offset(x(k), o.dy + 7), size: 10);
|
||
}
|
||
}
|
||
|
||
@override
|
||
bool shouldRepaint(covariant _HoursPainter old) => true;
|
||
}
|
||
|
||
/// One value of the "now" card: a small icon + the value (what it is and more on tap).
|
||
class _Stat extends StatelessWidget {
|
||
const _Stat(this.icon, this.value, this.tip);
|
||
final Widget icon;
|
||
final String value, tip;
|
||
@override
|
||
Widget build(BuildContext context) => Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
showDuration: const Duration(seconds: 6),
|
||
message: tip,
|
||
child: Row(
|
||
children: [
|
||
icon,
|
||
const SizedBox(width: 5),
|
||
Flexible(
|
||
child: Text(value, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13.5)),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
/// Sunrise → sunset as an arc over the horizon, the sun where it is now (the place's own time),
|
||
/// the daylight in between.
|
||
class _SunCard extends StatelessWidget {
|
||
const _SunCard({required this.sunrise, required this.sunset, required this.now, required this.daylight});
|
||
final String sunrise, sunset, now; // ISO, the place's local time
|
||
final double daylight; // s
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final a = DateTime.parse(sunrise), z = DateTime.parse(sunset), t = DateTime.tryParse(now);
|
||
final f = t == null ? null : t.difference(a).inSeconds / max(1, z.difference(a).inSeconds);
|
||
String hm(DateTime d) => '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
|
||
final left = f != null && f > 0 && f < 1 ? z.difference(t!) : null;
|
||
const small = TextStyle(fontSize: 12.5, fontWeight: FontWeight.bold);
|
||
return Card(
|
||
child: Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
message:
|
||
'Daylight today: sunrise → sunset. '
|
||
'${left != null
|
||
? '${left.inHours} h ${(left.inMinutes % 60).toString().padLeft(2, '0')} min of it left'
|
||
: f != null && f >= 1
|
||
? 'The sun has set'
|
||
: 'Before sunrise'}',
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(10, 10, 10, 8),
|
||
child: Column(
|
||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||
children: [
|
||
SizedBox(
|
||
height: 52,
|
||
child: Stack(
|
||
children: [
|
||
Positioned.fill(top: 7, child: CustomPaint(painter: _SunPainter(f))),
|
||
Align(
|
||
alignment: Alignment.topCenter,
|
||
child: Container(
|
||
color: card,
|
||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||
child: Text(
|
||
'${daylight ~/ 3600} h ${(daylight % 3600 ~/ 60).toString().padLeft(2, '0')} min',
|
||
style: const TextStyle(fontSize: 12.5),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
const SizedBox(height: 4),
|
||
Row(
|
||
children: [
|
||
Text('↑ ${hm(a)}', style: small),
|
||
const Spacer(),
|
||
Text('↓ ${hm(z)}', style: small),
|
||
],
|
||
),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// European air quality index: the number in its band's colour, where it sits on the scale, the parts on tap.
|
||
class _AirCard extends StatelessWidget {
|
||
const _AirCard({required this.a});
|
||
final Map<String, dynamic> a;
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
final aqi = (a['european_aqi'] as num?) ?? 0;
|
||
final band = _aqiBands.firstWhere((b) => aqi < b.$1);
|
||
final parts = [
|
||
('pm2_5', 'PM2.5'),
|
||
('pm10', 'PM10'),
|
||
('ozone', 'O₃'),
|
||
('nitrogen_dioxide', 'NO₂'),
|
||
].where((p) => a[p.$1] != null).map((p) => '${p.$2} ${(a[p.$1] as num).round()}');
|
||
return Card(
|
||
child: Tooltip(
|
||
triggerMode: TooltipTriggerMode.tap,
|
||
showDuration: const Duration(seconds: 8),
|
||
message:
|
||
'European air quality index: 0–20 good, 20–40 fair, 40–60 moderate, 60–80 poor, 80–100 very poor\n'
|
||
'${parts.join(' · ')} µg/m³',
|
||
child: Padding(
|
||
padding: const EdgeInsets.fromLTRB(12, 10, 12, 8),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||
children: [
|
||
const Text('AIR QUALITY', style: TextStyle(color: muted, fontSize: 10.5)),
|
||
Row(
|
||
crossAxisAlignment: CrossAxisAlignment.baseline,
|
||
textBaseline: TextBaseline.alphabetic,
|
||
children: [
|
||
Text(
|
||
'${aqi.round()}',
|
||
style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold, color: band.$3),
|
||
),
|
||
const SizedBox(width: 6),
|
||
Flexible(
|
||
child: Text(
|
||
band.$2,
|
||
overflow: TextOverflow.ellipsis,
|
||
style: TextStyle(color: band.$3, fontSize: 13),
|
||
),
|
||
),
|
||
],
|
||
),
|
||
SizedBox(
|
||
height: 12,
|
||
width: double.infinity,
|
||
child: CustomPaint(painter: _AqiScale(aqi.toDouble())),
|
||
),
|
||
const SizedBox(height: 4),
|
||
Text(parts.take(2).join(' · '), style: const TextStyle(color: muted, fontSize: 11.5)),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|
||
|
||
/// The index's bands as one bar (0–100), a marker where it is now.
|
||
class _AqiScale extends CustomPainter {
|
||
_AqiScale(this.v);
|
||
final double v;
|
||
@override
|
||
void paint(Canvas c, Size size) {
|
||
final r = Rect.fromLTWH(0, size.height / 2 - 2.5, size.width, 5);
|
||
c.drawRRect(
|
||
RRect.fromRectAndRadius(r, const Radius.circular(3)),
|
||
Paint()..shader = LinearGradient(colors: [for (final b in _aqiBands.take(5)) b.$3]).createShader(r),
|
||
);
|
||
final x = (min(v, 100) / 100 * size.width).clamp(4.0, size.width - 4);
|
||
c.drawRRect(
|
||
RRect.fromRectAndRadius(Rect.fromCenter(center: Offset(x, size.height / 2), width: 8, height: 12), const Radius.circular(3)),
|
||
Paint()..color = card,
|
||
);
|
||
c.drawRRect(
|
||
RRect.fromRectAndRadius(Rect.fromCenter(center: Offset(x, size.height / 2), width: 5, height: 9), const Radius.circular(2)),
|
||
Paint()..color = Colors.white,
|
||
);
|
||
}
|
||
|
||
@override
|
||
bool shouldRepaint(covariant _AqiScale old) => old.v != v;
|
||
}
|
||
|
||
class _SunPainter extends CustomPainter {
|
||
_SunPainter(this.f);
|
||
final double? f; // 0 = sunrise … 1 = sunset (outside = night)
|
||
|
||
@override
|
||
void paint(Canvas c, Size size) {
|
||
final w = size.width, h = size.height - 6;
|
||
final rect = Rect.fromLTRB(6, 6, w - 6, 6 + (h - 6) * 2); // the top half of this oval = the sun's path
|
||
Offset at(double x) {
|
||
final a = pi + pi * x.clamp(0, 1);
|
||
return Offset(rect.center.dx + rect.width / 2 * cos(a), rect.center.dy + rect.height / 2 * sin(a));
|
||
}
|
||
|
||
// the horizon
|
||
c.drawLine(
|
||
Offset(0, h),
|
||
Offset(w, h),
|
||
Paint()
|
||
..color = card2
|
||
..strokeWidth = 1.5,
|
||
);
|
||
// the whole path, dashed
|
||
final track = Paint()
|
||
..color = muted.withValues(alpha: .45)
|
||
..strokeWidth = 1.5
|
||
..style = PaintingStyle.stroke;
|
||
for (var x = 0.0; x < 1; x += 0.04) {
|
||
c.drawArc(rect, pi + pi * x, pi * 0.022, false, track);
|
||
}
|
||
final day = f != null && f! > 0 && f! < 1;
|
||
if (day) {
|
||
// the part of the day gone: a warm glow under the path + a solid line
|
||
final path = Path()..moveTo(rect.left, h);
|
||
for (var x = 0.0; x <= f!; x += 0.01) {
|
||
path.lineTo(at(x).dx, at(x).dy);
|
||
}
|
||
path.lineTo(at(f!).dx, h);
|
||
path.close();
|
||
c.drawPath(
|
||
path,
|
||
Paint()
|
||
..shader = LinearGradient(
|
||
begin: Alignment.topCenter,
|
||
end: Alignment.bottomCenter,
|
||
colors: [accent.withValues(alpha: .28), accent.withValues(alpha: .02)],
|
||
).createShader(rect),
|
||
);
|
||
c.drawArc(
|
||
rect,
|
||
pi,
|
||
pi * f!,
|
||
false,
|
||
Paint()
|
||
..color = accent
|
||
..strokeWidth = 2.5
|
||
..style = PaintingStyle.stroke
|
||
..strokeCap = StrokeCap.round,
|
||
);
|
||
final s = at(f!);
|
||
c.drawCircle(s, 9, Paint()..color = accent.withValues(alpha: .25));
|
||
c.drawCircle(s, 5.5, Paint()..color = accent);
|
||
}
|
||
// sunrise / sunset marks on the horizon
|
||
for (final x in [rect.left, rect.right]) {
|
||
c.drawCircle(Offset(x, h), 2.5, Paint()..color = day ? accent : muted);
|
||
}
|
||
}
|
||
|
||
@override
|
||
bool shouldRepaint(covariant _SunPainter old) => old.f != f;
|
||
}
|
||
|
||
/// Search a place by name (Open-Meteo geocoding) → the picked one.
|
||
class _PlaceSearch extends StatefulWidget {
|
||
const _PlaceSearch();
|
||
@override
|
||
State<_PlaceSearch> createState() => _PlaceSearchState();
|
||
}
|
||
|
||
class _PlaceSearchState extends State<_PlaceSearch> {
|
||
List<(Place, String)> found = [];
|
||
String? note;
|
||
int _seq = 0;
|
||
|
||
Future<void> _search(String q) async {
|
||
final mine = ++_seq;
|
||
if (q.trim().length < 2) return setState(() => found = []);
|
||
try {
|
||
final r = await http
|
||
.get(Uri.parse('$_geocode?name=${Uri.encodeQueryComponent(q.trim())}&count=8&language=en&format=json'))
|
||
.timeout(const Duration(seconds: 15));
|
||
if (mine != _seq) return;
|
||
final res = ((jsonDecode(r.body) as Map)['results'] as List?) ?? const [];
|
||
setState(() {
|
||
note = res.isEmpty ? 'Nothing found' : null;
|
||
found = [
|
||
for (final x in res.cast<Map<String, dynamic>>())
|
||
(
|
||
Place('${x['name']}, ${x['country_code'] ?? ''}', (x['latitude'] as num).toDouble(), (x['longitude'] as num).toDouble()),
|
||
[x['admin1'], x['country']].whereType<String>().join(', '),
|
||
),
|
||
];
|
||
});
|
||
} catch (e) {
|
||
if (mine == _seq) setState(() => note = 'No connection');
|
||
}
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) => Padding(
|
||
padding: EdgeInsets.fromLTRB(16, 16, 16, 12 + MediaQuery.of(context).viewInsets.bottom),
|
||
child: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
TextField(
|
||
autofocus: true,
|
||
onChanged: _search,
|
||
decoration: const InputDecoration(labelText: 'Place', hintText: 'a town or city', prefixIcon: Icon(Icons.search)),
|
||
),
|
||
if (note != null)
|
||
Padding(
|
||
padding: const EdgeInsets.all(12),
|
||
child: Text(note!, style: const TextStyle(color: muted)),
|
||
),
|
||
ConstrainedBox(
|
||
constraints: const BoxConstraints(maxHeight: 360),
|
||
child: ListView(
|
||
shrinkWrap: true,
|
||
children: [
|
||
for (final (p, where) in found)
|
||
ListTile(
|
||
title: Text(p.name.split(',').first),
|
||
subtitle: Text(where, style: const TextStyle(color: muted)),
|
||
onTap: () => Navigator.pop(context, p),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|