Author SHA1 Message Date
ahp e93058ba7e map: make tile server configurable and allow disabling map tiles
Adds a map settings dialog (layers icon in the map app bar) that lets the
user set a custom tile URL template or turn off background tiles entirely.
With tiles off the map shows only the bundled station markers and the app
makes no network requests. Settings are stored locally in
map_settings.json in the app support directory.

path_provider was already locked as a transitive dependency; it is now a
direct dependency with the same locked version.
2026-11-26 20:07:17 +03:30
4 changed files with 227 additions and 13 deletions

No files matched your search

+118 -12
View File
@@ -4,6 +4,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:mashhad_metro/models/station_model.dart';
import 'package:mashhad_metro/providers/map_settings_provider.dart';
import 'package:mashhad_metro/pages/station_details.dart';
import 'package:mashhad_metro/providers/station_provider.dart';
import 'package:mashhad_metro/widgets/station_status.dart';
@@ -147,6 +148,7 @@ class _MapPageState extends ConsumerState<MapPage> {
@override
Widget build(BuildContext context) {
final stationsAsync = ref.watch(allStationsProvider);
final mapSettings = ref.watch(mapSettingsProvider);
return Scaffold(
backgroundColor: const Color(0xFF1A1A1A),
@@ -178,6 +180,13 @@ class _MapPageState extends ConsumerState<MapPage> {
],
),
centerTitle: true,
actions: [
IconButton(
tooltip: 'تنظیمات نقشه',
icon: const Icon(Icons.layers_outlined, color: Colors.white),
onPressed: _showMapSettingsDialog,
),
],
),
body: stationsAsync.when(
data: (stations) {
@@ -208,11 +217,12 @@ class _MapPageState extends ConsumerState<MapPage> {
maxZoom: 18,
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'ir.shahriaarrr.mashhad_metro',
),
if (mapSettings.loaded && mapSettings.tilesEnabled)
TileLayer(
key: ValueKey(mapSettings.tileUrl),
urlTemplate: mapSettings.tileUrl,
userAgentPackageName: 'ir.shahriaarrr.mashhad_metro',
),
MarkerLayer(markers: _buildStationMarkers(stations)),
if (_currentPosition != null)
@@ -248,13 +258,18 @@ class _MapPageState extends ConsumerState<MapPage> {
],
),
RichAttributionWidget(
alignment: AttributionAlignment.bottomLeft,
popupInitialDisplayDuration: const Duration(seconds: 3),
attributions: [
TextSourceAttribution('© OpenStreetMap contributors'),
],
),
if (mapSettings.loaded && mapSettings.tilesEnabled)
RichAttributionWidget(
alignment: AttributionAlignment.bottomLeft,
popupInitialDisplayDuration: const Duration(seconds: 3),
attributions: [
TextSourceAttribution(
mapSettings.isDefaultServer
? '© OpenStreetMap contributors'
: '© OpenStreetMap contributors · ${mapSettings.tileHost}',
),
],
),
],
),
@@ -293,6 +308,97 @@ class _MapPageState extends ConsumerState<MapPage> {
);
}
Future<void> _showMapSettingsDialog() async {
final current = ref.read(mapSettingsProvider);
final urlController = TextEditingController(text: current.tileUrl);
var tilesEnabled = current.tilesEnabled;
String? urlError;
await showDialog<void>(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (dialogContext, setDialogState) => Directionality(
textDirection: TextDirection.rtl,
child: AlertDialog(
title: const Text('تنظیمات نقشه'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('نمایش نقشه زمینه'),
subtitle: const Text(
'در صورت غیرفعال بودن، فقط ایستگاه‌ها نمایش داده می‌شوند و هیچ اتصال اینترنتی برقرار نمی‌شود.',
),
value: tilesEnabled,
onChanged: (value) =>
setDialogState(() => tilesEnabled = value),
),
const SizedBox(height: 12),
TextField(
controller: urlController,
enabled: tilesEnabled,
textDirection: TextDirection.ltr,
keyboardType: TextInputType.url,
autocorrect: false,
decoration: InputDecoration(
labelText: 'آدرس سرور نقشه (Tile URL)',
hintText: defaultTileUrl,
helperText: 'باید شامل {z}، {x} و {y} باشد',
errorText: urlError,
border: const OutlineInputBorder(),
),
),
],
),
),
actions: [
TextButton(
onPressed: () {
setDialogState(() {
urlController.text = defaultTileUrl;
tilesEnabled = true;
urlError = null;
});
},
child: const Text('پیش‌فرض'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('انصراف'),
),
FilledButton(
onPressed: () {
final url = urlController.text.trim();
if (tilesEnabled && !MapSettings.isValidTileUrl(url)) {
setDialogState(() => urlError = 'آدرس نامعتبر است');
return;
}
ref
.read(mapSettingsProvider.notifier)
.update(
MapSettings(
tilesEnabled: tilesEnabled,
tileUrl: MapSettings.isValidTileUrl(url)
? url
: current.tileUrl,
),
);
Navigator.pop(dialogContext);
},
child: const Text('ذخیره'),
),
],
),
),
),
);
urlController.dispose();
}
List<Marker> _buildStationMarkers(List<StationModel> stations) {
return stations
.map((station) {
+107
View File
@@ -0,0 +1,107 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:path_provider/path_provider.dart';
const String defaultTileUrl = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
class MapSettings {
/// Whether map tiles are downloaded at all. When false the map shows only
/// the bundled station markers and makes no network requests.
final bool tilesEnabled;
/// Tile URL template, e.g. https://tile.openstreetmap.org/{z}/{x}/{y}.png
final String tileUrl;
/// False until the saved settings have been read from disk, so the map
/// never contacts the default server before a user's choice is known.
final bool loaded;
const MapSettings({
this.tilesEnabled = true,
this.tileUrl = defaultTileUrl,
this.loaded = true,
});
bool get isDefaultServer => tileUrl == defaultTileUrl;
/// Host name of the tile server, for attribution.
String get tileHost => Uri.tryParse(_fillPlaceholders(tileUrl))?.host ?? '';
static String _fillPlaceholders(String url) =>
url.replaceAll(RegExp(r'\{[a-z]+\}'), '0');
MapSettings copyWith({bool? tilesEnabled, String? tileUrl}) => MapSettings(
tilesEnabled: tilesEnabled ?? this.tilesEnabled,
tileUrl: tileUrl ?? this.tileUrl,
);
Map<String, dynamic> toJson() => {
'tilesEnabled': tilesEnabled,
'tileUrl': tileUrl,
};
factory MapSettings.fromJson(Map<String, dynamic> json) => MapSettings(
tilesEnabled: json['tilesEnabled'] as bool? ?? true,
tileUrl: json['tileUrl'] as String? ?? defaultTileUrl,
);
/// Returns true when [url] looks like a usable tile URL template.
static bool isValidTileUrl(String url) {
final uri = Uri.tryParse(_fillPlaceholders(url.trim()));
return uri != null &&
(uri.scheme == 'https' || uri.scheme == 'http') &&
uri.host.isNotEmpty &&
url.contains('{z}') &&
url.contains('{x}') &&
url.contains('{y}');
}
}
class MapSettingsNotifier extends StateNotifier<MapSettings> {
MapSettingsNotifier() : super(const MapSettings(loaded: false)) {
_load();
}
Future<File> _file() async {
final dir = await getApplicationSupportDirectory();
return File('${dir.path}/map_settings.json');
}
Future<void> _load() async {
var settings = const MapSettings();
try {
final file = await _file();
if (await file.exists()) {
settings = MapSettings.fromJson(
jsonDecode(await file.readAsString()) as Map<String, dynamic>,
);
}
} catch (_) {
// Corrupt or unreadable settings: keep defaults.
}
if (mounted) {
state = settings;
}
}
Future<void> _save() async {
try {
final file = await _file();
await file.writeAsString(jsonEncode(state.toJson()));
} catch (_) {}
}
Future<void> update(MapSettings settings) async {
state = settings;
await _save();
}
Future<void> reset() => update(const MapSettings());
}
final mapSettingsProvider =
StateNotifierProvider<MapSettingsNotifier, MapSettings>(
(ref) => MapSettingsNotifier(),
);
+1 -1
View File
@@ -657,7 +657,7 @@ packages:
source: hosted
version: "1.9.1"
path_provider:
dependency: transitive
dependency: "direct main"
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
+1
View File
@@ -43,6 +43,7 @@ dependencies:
latlong2: ^0.9.1
url_launcher: ^6.3.2
package_info_plus: ^8.3.1
path_provider: ^2.1.5
dev_dependencies:
flutter_test: