feat(block2): 'use my location' — set the sharing area without typing a code

Makes the coarse area human, per feedback that a typed code is jargon.
- CoarseLocationProvider interface + geolocator-backed impl (BSD-3): low
  accuracy only, returns null on any denial/error (degrades quietly). Behind an
  interface so it's fakeable and the plugin stays at the composition root.
- Config sheet: a 'Use my approximate location' button (shown only when a
  provider is wired) fills the area from the device position, reduced to a
  5-char geohash via commons_core's Geohash — a precise fix never leaves the
  device. 'Couldn't get your location' on failure.
- Threaded via TaneApp(location); main wires GeolocatorCoarseLocation.
- Platform: ACCESS_COARSE_LOCATION (Android) + NSLocationWhenInUseUsageDescription
  (iOS), both scoped to the coarse-area use.
- i18n en/es/pt. Widget test fills the area from a fake location. 8 tests green.
This commit is contained in:
vjrj 2026-07-10 10:25:44 +02:00
parent f8f73c4153
commit 492bc62025
15 changed files with 176 additions and 10 deletions

View file

@ -1,4 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Coarse location only, for the optional "use my location" sharing area
(reduced to a low-precision geohash; never a precise fix). -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application <application
android:label="tane" android:label="tane"
android:name="${applicationName}" android:name="${applicationName}"

View file

@ -68,5 +68,7 @@
</array> </array>
<key>UIStatusBarHidden</key> <key>UIStatusBarHidden</key>
<false/> <false/>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Used only to set your approximate sharing area — reduced to a coarse zone, never your exact location.</string>
</dict> </dict>
</plist> </plist>

View file

@ -7,6 +7,7 @@ import 'package:go_router/go_router.dart';
import 'data/species_repository.dart'; import 'data/species_repository.dart';
import 'data/variety_repository.dart'; import 'data/variety_repository.dart';
import 'i18n/strings.g.dart'; import 'i18n/strings.g.dart';
import 'services/coarse_location.dart';
import 'services/onboarding_store.dart'; import 'services/onboarding_store.dart';
import 'services/social_service.dart'; import 'services/social_service.dart';
import 'services/social_settings.dart'; import 'services/social_settings.dart';
@ -31,6 +32,7 @@ class TaneApp extends StatelessWidget {
required this.onboarding, required this.onboarding,
this.social, this.social,
this.socialSettings, this.socialSettings,
this.location,
this.showIntro = false, this.showIntro = false,
super.key, super.key,
}) : _router = _buildRouter( }) : _router = _buildRouter(
@ -39,6 +41,7 @@ class TaneApp extends StatelessWidget {
showIntro, showIntro,
social, social,
socialSettings, socialSettings,
location,
); );
final VarietyRepository repository; final VarietyRepository repository;
@ -49,6 +52,9 @@ class TaneApp extends StatelessWidget {
/// null the market stays a "coming soon" card and `/market` is not routed. /// null the market stays a "coming soon" card and `/market` is not routed.
final SocialService? social; final SocialService? social;
final SocialSettings? socialSettings; final SocialSettings? socialSettings;
/// Optional device-location source for the market's "use my location".
final CoarseLocationProvider? location;
final bool showIntro; final bool showIntro;
final GoRouter _router; final GoRouter _router;
@ -58,6 +64,7 @@ class TaneApp extends StatelessWidget {
bool showIntro, bool showIntro,
SocialService? social, SocialService? social,
SocialSettings? socialSettings, SocialSettings? socialSettings,
CoarseLocationProvider? location,
) { ) {
return GoRouter( return GoRouter(
initialLocation: showIntro ? '/intro' : '/', initialLocation: showIntro ? '/intro' : '/',
@ -70,8 +77,11 @@ class TaneApp extends StatelessWidget {
if (social != null && socialSettings != null) if (social != null && socialSettings != null)
GoRoute( GoRoute(
path: '/market', path: '/market',
builder: (context, state) => builder: (context, state) => MarketScreen(
MarketScreen(social: social, settings: socialSettings), social: social,
settings: socialSettings,
location: location,
),
), ),
GoRoute( GoRoute(
path: '/intro', path: '/intro',

View file

@ -351,6 +351,8 @@
"wanted": "Wanted", "wanted": "Wanted",
"shareMine": "Share my seeds", "shareMine": "Share my seeds",
"sharedCount": "Shared {n} seeds nearby", "sharedCount": "Shared {n} seeds nearby",
"nothingToShare": "Mark some seeds to give, swap or sell first" "nothingToShare": "Mark some seeds to give, swap or sell first",
"useLocation": "Use my approximate location",
"locationFailed": "Couldn't get your location"
} }
} }

View file

@ -351,6 +351,8 @@
"wanted": "Busco", "wanted": "Busco",
"shareMine": "Compartir mis semillas", "shareMine": "Compartir mis semillas",
"sharedCount": "Compartidas {n} semillas", "sharedCount": "Compartidas {n} semillas",
"nothingToShare": "Marca antes algunas semillas para regalar, cambiar o vender" "nothingToShare": "Marca antes algunas semillas para regalar, cambiar o vender",
"useLocation": "Usar mi ubicación aproximada",
"locationFailed": "No se pudo obtener tu ubicación"
} }
} }

