mobile-flutter/covas_mobile/lib/pages/ListItemMenu.dart

512 lines
17 KiB
Dart
Raw Normal View History

import 'package:covas_mobile/classes/alert.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart'; // Import dotenv
2024-06-23 17:23:26 +02:00
import 'dart:convert';
2024-06-24 23:57:43 +02:00
import 'dart:io';
2024-10-28 22:52:00 +01:00
import 'ItemMenu.dart';
2024-11-05 23:29:55 +01:00
import 'SearchDelegate.dart';
2024-06-30 15:17:10 +02:00
import '../classes/events.dart';
2024-06-23 20:57:54 +02:00
import 'package:shared_preferences/shared_preferences.dart';
2024-06-27 00:01:07 +02:00
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
2024-11-04 23:53:24 +01:00
import 'dart:math';
2024-11-06 13:27:31 +01:00
import 'package:geolocator/geolocator.dart';
2024-06-30 15:17:10 +02:00
import '../variable/globals.dart' as globals;
2024-11-06 13:27:31 +01:00
import 'package:permission_handler/permission_handler.dart';
2024-11-07 23:10:03 +01:00
import "Camera.dart";
import 'package:camera/camera.dart';
2024-06-24 23:57:43 +02:00
2024-06-23 17:23:26 +02:00
void main() {
2024-10-28 22:52:00 +01:00
initializeDateFormatting("fr_FR", null).then((_) => runApp(const MyApp()));
2024-06-23 17:23:26 +02:00
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const ListItemMenu(),
debugShowCheckedModeBanner: false,
);
}
}
class ListItemMenu extends StatefulWidget {
const ListItemMenu({super.key});
@override
State<ListItemMenu> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<ListItemMenu> {
2024-06-24 23:57:43 +02:00
Future<List<Events>> postsFuture = getPosts();
2024-10-23 22:43:03 +02:00
List<Events> filteredPosts = [];
String geographicalZone = '';
String query = '';
2024-11-04 23:53:24 +01:00
List<Map<String, dynamic>> suggestions = [];
TextEditingController inputGeo = TextEditingController();
2024-11-20 23:48:01 +01:00
TextEditingController Datepicker = TextEditingController();
// Fetching events from API
2024-06-24 23:57:43 +02:00
static Future<List<Events>> getPosts() async {
2024-11-06 15:55:15 +01:00
PermissionStatus status = await Permission.location.status;
final List<Events> body = [];
2024-11-06 15:55:15 +01:00
var url = Uri.parse("${globals.api}/events");
if (status.isGranted) {
print("Location permission granted");
// Get the current position with high accuracy
const LocationSettings locationSettings = LocationSettings(
accuracy: LocationAccuracy.medium,
timeLimit: Duration(seconds: 5),
2024-11-06 15:55:15 +01:00
);
Position? position;
try {
position = await Geolocator.getCurrentPosition(
locationSettings: locationSettings);
} on LocationServiceDisabledException {
// Handle location services disabled
print('Location services are disabled.');
position = await Geolocator.getLastKnownPosition();
if (position == null) {
print('No last known position available.');
}
} catch (e) {
// Handle other errors
print('Failed to get location: $e');
position = await Geolocator.getLastKnownPosition();
if (position == null) {
print('No last known position available.');
}
}
if (position != null) {
// Calculate the boundaries
double radiusInKm = 50;
double latDistance = radiusInKm / 111.0;
double lonDistance =
radiusInKm / (111.0 * cos(position.latitude * pi / 180));
2024-11-06 15:55:15 +01:00
double minLat = position.latitude - latDistance;
double maxLat = position.latitude + latDistance;
double minLon = position.longitude - lonDistance;
double maxLon = position.longitude + lonDistance;
DateTime currentDatetime = DateTime.now();
url = Uri.parse("${globals.api}/events/search"
"?min_lat=$minLat&max_lat=$maxLat"
"&min_lon=$minLon&max_lon=$maxLon&current_datetime=${currentDatetime.toString()}");
}
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? "";
if (accessToken.isNotEmpty) {
final response = await http.get(url, headers: {
"Content-Type": "application/json",
HttpHeaders.cookieHeader: "access_token=${accessToken}"
});
final List body = json.decode(utf8.decode(response.bodyBytes));
return body.map((e) => Events.fromJson(e)).toList();
}
2024-11-06 15:55:15 +01:00
}
return body;
}
// Fetching events from API
Future<List<Events>> getAllPosts() async {
2024-06-23 20:57:54 +02:00
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? "";
2024-06-24 23:57:43 +02:00
final List<Events> body = [];
2024-06-23 20:57:54 +02:00
if (accessToken.isNotEmpty) {
2024-11-11 11:52:21 +01:00
DateTime currentDateTime = DateTime.now();
2024-11-10 18:18:08 +01:00
var url = Uri.parse(
"${globals.api}/events?current_datetime=${currentDateTime.toString()}");
2024-06-24 23:57:43 +02:00
final response = await http.get(url, headers: {
"Content-Type": "application/json",
HttpHeaders.cookieHeader: "access_token=${accessToken}"
});
final List body = json.decode(utf8.decode(response.bodyBytes));
return body.map((e) => Events.fromJson(e)).toList();
2024-06-23 20:57:54 +02:00
}
return body;
2024-06-23 17:23:26 +02:00
}
2024-11-05 15:59:31 +01:00
@override
void initState() {
super.initState();
// Initialize data fetch when the page loads
2024-11-06 13:27:31 +01:00
_getCurrentLocation();
}
2024-11-06 15:55:15 +01:00
// Get the device's current location
Future<void> _getCurrentLocation() async {
2024-11-06 13:27:31 +01:00
PermissionStatus status = await Permission.location.status;
if (status.isGranted) {
print("Location permission granted");
2024-11-06 15:55:15 +01:00
// Get the current position with high accuracy
2024-11-23 09:56:37 +01:00
const LocationSettings locationSettings = LocationSettings(
accuracy: LocationAccuracy.medium, timeLimit: Duration(seconds: 5));
Position? position;
try {
position = await Geolocator.getCurrentPosition(
locationSettings: locationSettings);
} on LocationServiceDisabledException {
// Handle location services disabled
print('Location services are disabled.');
position = await Geolocator.getLastKnownPosition();
if (position == null) {
print('No last known position available.');
}
} catch (e) {
// Handle other errors
print('Failed to get location: $e');
position = await Geolocator.getLastKnownPosition();
if (position == null) {
print('No last known position available.');
}
}
2024-11-06 13:27:31 +01:00
2024-11-06 15:55:15 +01:00
// Reverse geocode: Get city and country from latitude and longitude using Mapbox Search API
2024-11-23 09:56:37 +01:00
if (position != null) {
_getCityAndCountry(position!.latitude, position!.longitude);
}
2024-11-06 13:27:31 +01:00
}
}
// Method to get city and country from latitude and longitude using Mapbox API
Future<void> _getCityAndCountry(double latitude, double longitude) async {
await dotenv.load(fileName: ".env"); // Load .env file
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? '';
final url = Uri.parse(
'https://api.mapbox.com/geocoding/v5/mapbox.places/$longitude,$latitude.json?access_token=$mapboxAccessToken',
);
try {
// Send GET request to Mapbox API
final response = await http.get(url);
// If the request is successful (HTTP status 200)
print("status mapbox : ${response.statusCode}");
if (response.statusCode == 200) {
// Parse the response body
final data = json.decode(response.body);
// Extract the city and country from the response
final features = data['features'];
if (features.isNotEmpty) {
String city = _getCityFromFeatures(features);
String country = _getCountryFromFeatures(features);
print("city : ${city} ${country}");
if (city.isNotEmpty && country.isNotEmpty) {
2024-11-06 15:55:15 +01:00
fetchPostsByLocation(latitude, longitude);
2024-11-06 13:27:31 +01:00
setState(() {
inputGeo.text = "${city}, ${country}";
});
} else {
_fetchInitialData();
}
} else {
_fetchInitialData();
}
} else {
_fetchInitialData();
throw Exception('Failed to load location data');
}
} catch (e) {
_fetchInitialData();
2024-11-06 15:55:15 +01:00
print("Error getting city and country: $e");
2024-11-06 13:27:31 +01:00
}
}
// Helper function to extract the city from the Mapbox features array
String _getCityFromFeatures(List<dynamic> features) {
for (var feature in features) {
if (feature['place_type'] != null &&
feature['place_type'].contains('place')) {
return feature['text'] ?? '';
}
}
return '';
}
// Helper function to extract the country from the Mapbox features array
String _getCountryFromFeatures(List<dynamic> features) {
for (var feature in features) {
if (feature['place_type'] != null &&
feature['place_type'].contains('country')) {
return feature['text'] ?? '';
}
}
return '';
2024-11-05 15:59:31 +01:00
}
// Fetch initial data from API or any other necessary initialization
Future<void> _fetchInitialData() async {
try {
// Optionally, you can fetch posts initially if needed.
2024-11-06 15:55:15 +01:00
List<Events> initialPosts = await getAllPosts();
2024-11-05 15:59:31 +01:00
setState(() {
// Assign to the postsFuture and update the filtered posts if needed
filteredPosts = initialPosts;
});
} catch (e) {
print('Error fetching initial data: $e');
}
}
Future<void> searchSuggestions(String input) async {
await dotenv.load(fileName: ".env"); // Load .env file
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? '';
final url =
2024-11-04 23:53:24 +01:00
'https://api.mapbox.com/geocoding/v5/mapbox.places/${input}.json?access_token=${mapboxAccessToken}&proximity=ip';
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final data = json.decode(response.body);
setState(() {
suggestions = (data['features'] as List)
2024-11-04 23:53:24 +01:00
.map((feature) => {
'place_name': feature['place_name'],
'geometry': feature[
'geometry'], // Include geometry for latitude/longitude
})
.toList();
2024-10-23 22:43:03 +02:00
});
} else {
throw Exception('Failed to load suggestions');
2024-10-23 22:43:03 +02:00
}
2024-07-06 17:29:41 +02:00
}
2024-11-04 23:53:24 +01:00
Future<void> fetchPostsByLocation(double latitude, double longitude) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? "";
if (accessToken.isNotEmpty) {
// Calculate the boundaries
double radiusInKm = 50;
double latDistance = radiusInKm / 111.0;
double lonDistance = radiusInKm / (111.0 * cos(latitude * pi / 180));
double minLat = latitude - latDistance;
double maxLat = latitude + latDistance;
double minLon = longitude - lonDistance;
double maxLon = longitude + lonDistance;
2024-11-10 18:18:08 +01:00
DateTime currentDate = DateTime.now();
2024-11-04 23:53:24 +01:00
var url = Uri.parse("${globals.api}/events/search"
"?min_lat=$minLat&max_lat=$maxLat"
2024-11-10 18:18:08 +01:00
"&min_lon=$minLon&max_lon=$maxLon&current_datetime=${currentDate.toString()}");
2024-11-04 23:53:24 +01:00
final response = await http.get(url, headers: {
"Content-Type": "application/json",
HttpHeaders.cookieHeader: "access_token=$accessToken"
});
2024-11-05 15:59:31 +01:00
print("status code : ${response.statusCode}");
2024-11-04 23:53:24 +01:00
if (response.statusCode == 200) {
final List<dynamic> body = json.decode(utf8.decode(response.bodyBytes));
2024-11-05 15:59:31 +01:00
print("results fetch : ${body}");
// Update state after getting the response
2024-11-04 23:53:24 +01:00
setState(() {
2024-11-05 15:59:31 +01:00
if (body.isNotEmpty) {
// If we have results, map them to Events
filteredPosts = body
.map((e) => Events.fromJson(e as Map<String, dynamic>))
.toList();
} else {
// If no results, clear filteredPosts
filteredPosts.clear();
}
2024-11-04 23:53:24 +01:00
});
} else {
throw Exception('Failed to load posts');
}
}
}
2024-11-20 23:48:01 +01:00
onTapFunctionDatePicker({required BuildContext context}) async {
DateTime dateEvent = DateTime.now();
DateTime? pickedDate = await showDatePicker(
2024-11-23 09:56:37 +01:00
context: context, firstDate: dateEvent, lastDate: DateTime(2104));
2024-11-20 23:48:01 +01:00
if (pickedDate == null) return;
Datepicker.text = DateFormat("dd-MM-yyyy").format(pickedDate);
}
Padding _BuildDateField() {
return Padding(
padding: const EdgeInsets.all(8.0),
//padding: EdgeInsets.symmetric(horizontal: 15),
child: TextFormField(
controller: Datepicker,
readOnly: true,
decoration: InputDecoration(
border: OutlineInputBorder(), hintText: 'Recherche par date'),
onTap: () => onTapFunctionDatePicker(context: context)),
);
}
2024-10-28 22:52:00 +01:00
Padding _buildGeographicalZoneSearchField() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
TextField(
controller: inputGeo,
decoration: InputDecoration(
labelText: 'Search by geographical zone',
border: OutlineInputBorder(),
2024-11-04 23:53:24 +01:00
suffixIcon: IconButton(
2024-11-05 15:59:31 +01:00
icon: const Icon(Icons.clear),
2024-11-04 23:53:24 +01:00
onPressed: () {
setState(() {
inputGeo.clear(); // Clear the text field
geographicalZone = ''; // Reset the geographical zone state
suggestions.clear(); // Optionally clear suggestions
2024-11-05 15:59:31 +01:00
_fetchInitialData(); // Clear the filtered posts
2024-11-04 23:53:24 +01:00
});
},
),
),
onChanged: (value) {
setState(() {
geographicalZone = value;
searchSuggestions(value);
});
},
),
if (suggestions.isNotEmpty)
Container(
height: 200,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue),
borderRadius: BorderRadius.circular(8),
),
child: ListView.builder(
2024-11-04 23:53:24 +01:00
shrinkWrap: true,
itemCount: suggestions.length,
itemBuilder: (context, index) {
return ListTile(
2024-11-04 23:53:24 +01:00
title: Text(suggestions[index]['place_name']),
onTap: () async {
final latitude =
suggestions[index]['geometry']['coordinates'][1];
final longitude =
suggestions[index]['geometry']['coordinates'][0];
setState(() {
2024-11-04 23:53:24 +01:00
geographicalZone = suggestions[index]['place_name'];
inputGeo.text = geographicalZone;
suggestions.clear();
});
2024-11-04 23:53:24 +01:00
await fetchPostsByLocation(latitude, longitude);
},
);
},
),
),
],
2024-10-28 22:52:00 +01:00
),
);
}
2024-11-07 23:10:03 +01:00
Future<void> popCamera() async {
await availableCameras().then((value) => Navigator.push(context,
MaterialPageRoute(builder: (_) => Camera(camera: value.first))));
}
2024-06-23 17:23:26 +02:00
@override
Widget build(BuildContext context) {
return Scaffold(
2024-10-23 22:43:03 +02:00
appBar: AppBar(
title: const Text("Item list menu"),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
actions: [
IconButton(
icon: const Icon(Icons.search),
onPressed: () {
showSearch(
context: context,
2024-11-05 23:29:55 +01:00
delegate: SearchDelegateExample(geoQuery: inputGeo.text),
2024-10-23 22:43:03 +02:00
);
},
),
],
),
body: Column(
children: [
2024-10-28 22:52:00 +01:00
_buildGeographicalZoneSearchField(),
2024-11-20 23:48:01 +01:00
_BuildDateField(),
Expanded(
child: FutureBuilder<List<Events>>(
future: postsFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
2024-10-28 22:52:00 +01:00
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasData) {
final posts = snapshot.data!;
final displayedPosts =
filteredPosts.isEmpty ? posts : filteredPosts;
return buildPosts(displayedPosts);
} else {
return const Text("No data available");
}
},
),
),
],
2024-06-23 17:23:26 +02:00
),
2024-11-07 23:10:03 +01:00
floatingActionButton: FloatingActionButton(
onPressed: popCamera,
backgroundColor: Colors.blue,
tooltip: 'Recherche',
child: const Icon(Icons.photo_camera, color: Colors.white),
),
2024-06-23 17:23:26 +02:00
);
}
// Function to display fetched data on screen
2024-06-24 23:57:43 +02:00
Widget buildPosts(List<Events> posts) {
2024-11-06 15:55:15 +01:00
print("posts : ${posts}");
2024-11-05 15:59:31 +01:00
print("filteredposts : ${filteredPosts}");
final displayedPosts = filteredPosts;
print("results ${displayedPosts}");
// If filteredPosts is empty, show a message saying no data is available
if (displayedPosts.isEmpty) {
return const Center(
child: Text('No events available for this location.',
style: TextStyle(fontSize: 18, color: Colors.grey)),
);
}
2024-10-28 22:52:00 +01:00
return ListView.separated(
2024-11-07 23:10:03 +01:00
itemCount: displayedPosts.length,
itemBuilder: (context, index) {
final post = displayedPosts[index];
final startDate = DateTime.parse(post.startDate!);
final date = DateFormat.yMd().format(startDate);
final time = DateFormat.Hm().format(startDate);
return ListTile(
title: Text('${post.name!}'),
subtitle: Text('${post.place!}\n${date} ${time}'),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => ItemMenu(title: post.id!)),
);
},
);
},
separatorBuilder: (context, index) {
return Divider();
});
2024-06-23 17:23:26 +02:00
}
}