skantravels/Mobile/lib/main.dart

462 lines
16 KiB
Dart
Raw Normal View History

import 'dart:convert';
import 'dart:math';
import 'package:flutter/cupertino.dart';
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';
import 'package:shared_preferences/shared_preferences.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 'models.dart';
import 'package:geolocator/geolocator.dart';
import 'api.dart' as api;
import 'package:http/http.dart' as http;
import 'dart:developer';
2024-08-05 08:00:16 +01:00
void main() async {
2024-09-02 12:14:13 +01:00
// Refresh JWT on startup
final prefs = await SharedPreferences.getInstance();
if (prefs.getString("token") != null && prefs.getString("refresh-token") != null) {
2024-09-02 12:14:13 +01:00
final token = await api.request(null, api.ApiService.auth, "POST", "/RefreshToken", {'refreshToken': prefs.getString("refresh-token")});
if (token != null) prefs.setString("token", token);
}
2024-08-05 08:00:16 +01:00
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;
LatLng _currentPosition = LatLng(55.656707, 10.563214);
LatLng? _userPosition;
double _zoom = 7.0;
MapController _mapController = MapController();
List<SearchResults> _searchResults = [];
final TextEditingController searchBarInput =TextEditingController(text: '');
final LocationSettings locationSettings = const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
2024-08-27 08:15:21 +01:00
@override
void didChangeDependencies() {
super.didChangeDependencies();
api.isLoggedIn(context).then((isLoggedIn) {
if (!isLoggedIn || !mounted) return;
_fetchFavorites();
});
}
@override
void dispose() {
searchBarInput.dispose();
super.dispose();
}
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();
});
}
Future<void> _getOpenStreetMapArea(LatLng fromGetLocation) async {
final dynamic location;
if (searchBarInput.text == '' && fromGetLocation == const LatLng(00.0000, 00.0000)) {
return;
}
final http.Response response;
_searchResults.clear();
if (fromGetLocation == const LatLng(00.0000, 00.0000)) {
response = await http.get(
Uri.parse('https://nominatim.openstreetmap.org/search.php?q=Attractions+in+${searchBarInput.text}&format=jsonv2'),
headers: {'User-Agent': 'SkanTravels/1.0'},
);
}
else{
response = await http.get(
Uri.parse('https://nominatim.openstreetmap.org/search.php?q=Attractions+near+${fromGetLocation.latitude}%2C+${fromGetLocation.longitude}&format=jsonv2'),
headers: {'User-Agent': 'SkanTravels/1.0'},
);
}
location = jsonDecode(response.body);
if (location is List && location.isNotEmpty) {
for (var i = 0; i < location.length; i++) {
if (location[i]['lat'] != null && location[i]['lon'] != null && location[i]['name'] != null && location[i]['display_name'] != null) {
double lat = double.parse(location[i]['lat']);
double lon = double.parse(location[i]['lon']);
String description = location[i]['display_name'];
String name = location[i]['name'];
if (name == "") {
name = description.split(",")[0];
}
setState(() {
_searchResults.add(SearchResults(LatLng(lat, lon), name, description));
});
}
}
if(fromGetLocation == const LatLng(00.0000, 00.0000)){
_mapController.move(_searchResults[0].location, 9);
}
}
}
Future<void> _getCurrentLocation() async {
LocationPermission permission = await Geolocator.checkPermission();
if(permission != LocationPermission.always || permission != LocationPermission.whileInUse){
}
else{
await Geolocator.requestPermission();
}
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
_getOpenStreetMapArea(LatLng(position.latitude, position.longitude));
_mapController.move(LatLng(position.latitude, position.longitude), 10);
setState(() {
_userPosition = LatLng(position.latitude, position.longitude);
});
}
@override
2024-08-05 08:00:16 +01:00
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,
body: Stack(
children: [
FlutterMap(
mapController: _mapController,
options: MapOptions(
initialCenter: _currentPosition,
initialZoom: _zoom,
onTap: _onTap,
onPositionChanged: (pos, _) => _zoom = pos.zoom,
),
children: [
openStreetMapTileLayer,
MarkerLayer(markers: [
if (_selectedPoint != null)
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),
],
),
),
if(_userPosition != null)
Marker(
point: _userPosition!,
width: 20,
height: 20,
alignment: Alignment.center,
child: const Icon(Icons.my_location, size: 15, color: Colors.blueAccent),
),
]),
..._searchResults.map((point) => MarkerLayer(
markers: [
Marker(
point: point.location,
width: 30,
height: 50,
alignment: Alignment.center,
child: Column(
children: [
IconButton(
icon: const Icon(Icons.location_pin, size: 30, color: Colors.red),
onPressed: () => _showLocation(point.location, point.name, point.description),
),
],
)
)
],
)),
..._favorites.map((favorite) => MarkerLayer(
markers: [
Marker(
point: LatLng(favorite.lat, favorite.lng),
width: 30,
height: 50,
alignment: Alignment.center,
child: Stack(
children: [
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),
),
],
),
)
],
)),
],
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
2024-08-27 10:48:11 +01:00
child: Stack(
2024-08-27 07:53:56 +01:00
children: [
Row(
children: [
Expanded(
child: CupertinoSearchTextField(
controller: searchBarInput,
suffixMode: OverlayVisibilityMode.never,
placeholder: 'Search city based',
2024-09-03 08:47:07 +01:00
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.white.withOpacity(0.9),
boxShadow: const [BoxShadow(color: Color(0x20000000), offset: Offset(0, 1), blurRadius: 4)]
),
),
),
],
2024-08-27 10:48:11 +01:00
),
2024-09-03 08:47:07 +01:00
Positioned(
right: 2, // Position the button at the bottom-right
bottom: 4.5,
child:
SizedBox(
width: 100,
height: 28,
child: ElevatedButton(
onPressed: () {
_getOpenStreetMapArea(const LatLng(00.0000, 00.0000));
},
2024-09-03 08:47:07 +01:00
child: const Text('Search'),
),
),
2024-08-27 10:48:11 +01:00
),
],
2024-08-27 07:53:56 +01:00
),
),
),
2024-08-27 08:15:21 +01:00
),
2024-09-03 08:47:07 +01:00
Positioned(
right: 2,
bottom: 50,
child:
SizedBox(
width: 50,
height: 50,
child: Stack(
alignment: Alignment.center,
children: [
const Icon(
Icons.circle,
color: Colors.white,
size: 48.0,
shadows: [BoxShadow(color: Color(0x20000000), offset: Offset(0, 1), blurRadius: 4)],
),
Padding(
padding: const EdgeInsets.all(3),
child: IconButton(
icon: const Icon(
Icons.location_searching,
color: Colors.blue,
2024-09-03 08:47:07 +01:00
size: 28.0,
),
onPressed: () {
_getCurrentLocation();
},
),
2024-09-03 08:47:07 +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-09-03 08:47:07 +01:00
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'dev.fleaflet.flutter_map.example',
);
}