Add Android support with configurable server URL and location permissions

- Add shared_preferences for persisting server URL
- Add SettingsService and PlatformService
- Add server URL input field on non-web platforms
- Make ApiConfig baseUrl configurable at runtime
- Add Android location permissions (ACCESS_FINE/COURSE_LOCATION, INTERNET)
- Request location permission on login and map init
- Fix geo_id type: use String instead of int (UUID format)
- Align share_service with API spec: remove unique_id, use share_id only
- Fix watch endpoint response: last_update instead of created_at
- Add error handling with SnackBars for geo operations
- Wrap login screen in SingleChildScrollView for keyboard handling
- Update map tile layer with userAgentPackageName for OSM
This commit is contained in:
dmit.b
2026-05-15 17:38:56 +03:00
parent ca90c6c3fc
commit f1e88b1ac3
26 changed files with 1255 additions and 297 deletions
+16 -10
View File
@@ -1,14 +1,20 @@
class ApiConfig {
static final String baseUrl = Uri.base.origin;
static String _baseUrl = 'https://family-safety.onrender.com/api';
static String get baseUrl => _baseUrl;
static void setBaseUrl(String url) {
_baseUrl = url.endsWith('/') ? url.substring(0, url.length - 1) : url;
}
// Auth endpoints
static final String loginUrl = '$baseUrl/login';
static final String regUrl = '$baseUrl/reg';
static String get loginUrl => '$baseUrl/login';
static String get regUrl => '$baseUrl/reg';
// Geo endpoints
static final String geoUrl = '$baseUrl/geo';
static String get geoUrl => '$baseUrl/geo';
// Share endpoints
static final String shareUrl = '$baseUrl/share';
static final String watchUrl = '$baseUrl/watch';
}
static String get shareUrl => '$baseUrl/share';
static String get watchUrl => '$baseUrl/watch';
}
+13 -4
View File
@@ -1,22 +1,31 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'config/api.dart';
import 'providers/auth_provider.dart';
import 'providers/map_provider.dart';
import 'providers/share_provider.dart';
import 'screens/login_screen.dart';
import 'screens/map_screen.dart';
import 'services/settings_service.dart';
void main() {
runApp(const MyApp());
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final settings = SettingsService();
await settings.initialize();
ApiConfig.setBaseUrl(settings.baseUrl);
runApp(MyApp(settingsService: settings));
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
final SettingsService settingsService;
const MyApp({super.key, required this.settingsService});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider.value(value: settingsService),
ChangeNotifierProvider(create: (_) => AuthProvider()),
ChangeNotifierProvider(create: (_) => MapProvider()),
ChangeNotifierProvider(create: (_) => ShareProvider()),
@@ -37,4 +46,4 @@ class MyApp extends StatelessWidget {
),
);
}
}
}
+22 -13
View File
@@ -5,24 +5,24 @@ import '../services/auth_service.dart';
class AuthProvider with ChangeNotifier {
final AuthService _authService;
String _token = '';
bool _isLoading = false;
String _error = '';
AuthProvider({AuthService? authService})
: _authService = authService ?? AuthService();
AuthProvider({AuthService? authService})
: _authService = authService ?? AuthService();
String get token => _token;
bool get isLoggedIn => _token.isNotEmpty;
bool get isLoading => _isLoading;
String get error => _error;
Future<void> login(String login, String password) async {
_isLoading = true;
_error = '';
notifyListeners();
try {
var response = await _authService.login(login, password);
var data = jsonDecode(response);
@@ -37,14 +37,18 @@ class AuthProvider with ChangeNotifier {
notifyListeners();
}
}
Future<void> register(String login, String password) async {
Future<void> register(
String login,
String password,
String secretKeyHash,
) async {
_isLoading = true;
_error = '';
notifyListeners();
try {
await _authService.register(login, password);
await _authService.register(login, password, secretKeyHash);
notifyListeners();
} catch (e) {
_error = e.toString();
@@ -55,9 +59,14 @@ class AuthProvider with ChangeNotifier {
notifyListeners();
}
}
void setError(String message) {
_error = message;
notifyListeners();
}
void logout() {
_token = '';
notifyListeners();
}
}
}
+7 -7
View File
@@ -5,7 +5,7 @@ class ShareProvider with ChangeNotifier {
final ShareService _shareService;
String _shareId = '';
int _geoId = 0;
String _geoId = '';
bool _isLoading = false;
String _error = '';
@@ -19,7 +19,7 @@ class ShareProvider with ChangeNotifier {
: _shareService = shareService ?? ShareService();
String get shareId => _shareId;
int get geoId => _geoId;
String get geoId => _geoId;
bool get isLoading => _isLoading;
String get error => _error;
Map<String, dynamic>? get position => _position;
@@ -34,8 +34,8 @@ class ShareProvider with ChangeNotifier {
try {
final result = await _shareService.createShare(token, x, y);
_geoId = result['geo_id'];
_shareId = result['share_id'];
_geoId = result['geo_id']?.toString() ?? '';
_shareId = result['share_id']?.toString() ?? '';
notifyListeners();
} catch (e) {
_error = e.toString();
@@ -47,13 +47,13 @@ class ShareProvider with ChangeNotifier {
}
}
Future<void> getPosition(String token, String shareID) async {
Future<void> getPosition(String token, String shareId) async {
_isLoading = true;
_error = '';
notifyListeners();
try {
_position = await _shareService.getPosition(token, shareID);
_position = await _shareService.getPositionByShareId(token, shareId);
notifyListeners();
} catch (e) {
_error = e.toString();
@@ -67,7 +67,7 @@ class ShareProvider with ChangeNotifier {
void clearShare() {
_shareId = '';
_geoId = 0;
_geoId = '';
_position = null;
notifyListeners();
}
+189 -83
View File
@@ -1,102 +1,208 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import 'dart:convert';
class LoginScreen extends StatelessWidget {
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:provider/provider.dart';
import '../config/api.dart';
import '../providers/auth_provider.dart';
import '../services/settings_service.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
final TextEditingController _loginController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _secretKeyController = TextEditingController();
final TextEditingController _serverUrlController = TextEditingController();
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
_tabController.addListener(() {
setState(() {});
});
final settings = context.read<SettingsService>();
_serverUrlController.text = settings.baseUrl;
}
@override
void dispose() {
_tabController.dispose();
_loginController.dispose();
_passwordController.dispose();
_secretKeyController.dispose();
_serverUrlController.dispose();
super.dispose();
}
static const String _secretKey = 'FtracKer*1405.';
@override
Widget build(BuildContext context) {
final authProvider = context.watch<AuthProvider>();
final TextEditingController loginController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
final settings = context.read<SettingsService>();
return Scaffold(
body: Center(
child: Card(
margin: const EdgeInsets.all(24),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Family Safety',
style: TextStyle(
fontSize: 32,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 32),
TextField(
controller: loginController,
decoration: const InputDecoration(
labelText: 'Login',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: passwordController,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
obscureText: true,
),
const SizedBox(height: 16),
if (authProvider.error.isNotEmpty)
Text(
authProvider.error,
style: const TextStyle(color: Colors.red),
),
const SizedBox(height: 16),
Row(
resizeToAvoidBottomInset: true,
body: SingleChildScrollView(
child: Center(
child: Card(
margin: const EdgeInsets.all(24),
child: Padding(
padding: const EdgeInsets.all(24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: ElevatedButton(
onPressed: authProvider.isLoading
? null
: () async {
try {
await authProvider.login(
loginController.text,
passwordController.text,
);
if (!context.mounted) return;
Navigator.of(context).pushReplacementNamed('/map');
} catch (e) {
// Error is handled by provider
}
},
child: const Text('Login'),
const Text(
'Family Safety',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
),
const SizedBox(height: 24),
if (!kIsWeb) ...[
TextField(
controller: _serverUrlController,
decoration: const InputDecoration(
labelText: 'Server URL',
hintText: 'https://example.com/api',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.cloud_outlined),
),
keyboardType: TextInputType.url,
),
const SizedBox(width: 16),
Expanded(
child: ElevatedButton(
onPressed: authProvider.isLoading
? null
: () async {
try {
await authProvider.register(
loginController.text,
passwordController.text,
);
} catch (e) {
// Error is handled by provider
}
},
child: const Text('Register'),
const SizedBox(height: 16),
],
TabBar(
controller: _tabController,
tabs: const [
Tab(text: 'Login'),
Tab(text: 'Register'),
],
),
const SizedBox(height: 24),
TextField(
controller: _loginController,
decoration: const InputDecoration(
labelText: 'Login',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 16),
TextField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
obscureText: true,
),
if (_tabController.index == 1) ...[
const SizedBox(height: 16),
TextField(
controller: _secretKeyController,
decoration: const InputDecoration(
labelText: 'Secret Key',
border: OutlineInputBorder(),
),
obscureText: true,
),
],
),
],
const SizedBox(height: 16),
if (authProvider.error.isNotEmpty)
Text(
authProvider.error,
style: const TextStyle(color: Colors.red),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: authProvider.isLoading
? null
: () async {
if (!kIsWeb) {
final status = await Geolocator.checkPermission();
if (status == LocationPermission.denied) {
final requested = await Geolocator.requestPermission();
if (requested == LocationPermission.denied) {
authProvider.setError('Location permission denied');
return;
}
}
if (status == LocationPermission.deniedForever) {
authProvider.setError('Location permission permanently denied. Please enable it in settings.');
return;
}
}
if (!kIsWeb) {
final newUrl = _serverUrlController.text.trim();
if (newUrl.isNotEmpty && newUrl != settings.baseUrl) {
ApiConfig.setBaseUrl(newUrl);
await settings.setBaseUrl(newUrl);
}
}
if (_tabController.index == 0) {
try {
await authProvider.login(
_loginController.text,
_passwordController.text,
);
if (!context.mounted) return;
Navigator.of(
context,
).pushReplacementNamed('/map');
} catch (e) {
// Error is handled by provider
}
} else {
if (_secretKeyController.text != _secretKey) {
authProvider.setError('Invalid secret key');
return;
}
Digest digest = md5.convert(
utf8.encode(_secretKeyController.text),
);
String secretKeyHash = hex.encode(digest.bytes);
try {
await authProvider.register(
_loginController.text,
_passwordController.text,
secretKeyHash,
);
} catch (e) {
// Error is handled by provider
}
}
},
child: authProvider.isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(
_tabController.index == 0 ? 'Login' : 'Register',
),
),
],
),
),
),
),
),
),
);
}
}
}
+64 -29
View File
@@ -43,6 +43,17 @@ class _MapScreenState extends State<MapScreen> {
return;
}
final status = await Geolocator.checkPermission();
if (status == LocationPermission.denied) {
final requested = await Geolocator.requestPermission();
if (requested == LocationPermission.denied) {
return;
}
}
if (status == LocationPermission.deniedForever) {
return;
}
final position = await Geolocator.getCurrentPosition();
setState(() {
_center = LatLng(position.latitude, position.longitude);
@@ -54,11 +65,18 @@ class _MapScreenState extends State<MapScreen> {
final shareProvider = context.read<ShareProvider>();
if (authProvider.token.isNotEmpty) {
await shareProvider.createShare(
authProvider.token,
position.longitude,
position.latitude,
);
try {
await shareProvider.createShare(
authProvider.token,
position.longitude,
position.latitude,
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Ошибка геолокации: $e')),
);
}
}
if (!mounted) return;
@@ -75,6 +93,11 @@ class _MapScreenState extends State<MapScreen> {
Future<void> _updateGeolocation() async {
try {
final status = await Geolocator.checkPermission();
if (status == LocationPermission.denied) {
final requested = await Geolocator.requestPermission();
if (requested == LocationPermission.denied) return;
}
final position = await Geolocator.getCurrentPosition();
setState(() {
_center = LatLng(position.latitude, position.longitude);
@@ -85,13 +108,20 @@ class _MapScreenState extends State<MapScreen> {
final authProvider = context.read<AuthProvider>();
final shareProvider = context.read<ShareProvider>();
await GeoService().updatePosition(
authProvider.token,
shareProvider.geoId,
position.longitude,
position.latitude,
);
} catch (_) {}
if (shareProvider.geoId.isEmpty) return;
await GeoService().updatePosition(
authProvider.token,
shareProvider.geoId,
position.longitude,
position.latitude,
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Ошибка обновления позиции: $e')),
);
}
}
void _copyShareLink() {
@@ -115,19 +145,22 @@ class _MapScreenState extends State<MapScreen> {
final TextEditingController _controller = TextEditingController();
return AlertDialog(
title: const Text('Отслеживание'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Введите Share ID для отслеживания:'),
const SizedBox(height: 16),
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Введите Share ID',
border: OutlineInputBorder(),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text('Введите Share ID для отслеживания:'),
const SizedBox(height: 16),
TextField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Введите Share ID',
border: OutlineInputBorder(),
),
),
),
],
],
),
),
actions: [
TextButton(
@@ -174,8 +207,8 @@ class _MapScreenState extends State<MapScreen> {
Marker? trackedMarker;
if (shareProvider.trackedPosition != null) {
final pos = shareProvider.trackedPosition!;
final lat = pos['y'] as double;
final lng = pos['x'] as double;
final lat = pos['y'] is String ? double.parse(pos['y']) : pos['y'] as double;
final lng = pos['x'] is String ? double.parse(pos['x']) : pos['x'] as double;
trackedMarker = Marker(
point: LatLng(lat, lng),
width: 40,
@@ -226,12 +259,14 @@ class _MapScreenState extends State<MapScreen> {
),
body: FlutterMap(
options: MapOptions(
center: _center,
zoom: 12.0,
initialCenter: _center,
initialZoom: 12.0,
),
children: [
TileLayer(
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
maxZoom: 20,
userAgentPackageName:'FamilySafety/1.0.0',
),
MarkerLayer(
markers: [
-94
View File
@@ -1,94 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../providers/share_provider.dart';
class ShareScreen extends StatelessWidget {
const ShareScreen({super.key});
@override
Widget build(BuildContext context) {
final authProvider = context.watch<AuthProvider>();
final shareProvider = context.watch<ShareProvider>();
return Scaffold(
appBar: AppBar(
title: const Text('Share Location'),
),
body: Center(
child: Card(
margin: const EdgeInsets.all(24),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'Share Your Location',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
const Text(
'Create a share link to share your location with family',
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
if (shareProvider.shareId.isNotEmpty)
Column(
children: [
Text(
'Share ID: ${shareProvider.shareId}',
style: const TextStyle(
fontSize: 16,
color: Colors.blue,
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
// Copy to clipboard functionality
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Share ID copied to clipboard'),
),
);
},
child: const Text('Copy Share ID'),
),
],
)
else
ElevatedButton(
onPressed: shareProvider.isLoading
? null
: () async {
try {
await shareProvider.createShare(
authProvider.token,
55.7558, // Default Moscow coordinates
37.6173,
);
} catch (e) {
// Error is handled by provider
}
},
child: const Text('Create Share Link'),
),
if (shareProvider.error.isNotEmpty) ...[
const SizedBox(height: 16),
Text(
shareProvider.error,
style: const TextStyle(color: Colors.red),
),
],
],
),
),
),
),
);
}
}
+14 -6
View File
@@ -4,7 +4,7 @@ import '../config/api.dart';
class AuthService {
final http.Client _client;
AuthService({http.Client? client}) : _client = client ?? http.Client();
Future<String> login(String login, String password) async {
@@ -13,7 +13,7 @@ class AuthService {
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'login': login, 'password': password}),
);
if (response.statusCode == 200) {
return response.body;
} else {
@@ -21,15 +21,23 @@ class AuthService {
}
}
Future<void> register(String login, String password) async {
Future<void> register(
String login,
String password,
String secretKeyHash,
) async {
final response = await _client.post(
Uri.parse(ApiConfig.regUrl),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'login': login, 'password': password}),
body: jsonEncode({
'login': login,
'password': password,
'secret_key_hash': secretKeyHash,
}),
);
if (response.statusCode != 201) {
throw Exception('Registration failed');
}
}
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ class GeoService {
GeoService({http.Client? client}) : _client = client ?? http.Client();
Future<void> updatePosition(String token, int id, double x, double y) async {
Future<void> updatePosition(String token, String id, double x, double y) async {
final response = await _client.put(
Uri.parse('${ApiConfig.geoUrl}?id=$id'),
headers: {
+8
View File
@@ -0,0 +1,8 @@
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
class PlatformService {
bool get isWeb => kIsWeb;
bool get isNative => !kIsWeb;
String get platformName => isWeb ? 'web' : Platform.isAndroid ? 'android' : Platform.isIOS ? 'ios' : Platform.isWindows ? 'windows' : Platform.isMacOS ? 'macos' : Platform.isLinux ? 'linux' : 'unknown';
}
+28
View File
@@ -0,0 +1,28 @@
import 'package:shared_preferences/shared_preferences.dart';
class SettingsService {
static const String _baseUrlKey = 'server_base_url';
static const String _defaultBaseUrl = 'https://family-safety.onrender.com/api';
String _baseUrl = _defaultBaseUrl;
bool _initialized = false;
String get baseUrl => _baseUrl;
Future<void> initialize() async {
if (_initialized) return;
final prefs = await SharedPreferences.getInstance();
_baseUrl = prefs.getString(_baseUrlKey) ?? _defaultBaseUrl;
_initialized = true;
}
Future<void> setBaseUrl(String url) async {
_baseUrl = url;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_baseUrlKey, url);
}
void resetToDefault() {
_baseUrl = _defaultBaseUrl;
}
}
+15 -32
View File
@@ -18,35 +18,18 @@ class ShareService {
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
return {
'geo_id': data['geo_id'],
'share_id': data['share_id'],
};
try {
final data = jsonDecode(response.body) as Map<String, dynamic>;
return {
'geo_id': data['geo_id']?.toString() ?? '',
'share_id': data['share_id']?.toString() ?? '',
};
} catch (e) {
throw Exception('Failed to parse response: $e | Body: ${response.body.substring(0, response.body.length > 200 ? 200 : response.body.length)}');
}
} else {
throw Exception('Failed to create share link');
}
}
Future<Map<String, dynamic>> getPosition(String token, String uniqueId) async {
final response = await _client.get(
Uri.parse('${ApiConfig.watchUrl}?unique_id=$uniqueId'),
headers: {
'Authorization': 'Bearer $token',
},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return {
'id': data['id'],
'x': data['x'],
'y': data['y'],
'created_at': data['created_at'],
'expires_at': data['expires_at'],
};
} else {
throw Exception('Share link not found or no position available');
final errorBody = response.body.length > 200 ? response.body.substring(0, 200) : response.body;
throw Exception('Failed to create share link: ${response.statusCode} - $errorBody');
}
}
@@ -59,15 +42,15 @@ class ShareService {
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final data = jsonDecode(response.body) as Map<String, dynamic>;
return {
'x': data['x'],
'y': data['y'],
'created_at': data['created_at'],
'expires_at': data['expires_at'],
'last_update': data['last_update']?.toString() ?? '',
'expires_at': data['expires_at']?.toString() ?? '',
};
} else {
throw Exception('Share link not found or no position available');
}
}
}
}
-1
View File
@@ -1,6 +1,5 @@
class AppConstants {
static const String appName = 'Family Safety';
static const String defaultMapsApiKey = 'YOUR_MAPS_API_KEY';
// Default coordinates (Moscow)
static const double defaultLatitude = 55.7558;