View file

@ -347,6 +347,8 @@
"wanted": "Procuro", "wanted": "Procuro",
"shareMine": "Partilhar as minhas sementes", "shareMine": "Partilhar as minhas sementes",
"sharedCount": "Partilhadas {n} sementes", "sharedCount": "Partilhadas {n} sementes",
"nothingToShare": "Marca primeiro algumas sementes para dar, trocar ou vender" "nothingToShare": "Marca primeiro algumas sementes para dar, trocar ou vender",
"useLocation": "Usar a minha localização aproximada",
"locationFailed": "Não foi possível obter a tua localização"
} }
} }

View file

@ -4,9 +4,9 @@
/// To regenerate, run: `dart run slang` /// To regenerate, run: `dart run slang`
/// ///
/// Locales: 3 /// Locales: 3
/// Strings: 938 (312 per locale) /// Strings: 944 (314 per locale)
/// ///
/// Built on 2026-07-10 at 08:17 UTC /// Built on 2026-07-10 at 08:25 UTC
// coverage:ignore-file // coverage:ignore-file
// ignore_for_file: type=lint, unused_import // ignore_for_file: type=lint, unused_import

View file

@ -1114,6 +1114,12 @@ class Translations$market$en {
/// en: 'Mark some seeds to give, swap or sell first' /// en: 'Mark some seeds to give, swap or sell first'
String get nothingToShare => 'Mark some seeds to give, swap or sell first'; String get nothingToShare => 'Mark some seeds to give, swap or sell first';
/// en: 'Use my approximate location'
String get useLocation => 'Use my approximate location';
/// en: 'Couldn't get your location'
String get locationFailed => 'Couldn\'t get your location';
} }
// Path: intro.slides // Path: intro.slides
@ -1887,6 +1893,8 @@ extension on Translations {
'market.shareMine' => 'Share my seeds', 'market.shareMine' => 'Share my seeds',
'market.sharedCount' => ({required Object n}) => 'Shared ${n} seeds nearby', 'market.sharedCount' => ({required Object n}) => 'Shared ${n} seeds nearby',
'market.nothingToShare' => 'Mark some seeds to give, swap or sell first', 'market.nothingToShare' => 'Mark some seeds to give, swap or sell first',
'market.useLocation' => 'Use my approximate location',
'market.locationFailed' => 'Couldn\'t get your location',
_ => null, _ => null,
}; };
} }

View file

