skantravels/Mobile/lib/main.dart

258 lines
8.3 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'dart:math';
2024-08-05 08:00:16 +01:00
import 'package:flutter/material.dart';
2024-08-20 10:00:10 +01:00
import 'package:flutter_map/flutter_map.dart';
2024-08-21 11:49:38 +01:00
import 'package:latlong2/latlong.dart';
import 'package:mobile/favorites.dart';
2024-08-20 15:46:13 +01:00
import 'package:mobile/register.dart';
2024-08-21 11:49:38 +01:00
import 'login.dart';
2024-08-21 12:28:48 +01:00
import 'base/sidemenu.dart';
import 'profile.dart';
import 'api.dart' as api;
import 'models.dart';
import 'package:http/http.dart' as http;
2024-08-05 08:00:16 +01:00
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'H4 Flutter',
theme: ThemeData(
2024-08-20 13:04:40 +01:00
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
2024-08-05 08:00:16 +01:00
useMaterial3: true,
),
home: const MyHomePage(),
2024-08-21 12:28:48 +01:00
initialRoute: '/',
routes: {
'/home': (context) => const MyHomePage(),
2024-08-21 12:28:48 +01:00
'/profile': (context) => const ProfilePage(),
'/favorites': (context) => const FavoritesPage(),
'/login': (context) => const LoginPage(),
'/register': (context) => const RegisterPage(),
2024-08-21 12:28:48 +01:00
},
2024-08-05 08:00:16 +01:00
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
2024-08-05 08:00:16 +01:00
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
2024-08-21 11:49:38 +01:00
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
List<Favorite> _favorites = [];
2024-08-27 08:15:21 +01:00
LatLng? _selectedPoint;
double _zoom = 7.0;
2024-08-27 08:15:21 +01:00
2024-08-27 10:48:11 +01:00
void _onTap(TapPosition _, LatLng point) async {
2024-08-27 08:15:21 +01:00
setState(() => _selectedPoint = point);
final dynamic location;
try {
final response = await http.get(
Uri.parse('https://nominatim.openstreetmap.org/reverse.php?lat=${point.latitude}&lon=${point.longitude}&zoom=${max(12, _zoom.ceil())}&format=jsonv2'),
headers: {'User-Agent': 'SkanTravels/1.0'},
);
2024-08-27 10:48:11 +01:00
if (mounted && response.statusCode != 200) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Unable to fetch information about this location (HTTP ${response.statusCode})')));
debugPrint(response.body);
2024-08-27 10:48:11 +01:00
return;
}
location = jsonDecode(response.body);
} catch (_) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Unable to fetch information about this location')));
setState(() => _selectedPoint = null);
return;
}
if (!mounted) return;
2024-08-27 10:48:11 +01:00
if (location['name'] != null && location['display_name'] != null) {
await _showLocation(point, location['name'], location['display_name']);
}
setState(() => _selectedPoint = null);
}
Future<void> _showLocation(LatLng point, String name, String description) async {
await showModalBottomSheet(
barrierColor: Colors.black.withOpacity(0.3),
context: context,
builder: (builder) {
return StatefulBuilder(builder: (BuildContext context, StateSetter setModalState) {
return Wrap(children: [
Container(
color: Colors.white,
padding: const EdgeInsets.all(20),
width: MediaQuery.of(context).size.width,
child: Row(children: [
Expanded(child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
2024-08-27 10:48:11 +01:00
Text(name, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 24)),
const SizedBox(height: 10),
2024-08-27 10:48:11 +01:00
Text(description),
],
)),
Column(children: [
IconButton(
2024-08-27 10:48:11 +01:00
icon: const Icon(Icons.star),
iconSize: 32,
color: _favorites.where((fav) => fav.lat == point.latitude && fav.lng == point.longitude).isEmpty ? Colors.grey : Colors.yellow,
onPressed: () => _toggleFavorite(point, name, description, setModalState, context)
),
const IconButton(icon: Icon(Icons.rate_review), iconSize: 32, onPressed: null),
]),
]),
),
]);
});
},
);
2024-08-27 08:15:21 +01:00
}
void _toggleFavorite(LatLng point, String name, String description, StateSetter setModalState, BuildContext context) async {
final messenger = ScaffoldMessenger.of(context);
2024-08-27 10:06:33 +01:00
final navigator = Navigator.of(context);
final favorite = _favorites.where((fav) => fav.lat == point.latitude && fav.lng == point.longitude).firstOrNull;
if (!await api.isLoggedIn(context)) {
2024-08-27 10:06:33 +01:00
messenger.showSnackBar(const SnackBar(content: Text('You need to login to do that'), behavior: SnackBarBehavior.floating));
navigator.pop();
return;
}
if (!context.mounted) return;
if (favorite == null) {
final newFavorite = await api.request(
context, api.ApiService.app, 'POST', '/favorites',
{'lat': point.latitude, 'lng': point.longitude, 'name': name, 'description': description},
);
if (newFavorite == null) {
2024-08-27 10:06:33 +01:00
navigator.pop();
return;
}
setState(() {
_favorites.add(Favorite.fromJson(jsonDecode(newFavorite)));
});
setModalState(() {});
return;
}
if (await api.request(context, api.ApiService.app, 'DELETE', '/favorites/${favorite.id}', null) == null) {
2024-08-27 10:06:33 +01:00
navigator.pop();
return;
}
setState(() {
_favorites = _favorites.where((fav) => fav.id != favorite.id).toList();
});
setModalState(() {});
}
2024-08-27 10:48:11 +01:00
Future<void> _fetchFavorites() async {
final response = await api.request(context, api.ApiService.app, 'GET', '/favorites', null);
if (response == null) return;
final List<dynamic> favorites = jsonDecode(response);
setState(() {
_favorites = favorites.map((favorite) => Favorite.fromJson(favorite)).toList();
});
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
api.isLoggedIn(context).then((isLoggedIn) {
if (!isLoggedIn || !mounted) return;
_fetchFavorites();
});
}
2024-08-05 08:00:16 +01:00
@override
Widget build(BuildContext context) {
2024-08-21 12:28:48 +01:00
return SideMenu(
selectedIndex: 0,
2024-08-21 12:28:48 +01:00
body: Scaffold(
2024-08-21 13:24:53 +01:00
key: _scaffoldKey,
//drawer: navigationMenu,
body: FlutterMap(
2024-08-27 08:15:21 +01:00
options: MapOptions(
initialCenter: const LatLng(55.9397, 9.5156),
initialZoom: _zoom,
2024-08-27 10:48:11 +01:00
onTap: _onTap,
onPositionChanged: (pos, _) => _zoom = pos.zoom,
2024-08-27 08:15:21 +01:00
),
children: [
2024-08-21 12:28:48 +01:00
openStreetMapTileLayer,
2024-08-27 10:06:33 +01:00
if (_selectedPoint != null)
MarkerLayer(markers: [
Marker(
point: _selectedPoint!,
width: 30,
height: 50,
alignment: Alignment.center,
child: const Stack(
children: [
Icon(Icons.location_pin, size: 30, color: Colors.red),
Icon(Icons.location_on_outlined, size: 30, color: Colors.black),
]
),
)
]),
2024-08-22 10:46:45 +01:00
..._favorites.map((favorite) =>
MarkerLayer(markers: [
Marker(
point: LatLng(favorite.lat, favorite.lng),
2024-08-27 07:53:56 +01:00
width: 30,
height: 50,
2024-08-22 10:46:45 +01:00
alignment: Alignment.center,
2024-08-27 10:48:11 +01:00
child: Stack(
2024-08-27 07:53:56 +01:00
children: [
2024-08-27 10:48:11 +01:00
IconButton(
padding: const EdgeInsets.only(bottom: 10),
icon: const Icon(Icons.location_pin, size: 30, color: Colors.yellow),
onPressed: () => _showLocation(LatLng(favorite.lat, favorite.lng), favorite.name, favorite.description),
),
IconButton(
padding: const EdgeInsets.only(bottom: 10),
icon: const Icon(Icons.location_on_outlined, size: 30, color: Colors.black),
onPressed: () => _showLocation(LatLng(favorite.lat, favorite.lng), favorite.name, favorite.description),
),
2024-08-27 07:53:56 +01:00
]
),
2024-08-22 10:46:45 +01:00
)
2024-08-27 08:15:21 +01:00
]),
),
],
),
2024-08-21 12:28:48 +01:00
),
2024-08-05 08:00:16 +01:00
);
}
2024-08-20 15:46:13 +01:00
2024-08-21 12:28:48 +01:00
TileLayer get openStreetMapTileLayer => TileLayer(
2024-08-27 07:53:56 +01:00
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'dev.fleaflet.flutter_map.example',
);
2024-08-05 08:00:16 +01:00
}