Add saved places and optional device location

A saved place is a named point the user keeps: it frames the map now, and once
the worker publishes station data it is what the nearest-station readings and,
later, the rain notifications will hang off. Free points rather than stations,
because people think in terms of home and work, not in terms of which weather
station happens to represent them.

Everything stays on the device. Places live in SharedPreferences under a
versioned key, and there is no account to attach them to and no server that
would accept them. That is what keeps the Data safety declaration able to say
no location is collected, and it must survive the notification work: the device
will subscribe to the topic for the cell containing a place, so the link
between a person and a place never leaves their phone.

Location is coarse only, and that took enforcing. geolocator declares
ACCESS_FINE_LOCATION in its own manifest and the merger pulls it in, so the
system dialog offered "Precise" despite the app asking for nothing of the sort;
the manifest now removes it with tools:node="remove", and the dialog reads
"approximate location" with no choice offered. Requests also go through the
platform LocationManager rather than the Play Services fused provider, which
prompts about Location Accuracy and, when declined, returns no fix at all —
an absurd outcome for an app that only ever wanted an approximate one, and one
that also tied location to Play Services being present.

The prominent disclosure comes before the system dialog, as Play requires, and
is repeated in Settings so someone who already answered can still read what the
permission is for. Declining leaves the app fully usable.

Two more defects found by running it and by a test:

- MapLibreMap leaves cameraPosition null unless trackCameraPosition is set, so
  "save the map centre" silently saved the region default rather than what the
  user was looking at.
- Place ids came straight from the microsecond clock, so two places saved in
  the same microsecond shared an id and rename, remove and the duplicate-name
  check all acted on the wrong one. A test caught it on a fast machine.

Saving refuses points outside the region rather than accepting them: a place in
Rome would look like it worked and then show nothing forever.

Also corrects CLAUDE.md, which still said ARPA states no licence, and records
the ARPA realtime API there with the property that governs how it may be used —
it lags about 4.5 hours, so it is an observation archive and must never sit
next to 5-minute radar looking current.