@ -622,6 +622,8 @@ class _Translations$market$es extends Translations$market$en {
@override String get shareMine => 'Compartir mis semillas'; @override String get shareMine => 'Compartir mis semillas';
@override String sharedCount({required Object n}) => 'Compartidas ${n} semillas'; @override String sharedCount({required Object n}) => 'Compartidas ${n} semillas';
@override String get nothingToShare => 'Marca antes algunas semillas para regalar, cambiar o vender'; @override String get nothingToShare => 'Marca antes algunas semillas para regalar, cambiar o vender';
@override String get useLocation => 'Usar mi ubicación aproximada';
@override String get locationFailed => 'No se pudo obtener tu ubicación';
} }
// Path: intro.slides // Path: intro.slides
@ -1279,6 +1281,8 @@ extension on TranslationsEs {
'market.shareMine' => 'Compartir mis semillas', 'market.shareMine' => 'Compartir mis semillas',
'market.sharedCount' => ({required Object n}) => 'Compartidas ${n} semillas', 'market.sharedCount' => ({required Object n}) => 'Compartidas ${n} semillas',
'market.nothingToShare' => 'Marca antes algunas semillas para regalar, cambiar o vender', 'market.nothingToShare' => 'Marca antes algunas semillas para regalar, cambiar o vender',
'market.useLocation' => 'Usar mi ubicación aproximada',
'market.locationFailed' => 'No se pudo obtener tu ubicación',
_ => null, _ => null,
}; };
} }

View file

@ -618,6 +618,8 @@ class _Translations$market$pt extends Translations$market$en {
@override String get shareMine => 'Partilhar as minhas sementes'; @override String get shareMine => 'Partilhar as minhas sementes';
@override String sharedCount({required Object n}) => 'Partilhadas ${n} sementes'; @override String sharedCount({required Object n}) => 'Partilhadas ${n} sementes';
@override String get nothingToShare => 'Marca primeiro algumas sementes para dar, trocar ou vender'; @override String get nothingToShare => 'Marca primeiro algumas sementes para dar, trocar ou vender';
@override String get useLocation => 'Usar a minha localização aproximada';
@override String get locationFailed => 'Não foi possível obter a tua localização';
} }
// Path: intro.slides // Path: intro.slides
@ -1271,6 +1273,8 @@ extension on TranslationsPt {
'market.shareMine' => 'Partilhar as minhas sementes', 'market.shareMine' => 'Partilhar as minhas sementes',
'market.sharedCount' => ({required Object n}) => 'Partilhadas ${n} sementes', 'market.sharedCount' => ({required Object n}) => 'Partilhadas ${n} sementes',
'market.nothingToShare' => 'Marca primeiro algumas sementes para dar, trocar ou vender', 'market.nothingToShare' => 'Marca primeiro algumas sementes para dar, trocar ou vender',
'market.useLocation' => 'Usar a minha localização aproximada',
'market.locationFailed' => 'Não foi possível obter a tua localização',
_ => null, _ => null,
}; };
} }

View file

@ -5,6 +5,7 @@ import 'data/species_repository.dart';
import 'data/variety_repository.dart'; import 'data/variety_repository.dart';
import 'di/injector.dart'; import 'di/injector.dart';
import 'i18n/strings.g.dart'; import 'i18n/strings.g.dart';
import 'services/coarse_location.dart';
import 'services/onboarding_store.dart'; import 'services/onboarding_store.dart';
import 'services/social_service.dart'; import 'services/social_service.dart';
import 'services/social_settings.dart'; import 'services/social_settings.dart';
@ -22,6 +23,7 @@ Future<void> main() async {
onboarding: onboarding, onboarding: onboarding,
social: getIt<SocialService>(), social: getIt<SocialService>(),
socialSettings: getIt<SocialSettings>(), socialSettings: getIt<SocialSettings>(),
location: const GeolocatorCoarseLocation(),
showIntro: !await onboarding.introSeen(), showIntro: !await onboarding.introSeen(),
), ),
), ),

View file

