Files
mobile-flutter/covas_mobile/lib/pages/ItemMenu.dart
2025-07-30 23:54:15 +02:00

424 lines
16 KiB
Dart

// ignore_for_file: unnecessary_brace_in_string_interps
import 'dart:io';
import 'dart:convert';
import 'package:covas_mobile/classes/alert.dart';
import 'package:covas_mobile/pages/ListItemByTags.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import '../variable/globals.dart' as globals;
import '../classes/events.dart';
import '../classes/MyDrawer.dart';
import 'ListItemMenu.dart';
import 'MapboxPages.dart';
import 'ListItemByOrganizers.dart';
import 'EditEvent.dart';
import '../classes/ad_helper.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import '../classes/auth_service.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import '../locale_provider.dart'; //
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await MobileAds.instance.initialize();
initializeDateFormatting("fr_FR", null).then((_) => (const MyApp()));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const ItemMenu(title: 'Flutter Demo Home Page'),
);
}
}
class ItemMenu extends StatefulWidget {
const ItemMenu({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<ItemMenu> createState() => _ItemMenuState();
}
class _ItemMenuState extends State<ItemMenu> with ShowAlertDialog {
BannerAd? _bannerAd;
final AuthService _authService = AuthService();
String listUser = "";
String eventName = "";
String eventStartDate = "";
String eventDescription = "";
String place = "";
String imgUrl = "";
List<String> tags = [];
List<String> organizers = [];
String id = "";
Events? events;
@override
void initState() {
super.initState();
_authService.checkTokenStatus(context);
AdHelper.createBannerAd(() => setState(() {})).then((ad) {
setState(() {
_bannerAd = ad;
});
});
_getEventInfos();
}
Future<void> _getEventInfos() async {
final prefs = await SharedPreferences.getInstance();
final accessToken = prefs.getString("access_token") ?? "";
if (accessToken.isEmpty) {
showAlertDialog(context, AppLocalizations.of(context)?.error ?? "Error",
AppLocalizations.of(context)?.invalid_cache ?? "Invalid cache");
return;
}
final urlGet = Uri.parse("${globals.api}/events/${widget.title}");
final responseGet = await http.get(
urlGet,
headers: {HttpHeaders.cookieHeader: 'access_token=$accessToken'},
);
if (responseGet.statusCode == 200) {
final responseBody = utf8.decode(responseGet.bodyBytes);
final event = Events.fromJson(jsonDecode(responseBody));
final locale = Provider.of<LocaleProvider>(context, listen: false)
.locale
?.toString() ??
'en_US';
final startDate =
DateTime.parse(event.startDate ?? DateTime.now().toString());
//final date = DateFormat.yMd().format(startDate);
//final time = DateFormat.Hm().format(startDate);
final endDate =
DateTime.parse(event.endDate ?? DateTime.now().toString());
String separator = AppLocalizations.of(context)?.at ?? "at";
final formattedStartDate =
DateFormat("EEEE d MMMM y '${separator}' HH:mm", locale)
.format(startDate);
final formattedEndDate =
DateFormat("EEEE d MMMM y '${separator}' HH:mm", locale)
.format(endDate);
String link = AppLocalizations.of(context)?.to_date ?? "to";
setState(() {
eventName = event.name ?? "";
eventStartDate = "$formattedStartDate ${link} $formattedEndDate";
organizers = List<String>.from(event.organizers ?? []);
place = event.place ?? "";
imgUrl = event.imgUrl ?? "";
eventDescription = event.description ?? "";
tags = List<String>.from(event.tags ?? []);
});
} else {
final messages = {
400: AppLocalizations.of(context)?.request_error ??
"Poorly constructed query",
406: AppLocalizations.of(context)?.incorrect_password ??
"Incorrect password",
404: AppLocalizations.of(context)?.unknown_user ?? "Unknown user",
403: AppLocalizations.of(context)?.disabled_user ?? "Disabled user",
410: AppLocalizations.of(context)?.invalid_token ?? "Invalid token",
500: AppLocalizations.of(context)?.internal_error_server ??
"Internal error server"
};
final errorMessage = messages[responseGet.statusCode] ??
AppLocalizations.of(context)?.unknown_error_auth ??
"Unknown error auth";
showAlertDialog(context, AppLocalizations.of(context)?.error ?? "Error",
errorMessage);
}
}
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text("${eventName}", overflow: TextOverflow.ellipsis),
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (_) => ListItemMenu()));
},
)),
drawer: MyDrawer(),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
_bannerAd == null
? SizedBox.shrink()
: SizedBox(
height: _bannerAd!.size.height.toDouble(),
width: _bannerAd!.size.width.toDouble(),
child: AdWidget(ad: _bannerAd!)),
Padding(
padding: const EdgeInsets.only(top: 60.0),
child: Image.network(
imgUrl,
width: MediaQuery.of(context).size.width *
0.5, // 50% of screen width
height: MediaQuery.of(context).size.height * 0.5,
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) {
return child; // The image has finished loading
}
return Center(
child: CircularProgressIndicator(),
);
},
errorBuilder: (BuildContext context, Object error,
StackTrace? stackTrace) {
return Center(
child: Icon(Icons.error,
size: MediaQuery.of(context).size.width * 0.1),
);
},
)),
Row(children: [
Icon(Icons.event),
Text(
AppLocalizations.of(context)?.item_date ?? "Date : ",
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),
)
]),
Row(
children: [
Flexible(
child: Text("${eventStartDate}",
style: TextStyle(fontSize: 15.0)))
],
),
Row(children: [
Icon(Icons.explore),
Text(
AppLocalizations.of(context)?.item_maps ?? "Maps : ",
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),
)
]),
Row(children: [
Flexible(
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => MapboxPages(
title: '${widget.title}',
place: '${place}')));
},
child: Text("${place}",
style: TextStyle(fontSize: 15.0),
maxLines: 3,
overflow: TextOverflow.ellipsis)))
]),
Row(children: [
Icon(Icons.group),
Text(
AppLocalizations.of(context)?.item_organizer ?? "Organizers : ",
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),
)
]),
Row(children: [
Flexible(
flex: 3,
fit: FlexFit.tight,
child: Padding(
padding: const EdgeInsets.only(
top: 8,
bottom: 8,
left: 8,
),
child: Wrap(
runSpacing: 2.0,
spacing: 2.0,
children: organizers.map((String tag) {
return Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
color: Colors.blue,
),
margin: const EdgeInsets.symmetric(horizontal: 5.0),
padding: const EdgeInsets.symmetric(
horizontal: 10.0, vertical: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ListItemOrganizers(
organizer: '$tag')));
},
child: Text(
'$tag',
style: const TextStyle(color: Colors.white),
),
),
],
),
);
}).toList()),
)),
]),
Row(children: [
Icon(Icons.description),
Text(
AppLocalizations.of(context)?.item_description ??
"Description : ",
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold))
]),
Row(children: [
Flexible(
child: Text("${eventDescription}",
style: TextStyle(fontSize: 15.0),
maxLines: 3,
overflow: TextOverflow.ellipsis))
]),
Row(children: [
Icon(Icons.category),
Text(AppLocalizations.of(context)?.item_tags ?? "Tags : ",
style: TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold))
]),
Row(
children: [
Flexible(
flex: 3,
fit: FlexFit.tight,
child: Padding(
padding: const EdgeInsets.only(
top: 8,
bottom: 8,
left: 8,
),
child: Wrap(
runSpacing: 2.0,
spacing: 2.0,
children: tags.map((String tag) {
return Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(20.0),
),
color: Colors.blue,
),
margin:
const EdgeInsets.symmetric(horizontal: 5.0),
padding: const EdgeInsets.symmetric(
horizontal: 10.0, vertical: 5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
ListItemTags(tags: '$tag')));
},
child: Text(
'$tag',
style:
const TextStyle(color: Colors.white),
),
),
],
),
);
}).toList()),
)),
],
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => EditEvent(
events: events,
imgPath: "",
)),
);
},
backgroundColor: Colors.blue,
tooltip: AppLocalizations.of(context)?.search ?? 'Search',
child: const Icon(Icons.edit, color: Colors.white),
),
);
}
}