Verified: analyze clean, 158 tests passing, and on the emulator the disclosure
precedes the system dialog, the dialog asks only for approximate location, a
place survives restart and reinstall, and tapping one moves the map onto it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-10 19:39:03 +02:00
co-authored by Claude Opus 5
parent e14308bbb6
commit 06ab816ebe
20 changed files with 2174 additions and 26 deletions
@@ -0,0 +1,119 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:geolocator/geolocator.dart';
import '../../core/region/geo.dart';
import '../../l10n/app_localizations.dart';
import 'location_service.dart';
/// Obtains a position, explaining why before asking.
///
/// Google Play requires a prominent disclosure **before** the system permission
/// dialog: the user has to be told what is collected and why while they can
/// still decline without a dialog in their face. That ordering is the whole
/// reason this lives in one function instead of being scattered across the
/// screens that need a fix.
///
/// Returns null whenever no position is available, having already told the user
/// why. Callers fall back to the region centre rather than blocking.
Future<GeoPoint?> requestPosition(BuildContext context, WidgetRef ref) async {
final l10n = AppLocalizations.of(context);
final service = ref.read(locationServiceProvider);
var availability = await service.availability();
if (!context.mounted) return null;
if (availability == LocationAvailability.serviceDisabled) {
_explain(
context,
l10n.locationStatusServiceDisabled,
actionLabel: l10n.locationOpenSystemSettings,
onAction: Geolocator.openLocationSettings,
);
return null;
}
if (availability == LocationAvailability.deniedForever) {
_explain(
context,
l10n.locationStatusDeniedForever,
actionLabel: l10n.locationOpenSystemSettings,
onAction: Geolocator.openAppSettings,
);
return null;
}
if (availability == LocationAvailability.denied) {
final shown = ref.read(locationDisclosureShownProvider);
if (!shown) {
final accepted = await showLocationDisclosure(context);
if (!context.mounted) return null;
if (!accepted) return null;
ref.read(locationDisclosureShownProvider.notifier).markShown();
}
availability = await service.request();
if (!context.mounted) return null;
if (availability != LocationAvailability.granted) {
_explain(
context,
availability == LocationAvailability.deniedForever
? l10n.locationStatusDeniedForever
: l10n.locationStatusDenied,
);
return null;
}
}
final point = await service.currentPoint();
if (!context.mounted) return null;
if (point == null) {
_explain(context, l10n.locationUnavailable);
return null;
}
return point;
}
/// Shows the prominent disclosure. Returns true if the user chose to continue.
Future<bool> showLocationDisclosure(BuildContext context) async {
final l10n = AppLocalizations.of(context);
final accepted = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
icon: const Icon(Icons.my_location),
title: Text(l10n.locationDisclosureTitle),
content: SingleChildScrollView(child: Text(l10n.locationDisclosureBody)),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: Text(l10n.locationDisclosureDecline),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: Text(l10n.locationDisclosureContinue),
),
],
),
);
return accepted ?? false;
}
void _explain(
BuildContext context,
String message, {
String? actionLabel,
VoidCallback? onAction,
}) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 6),
action: actionLabel == null || onAction == null
? null
: SnackBarAction(label: actionLabel, onPressed: onAction),
),
);
}
@@ -0,0 +1,142 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:geolocator/geolocator.dart';
import '../../core/region/geo.dart';
/// What stands between the app and a position fix.
enum LocationAvailability {
/// Ready to locate.
granted,
/// Location is switched off on the device. The user has to enable it in
/// system settings; asking for permission would not help.
serviceDisabled,
/// Not granted yet, but askable.
denied,
/// Refused permanently. Only system settings can undo it, so the UI must send
/// the user there rather than asking again into the void.
deniedForever,
}
/// Reads the device position.
///
/// Behind an interface so the permission dance can be tested without a device
/// and without the plugin's static methods.
abstract interface class LocationService {
Future<LocationAvailability> availability();
/// Asks for permission if it has not been granted yet.
Future<LocationAvailability> request();
/// A single coarse fix, or null if it could not be obtained.
Future<GeoPoint?> currentPoint();
}
class GeolocatorLocationService implements LocationService {
const GeolocatorLocationService();
/// Deliberately coarse.
///
/// This app centres a map and picks the nearest weather station, and stations
/// are kilometres apart. Street-level precision would buy nothing and would
/// mean asking for a more invasive permission, so the app declares only
/// `ACCESS_COARSE_LOCATION` and asks for low accuracy to match.
///
/// `forceLocationManager` uses the platform's own LocationManager instead of
/// the Google Play Services fused provider. The fused provider triggers a
/// "your device will need to use Location Accuracy" prompt, and declining it
/// yields **no fix at all** — an absurd outcome for an app that only wants an
/// approximate one. It also drops the Play Services dependency, so location
/// works on devices that do not have them.
static LocationSettings get _settings {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidSettings(
accuracy: LocationAccuracy.low,
forceLocationManager: true,
timeLimit: const Duration(seconds: 20),
);
}
return const LocationSettings(
accuracy: LocationAccuracy.low,
timeLimit: Duration(seconds: 20),
);
}
@override
Future<LocationAvailability> availability() async {
if (!await Geolocator.isLocationServiceEnabled()) {
return LocationAvailability.serviceDisabled;
}
return _map(await Geolocator.checkPermission());
}
@override
Future<LocationAvailability> request() async {
if (!await Geolocator.isLocationServiceEnabled()) {
return LocationAvailability.serviceDisabled;
}
final current = await Geolocator.checkPermission();
if (current == LocationPermission.denied) {
return _map(await Geolocator.requestPermission());
}
return _map(current);
}
@override
Future<GeoPoint?> currentPoint() async {
if (await availability() != LocationAvailability.granted) return null;
try {
final position = await Geolocator.getCurrentPosition(
locationSettings: _settings,
);
return GeoPoint(position.longitude, position.latitude);
} on Object {
// A fresh fix can take seconds indoors, or time out entirely. For
// centring a map a slightly stale position is worth far more than
// nothing, so fall back to whatever the system already knows.
try {
final last = await Geolocator.getLastKnownPosition();
if (last == null) return null;
return GeoPoint(last.longitude, last.latitude);
} on Object {
return null;
}
}
}
static LocationAvailability _map(LocationPermission permission) =>
switch (permission) {
LocationPermission.always ||
LocationPermission.whileInUse => LocationAvailability.granted,
LocationPermission.deniedForever => LocationAvailability.deniedForever,
LocationPermission.denied ||
LocationPermission.unableToDetermine => LocationAvailability.denied,
};
}
final locationServiceProvider = Provider<LocationService>(
(ref) => const GeolocatorLocationService(),
);
/// Whether the user has seen the prominent disclosure in this session.
///
/// Google Play requires the explanation to come **before** the system dialog.
/// Session-scoped rather than persisted: showing it again after an app restart
/// costs one tap, and a user who forgot what they agreed to deserves to be
/// reminded.
class LocationDisclosureShown extends Notifier<bool> {
@override
bool build() => false;
void markShown() => state = true;
}
final locationDisclosureShownProvider =
NotifierProvider<LocationDisclosureShown, bool>(
LocationDisclosureShown.new,
);
@@ -0,0 +1,70 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'saved_place.dart';
/// Stores saved places on the device.
///
/// Local storage, and only local storage. A saved place is the closest thing
/// this app has to a home address; it never reaches a server, which is what
/// lets the Data safety declaration say that no location is collected. See
/// docs/privacy.md.
abstract interface class PlacesStore {
Future<List<SavedPlace>> load();
Future<void> save(List<SavedPlace> places);
}
class SharedPreferencesPlacesStore implements PlacesStore {
const SharedPreferencesPlacesStore();
static const String storageKey = 'nuvolari.saved_places.v1';
@override
Future<List<SavedPlace>> load() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(storageKey);
if (raw == null || raw.isEmpty) return const <SavedPlace>[];
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return const <SavedPlace>[];
return decoded
.whereType<Map<String, Object?>>()
.map(SavedPlace.fromJson)
.toList(growable: false);
} on Object {
// Corrupt storage loses the places, which is bad, but throwing here would
// make the app unopenable, which is worse. Starting empty is recoverable
// by the user; a crash loop is not.
return const <SavedPlace>[];
}
}
@override
Future<void> save(List<SavedPlace> places) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(
storageKey,
jsonEncode(places.map((place) => place.toJson()).toList(growable: false)),
);
}
}
/// An in-memory store, for tests and for previewing without touching the device.
class InMemoryPlacesStore implements PlacesStore {
InMemoryPlacesStore([List<SavedPlace>? initial])
: _places = List<SavedPlace>.of(initial ?? const <SavedPlace>[]);
List<SavedPlace> _places;
@override
Future<List<SavedPlace>> load() async =>
List<SavedPlace>.unmodifiable(_places);
@override
Future<void> save(List<SavedPlace> places) async {
_places = List<SavedPlace>.of(places);
}
}
@@ -0,0 +1,279 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/region/geo.dart';
import '../../l10n/app_localizations.dart';
import 'location_flow.dart';
import 'saved_place.dart';
import 'saved_places.dart';
/// The saved places list.
///
/// Returns the chosen [SavedPlace] to the caller when one is tapped, so the map
/// can centre on it without this screen knowing anything about the map.
class PlacesScreen extends ConsumerWidget {
const PlacesScreen({required this.mapCentre, super.key});
/// Where the map is looking right now, offered as a one-tap thing to save.
final GeoPoint mapCentre;
@override
Widget build(BuildContext context, WidgetRef ref) {
final l10n = AppLocalizations.of(context);
final places = ref.watch(savedPlacesProvider);
return Scaffold(
appBar: AppBar(title: Text(l10n.placesTitle)),
body: switch (places) {
AsyncData(:final value) => _PlacesList(
places: value,
mapCentre: mapCentre,
),
AsyncError(:final error) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text('${l10n.dataUnavailable}\n$error'),
),
),
_ => Center(child: Text(l10n.loading)),
},
);
}
}
class _PlacesList extends ConsumerWidget {
const _PlacesList({required this.places, required this.mapCentre});
final List<SavedPlace> places;
final GeoPoint mapCentre;
@override
Widget build(BuildContext context, WidgetRef ref) {
final l10n = AppLocalizations.of(context);
final theme = Theme.of(context);
final isFull = places.length >= SavedPlaces.maxPlaces;
return Column(
children: [
Expanded(
child: places.isEmpty
? _EmptyState()
: ListView.separated(
itemCount: places.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) =>
_PlaceTile(place: places[index]),
),
),
if (isFull)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
l10n.placesFull(SavedPlaces.maxPlaces),
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.error,
),
),
),
SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(
children: [
FilledButton.icon(
onPressed: isFull
? null
: () => _addFromDevicePosition(context, ref),
icon: const Icon(Icons.my_location),
label: Text(l10n.placeAddCurrent),
),
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: isFull
? null
: () => _promptAndAdd(context, ref, mapCentre),
icon: const Icon(Icons.center_focus_strong),
label: Text(l10n.placeAddMapCentre),
),
],
),
),
),
],
);
}
Future<void> _addFromDevicePosition(
BuildContext context,
WidgetRef ref,
) async {
final point = await requestPosition(context, ref);
if (point == null || !context.mounted) return;
await _promptAndAdd(context, ref, point);
}
}
class _EmptyState extends StatelessWidget {
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final theme = Theme.of(context);
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.place_outlined,
size: 48,
color: theme.colorScheme.outline,
),
const SizedBox(height: 16),
Text(l10n.placesEmpty, style: theme.textTheme.titleMedium),
const SizedBox(height: 8),
Text(
l10n.placesEmptyHint,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.outline,
),
),
],
),
),
);
}
}
class _PlaceTile extends ConsumerWidget {
const _PlaceTile({required this.place});
final SavedPlace place;
@override
Widget build(BuildContext context, WidgetRef ref) {
final l10n = AppLocalizations.of(context);
return ListTile(
leading: const Icon(Icons.place),
title: Text(place.name),
subtitle: Text(formatPoint(place.point)),
onTap: () => Navigator.of(context).pop(place),
trailing: PopupMenuButton<String>(
onSelected: (value) async {
if (value == 'rename') {
await _rename(context, ref, place);
} else if (value == 'delete') {
await _delete(context, ref, place);
}
},
itemBuilder: (context) => [
PopupMenuItem<String>(value: 'rename', child: Text(l10n.placeRename)),
PopupMenuItem<String>(value: 'delete', child: Text(l10n.placeDelete)),
],
),
);
}
}
/// Coordinates at a precision that matches how they were obtained.
///
/// Four decimals is about 10 m, which is finer than the coarse fix the app asks
/// for and finer than anyone needs to read. More digits would imply an accuracy
/// the app does not have.
String formatPoint(GeoPoint point) =>
'${point.latitude.toStringAsFixed(4)}, ${point.longitude.toStringAsFixed(4)}';
Future<void> _promptAndAdd(
BuildContext context,
WidgetRef ref,
GeoPoint point,
) async {
final name = await _askForName(context);
if (name == null || !context.mounted) return;
try {
await ref.read(savedPlacesProvider.notifier).add(name: name, point: point);
} on SavedPlaceException catch (error) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(messageFor(AppLocalizations.of(context), error))),
);
}
}
Future<void> _rename(
BuildContext context,
WidgetRef ref,
SavedPlace place,
) async {
final name = await _askForName(context, initial: place.name);
if (name == null || !context.mounted) return;
try {
await ref.read(savedPlacesProvider.notifier).rename(place.id, name);
} on SavedPlaceException catch (error) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(messageFor(AppLocalizations.of(context), error))),
);
}
}
Future<void> _delete(
BuildContext context,
WidgetRef ref,
SavedPlace place,
) async {
final l10n = AppLocalizations.of(context);
await ref.read(savedPlacesProvider.notifier).remove(place.id);
if (!context.mounted) return;
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(l10n.placeDeleted(place.name))));
}
Future<String?> _askForName(BuildContext context, {String? initial}) {
final l10n = AppLocalizations.of(context);
final controller = TextEditingController(text: initial);
return showDialog<String>(
context: context,
builder: (context) => AlertDialog(
title: Text(initial == null ? l10n.placeAddMapCentre : l10n.placeRename),
content: TextField(
controller: controller,
autofocus: true,
maxLength: SavedPlace.maxNameLength,
decoration: InputDecoration(
labelText: l10n.placeNameLabel,
hintText: l10n.placeNameHint,
),
onSubmitted: (value) => Navigator.of(context).pop(value),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.of(context).pop(controller.text),
child: Text(l10n.save),
),
],
),
);
}
/// Turns a rejection into the sentence that explains it.
String messageFor(AppLocalizations l10n, SavedPlaceException error) =>
switch (error.rejection) {
SavedPlaceRejection.emptyName => l10n.placeErrorEmptyName,
SavedPlaceRejection.nameTooLong => l10n.placeErrorNameTooLong(
SavedPlace.maxNameLength,
),
SavedPlaceRejection.duplicateName => l10n.placeErrorDuplicateName,
SavedPlaceRejection.outsideRegion => l10n.placeErrorOutsideRegion,
};
@@ -0,0 +1,120 @@
import '../../core/region/geo.dart';
/// A place the user has named and kept.
///
/// The anchor everything location-shaped hangs off: which part of the region the
/// radar map opens on, and — once the worker publishes them — which alert zone
/// and which rain cell the notifications for this place should follow.
///
/// A free point rather than a station: people think in terms of home and work,
/// not in terms of which weather station happens to represent them. The nearest
/// station is derived from the point when readings are shown, so the user can
/// always see how far away the measurement actually came from.
class SavedPlace {
const SavedPlace({
required this.id,
required this.name,
required this.point,
required this.createdAt,
});
factory SavedPlace.fromJson(Map<String, Object?> json) {
final id = json['id'];
final name = json['name'];
final longitude = json['lng'];
final latitude = json['lat'];
final createdAt = json['createdAt'];
if (id is! String || id.isEmpty) {
throw const FormatException('saved place id must be a non-empty string');
}
if (name is! String || name.isEmpty) {
throw const FormatException(
'saved place name must be a non-empty string',
);
}
if (longitude is! num || latitude is! num) {
throw const FormatException('saved place coordinates must be numbers');
}
if (createdAt is! int) {
throw const FormatException(
'saved place createdAt must be an epoch in ms',
);
}
return SavedPlace(
id: id,
name: name,
point: GeoPoint(longitude.toDouble(), latitude.toDouble()),
createdAt: DateTime.fromMillisecondsSinceEpoch(createdAt, isUtc: true),
);
}
/// Longest name the UI will accept.
///
/// Not a storage limit — it keeps a name readable in the one-line list and in
/// a notification title, where a long string would simply be truncated
/// somewhere unhelpful.
static const int maxNameLength = 40;
final String id;
final String name;
final GeoPoint point;
final DateTime createdAt;
Map<String, Object?> toJson() => <String, Object?>{
'id': id,
'name': name,
'lng': point.longitude,
'lat': point.latitude,
'createdAt': createdAt.millisecondsSinceEpoch,
};
SavedPlace copyWith({String? name, GeoPoint? point}) => SavedPlace(
id: id,
name: name ?? this.name,
point: point ?? this.point,
createdAt: createdAt,
);
@override
String toString() => 'SavedPlace($id, $name, $point)';
@override
bool operator ==(Object other) =>
other is SavedPlace &&
other.id == id &&
other.name == name &&
other.point == point &&
other.createdAt == createdAt;
@override
int get hashCode => Object.hash(id, name, point, createdAt);
}
/// Why a place could not be saved.
///
/// Modelled rather than returned as a bare bool so the UI can say which rule was
/// broken instead of a generic failure.
enum SavedPlaceRejection {
/// The name was empty or only whitespace.
emptyName,
/// The name exceeded [SavedPlace.maxNameLength].
nameTooLong,
/// The point lies outside the region the app has data for.
outsideRegion,
/// Another saved place already uses that name.
duplicateName,
}
class SavedPlaceException implements Exception {
const SavedPlaceException(this.rejection);
final SavedPlaceRejection rejection;
@override
String toString() => 'SavedPlaceException(${rejection.name})';
}
@@ -0,0 +1,158 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/region/geo.dart';
import '../../core/region/region_config.dart';
import '../../core/region/region_repository.dart';
import 'places_repository.dart';
import 'saved_place.dart';
final placesStoreProvider = Provider<PlacesStore>(
(ref) => const SharedPreferencesPlacesStore(),
);
/// The user's saved places, newest first.
class SavedPlaces extends AsyncNotifier<List<SavedPlace>> {
/// Beyond this the list stops being a shortcut and becomes a directory to
/// search through, which is not what it is for.
static const int maxPlaces = 20;
@override
Future<List<SavedPlace>> build() => ref.watch(placesStoreProvider).load();
/// Adds a place at [point] called [name].
///
/// Throws [SavedPlaceException] naming the rule that was broken, so the UI can
/// explain the refusal rather than swallowing it.
Future<SavedPlace> add({
required String name,
required GeoPoint point,
}) async {
final trimmed = name.trim();
_validateName(trimmed);
await _validatePoint(point);
final current = List<SavedPlace>.of(state.value ?? const []);
if (current.any((p) => p.name.toLowerCase() == trimmed.toLowerCase())) {
throw const SavedPlaceException(SavedPlaceRejection.duplicateName);
}
final place = SavedPlace(
id: _newId(current),
name: trimmed,
point: point,
createdAt: DateTime.now().toUtc(),
);
// Newest first: the place just added is the one most likely to be tapped.
final updated = <SavedPlace>[place, ...current];
if (updated.length > maxPlaces) {
updated.removeRange(maxPlaces, updated.length);
}
await _persist(updated);
return place;
}
Future<void> rename(String id, String name) async {
final trimmed = name.trim();
_validateName(trimmed);
final current = List<SavedPlace>.of(state.value ?? const []);
if (current.any(
(p) => p.id != id && p.name.toLowerCase() == trimmed.toLowerCase(),
)) {
throw const SavedPlaceException(SavedPlaceRejection.duplicateName);
}
await _persist(<SavedPlace>[
for (final place in current)
if (place.id == id) place.copyWith(name: trimmed) else place,
]);
}
Future<void> remove(String id) async {
final current = state.value ?? const <SavedPlace>[];
await _persist(
current
.where((SavedPlace place) => place.id != id)
.toList(growable: false),
);
}
Future<void> clear() => _persist(const <SavedPlace>[]);
Future<void> _persist(List<SavedPlace> places) async {
await ref.read(placesStoreProvider).save(places);
state = AsyncData<List<SavedPlace>>(List<SavedPlace>.unmodifiable(places));
}
/// An id no existing place is using.
///
/// The clock alone is not enough: two places saved in the same microsecond
/// get the same id, and everything that addresses a place by id — rename,
/// remove, the duplicate-name check — then acts on the wrong one or on both.
/// A test caught exactly that on a fast machine.
String _newId(List<SavedPlace> existing) {
final taken = existing.map((place) => place.id).toSet();
final base = 'p${DateTime.now().microsecondsSinceEpoch}';
if (!taken.contains(base)) return base;
var suffix = 1;
while (taken.contains('${base}_$suffix')) {
suffix++;
}
return '${base}_$suffix';
}
void _validateName(String name) {
if (name.isEmpty) {
throw const SavedPlaceException(SavedPlaceRejection.emptyName);
}
if (name.length > SavedPlace.maxNameLength) {
throw const SavedPlaceException(SavedPlaceRejection.nameTooLong);
}
}
/// Refuses points the app has no data for.
///
/// Saving a place in Rome would look like it worked and then show nothing
/// forever. Better to say so at the moment of saving, while the user still
/// knows what they were trying to do.
Future<void> _validatePoint(GeoPoint point) async {
final region = await ref.read(regionConfigProvider.future);
if (!region.bounds.contains(point)) {
throw const SavedPlaceException(SavedPlaceRejection.outsideRegion);
}
}
}
final savedPlacesProvider =
AsyncNotifierProvider<SavedPlaces, List<SavedPlace>>(SavedPlaces.new);
/// The place the map is currently centred on, or null for the region default.
///
/// Session state on purpose: which place you last looked at is not worth
/// persisting, and restoring it on launch would surprise someone who opened the
/// app to see the weather where they are now.
class ActivePlace extends Notifier<SavedPlace?> {
@override
SavedPlace? build() => null;
void select(SavedPlace? place) => state = place;
}
final activePlaceProvider = NotifierProvider<ActivePlace, SavedPlace?>(
ActivePlace.new,
);
/// Returns [places] ordered by distance from [point], nearest first.
List<SavedPlace> byDistanceFrom(GeoPoint point, List<SavedPlace> places) {
final sorted = List<SavedPlace>.of(places);
sorted.sort(
(a, b) => point.distanceTo(a.point).compareTo(point.distanceTo(b.point)),
);
return sorted;
}
/// Convenience for the region default when no place is active.
GeoPoint defaultCentreOf(RegionConfig region) => region.map.center;