@ -0,0 +1,38 @@
import 'package:geolocator/geolocator.dart';
/// Supplies the device's *approximate* location (or null when unavailable or
/// denied). Behind an interface so the UI is fakeable in tests and the concrete
/// platform plugin stays at the composition root. The caller immediately reduces
/// the result to a low-precision geohash a precise fix never leaves the device.
abstract interface class CoarseLocationProvider {
Future<({double lat, double lon})?> currentCoarseLatLon();
}
/// [geolocator]-backed implementation. Requests low accuracy only, and returns
/// null on any denial/error rather than throwing, so the UI can degrade quietly.
class GeolocatorCoarseLocation implements CoarseLocationProvider {
const GeolocatorCoarseLocation();
@override
Future<({double lat, double lon})?> currentCoarseLatLon() async {
try {
if (!await Geolocator.isLocationServiceEnabled()) return null;
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
return null;
}
final position = await Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(
accuracy: LocationAccuracy.low,
),
);
return (lat: position.latitude, lon: position.longitude);
} catch (_) {
return null; // service off, plugin unsupported (desktop), timeout,
}
}
}

View file

@ -4,6 +4,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import '../data/variety_repository.dart'; import '../data/variety_repository.dart';
import '../i18n/strings.g.dart'; import '../i18n/strings.g.dart';
import '../services/coarse_location.dart';
import '../services/social_service.dart'; import '../services/social_service.dart';
import '../services/social_settings.dart'; import '../services/social_settings.dart';
import '../state/offers_cubit.dart'; import '../state/offers_cubit.dart';
@ -13,11 +14,20 @@ import 'theme.dart';
/// an offer transport lazily; local-first, so it degrades to a "set up sharing" /// an offer transport lazily; local-first, so it degrades to a "set up sharing"
/// prompt when no relay/area is configured or the network is unreachable. /// prompt when no relay/area is configured or the network is unreachable.
class MarketScreen extends StatefulWidget { class MarketScreen extends StatefulWidget {
const MarketScreen({required this.social, required this.settings, super.key}); const MarketScreen({
required this.social,
required this.settings,
this.location,
super.key,
});
final SocialService social; final SocialService social;
final SocialSettings settings; final SocialSettings settings;
/// Optional device-location source for the "use my location" shortcut; when
/// null (tests, or a platform without it) the shortcut is hidden.
final CoarseLocationProvider? location;
@override @override
State<MarketScreen> createState() => _MarketScreenState(); State<MarketScreen> createState() => _MarketScreenState();
} }
@ -53,7 +63,8 @@ class _MarketScreenState extends State<MarketScreen> {
final changed = await showModalBottomSheet<bool>( final changed = await showModalBottomSheet<bool>(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
builder: (_) => _ConfigSheet(settings: widget.settings), builder: (_) =>
_ConfigSheet(settings: widget.settings, location: widget.location),
); );
if (changed == true) await _init(); if (changed == true) await _init();
} }
@ -325,9 +336,10 @@ class _EmptyState extends StatelessWidget {
/// Coarse-area + community-server setup. Kept behind progressive disclosure a /// Coarse-area + community-server setup. Kept behind progressive disclosure a
/// power-user surface with human-worded labels. /// power-user surface with human-worded labels.
class _ConfigSheet extends StatefulWidget { class _ConfigSheet extends StatefulWidget {
const _ConfigSheet({required this.settings}); const _ConfigSheet({required this.settings, this.location});
final SocialSettings settings; final SocialSettings settings;
final CoarseLocationProvider? location;
@override @override
State<_ConfigSheet> createState() => _ConfigSheetState(); State<_ConfigSheet> createState() => _ConfigSheetState();
@ -356,6 +368,22 @@ class _ConfigSheetState extends State<_ConfigSheet> {
if (mounted) Navigator.of(context).pop(true); if (mounted) Navigator.of(context).pop(true);
} }
/// Fills the area from the device's approximate location, reduced to a coarse
/// geohash so no precise fix is stored.
Future<void> _useLocation() async {
final provider = widget.location;
if (provider == null) return;
final messenger = ScaffoldMessenger.of(context);
final t = context.t;
final loc = await provider.currentCoarseLatLon();
if (!mounted) return;
if (loc == null) {
messenger.showSnackBar(SnackBar(content: Text(t.market.locationFailed)));
return;
}
setState(() => _area.text = Geohash.encode(loc.lat, loc.lon, precision: 5));
}
@override @override
void dispose() { void dispose() {
_area.dispose(); _area.dispose();
@ -402,6 +430,16 @@ class _ConfigSheetState extends State<_ConfigSheet> {
helperMaxLines: 3, helperMaxLines: 3,
), ),
), ),
if (widget.location != null)
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton.icon(
key: const Key('market.useLocation'),
icon: const Icon(Icons.my_location, size: 18),
label: Text(t.market.useLocation),
onPressed: _useLocation,
),
),
const SizedBox(height: 8), const SizedBox(height: 8),
// The technical web address lives under progressive disclosure // The technical web address lives under progressive disclosure
// most people won't have one, and jargon shouldn't greet them. // most people won't have one, and jargon shouldn't greet them.

View file

@ -62,6 +62,10 @@ dependencies:
material_symbols_icons: ^4.2951.0 material_symbols_icons: ^4.2951.0
url_launcher: ^6.3.2 url_launcher: ^6.3.2
package_info_plus: ^9.0.1 package_info_plus: ^9.0.1
# Optional coarse device location (BSD-3) to set the sharing area without
# typing a code. Low accuracy only; the value is immediately reduced to a
# low-precision geohash. Behind an interface so it's fakeable and pluggable.
geolocator: ^13.0.1
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

View file

@ -6,6 +6,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:tane/i18n/strings.g.dart'; import 'package:tane/i18n/strings.g.dart';
import 'package:tane/services/coarse_location.dart';
import 'package:tane/services/social_service.dart'; import 'package:tane/services/social_service.dart';
import 'package:tane/services/social_settings.dart'; import 'package:tane/services/social_settings.dart';
import 'package:tane/state/offers_cubit.dart'; import 'package:tane/state/offers_cubit.dart';
@ -13,6 +14,16 @@ import 'package:tane/ui/market_screen.dart';
import '../support/test_support.dart'; import '../support/test_support.dart';
/// A location provider returning a fixed coarse position.
class FakeLocation implements CoarseLocationProvider {
FakeLocation(this.lat, this.lon);
final double lat;
final double lon;
@override
Future<({double lat, double lon})?> currentCoarseLatLon() async =>
(lat: lat, lon: lon);
}
/// In-memory offer transport: discover matches by geohash prefix. /// In-memory offer transport: discover matches by geohash prefix.
class FakeOfferTransport implements OfferTransport { class FakeOfferTransport implements OfferTransport {
final List<Offer> offers; final List<Offer> offers;
@ -120,4 +131,40 @@ void main() {
expect(find.text('Seeds near you'), findsOneWidget); // app bar title expect(find.text('Seeds near you'), findsOneWidget); // app bar title
expect(find.text('Set up sharing'), findsOneWidget); // offline prompt expect(find.text('Set up sharing'), findsOneWidget); // offline prompt
}); });
testWidgets('"use my location" fills the area with a coarse geohash',
(tester) async {
final social = await SocialService.fromRootSeedHex('00' * 32);
final settings = SocialSettings(InMemorySecretStore());
LocaleSettings.setLocaleSync(AppLocale.en);
await tester.pumpWidget(
TranslationProvider(
child: MaterialApp(
locale: AppLocale.en.flutterLocale,
supportedLocales: AppLocaleUtils.supportedLocales,
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: MarketScreen(
social: social,
settings: settings,
location: FakeLocation(41.39, 2.16), // Barcelona-ish
),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('market.config')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('market.useLocation')));
await tester.pumpAndSettle();
final area = tester.widget<TextField>(find.byKey(const Key('market.area')));
expect(area.controller!.text, hasLength(5));
expect(area.controller!.text, matches(RegExp(r'^[0-9a-z]+$')));
});
} }