fix: přepsat Platform UI a zmenit RefreshIndicator

This commit is contained in:
Matyáš Caras 2023-01-28 14:30:54 +01:00
parent c8d1878a39
commit 64b7f261a0
19 changed files with 1115 additions and 893 deletions

View file

@ -45,6 +45,8 @@ abstract class Languages {
// Jídelníček // Jídelníček
String get todayTooltip;
String get loading; String get loading;
String get monday; String get monday;

View file

@ -244,4 +244,7 @@ class LanguageCz extends Languages {
@override @override
String get errorSaving => String get errorSaving =>
"Při ukládání offline nastala chyba, zkuste to znovu později."; "Při ukládání offline nastala chyba, zkuste to znovu později.";
@override
String get todayTooltip => "Přejít na dnešní jídelníček";
} }

View file

@ -242,4 +242,7 @@ class LanguageEn extends Languages {
@override @override
String get errorSaving => String get errorSaving =>
"An error occured while trying to save menu offline, try again later."; "An error occured while trying to save menu offline, try again later.";
@override
String get todayTooltip => "Go to today's meal";
} }

View file

@ -2,7 +2,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class LoginManager { class LoginManager {
static Future<Map<String, String>?> getDetails() async { static Future<Map<String, String>?> getDetails() async {
// zkontrolovat secure storage pokud je něco uložené // check secure storage for details
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
var user = await storage.read(key: "oc_user"); var user = await storage.read(key: "oc_user");
var pass = await storage.read(key: "oc_pass"); var pass = await storage.read(key: "oc_pass");
@ -18,7 +18,7 @@ class LoginManager {
await storage.write(key: "oc_url", value: url); await storage.write(key: "oc_url", value: url);
} }
static Future<bool> zapamatovat() async { static Future<bool> rememberme() async {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
return await storage.containsKey(key: "oc_pass"); return await storage.containsKey(key: "oc_pass");
} }

View file

@ -1,5 +1,6 @@
import 'dart:io'; import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
@ -37,7 +38,8 @@ Copyright (C) 2022 Matyáš Caras a přispěvatelé
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin(); FlutterLocalNotificationsPlugin();
void oznamitPredem(SharedPreferences prefs, tz.Location l) async { /// Used to setup notifications about ordered food
void setupNotification(SharedPreferences prefs, tz.Location l) async {
String title; String title;
String locale = Intl.getCurrentLocale(); String locale = Intl.getCurrentLocale();
@ -50,24 +52,24 @@ void oznamitPredem(SharedPreferences prefs, tz.Location l) async {
} }
/*if (prefs.getBool("offline") ?? false) { /*if (prefs.getBool("offline") ?? false) {
// TODO možnost brát z offline dat // TODO grab data from offline storage
} else {*/ } else {*/
// bere online // data from the web
var d = await LoginManager.getDetails(); // získat údaje var d = await LoginManager.getDetails(); // grab login
if (d != null) { if (d != null) {
var c = Canteen(d["url"]!); var c = Canteen(d["url"]!);
if (await c.login(d["user"]!, d["pass"]!)) { if (await c.login(d["user"]!, d["pass"]!)) {
var jidla = await c.jidelnicekDen(); var jidla = await c.jidelnicekDen();
try { try {
var jidlo = jidla.jidla.singleWhere( var jidlo = jidla.jidla
(element) => element.objednano); // získá objednané jídlo .singleWhere((element) => element.objednano); // grab ordered meal
var kdy = DateTime.parse(prefs.getString( var kdy = DateTime.parse(prefs.getString(
"oznameni_cas")!); // uložíme čas, kdy se odeslat oznámení "oznameni_cas")!); // save the time the notif should be sent
var cas = casNaDate( var cas = timeToDate(
TimeOfDay(hour: kdy.hour, minute: kdy.minute), TimeOfDay(hour: kdy.hour, minute: kdy.minute),
); );
if (cas.isBefore(DateTime.now())) return; if (cas.isBefore(DateTime.now())) return;
// data o oznámení // notif data
const AndroidNotificationDetails androidSpec = const AndroidNotificationDetails androidSpec =
AndroidNotificationDetails('predobedem', 'Oznámení před obědem', AndroidNotificationDetails('predobedem', 'Oznámení před obědem',
channelDescription: 'Oznámení o dnešním jídle', channelDescription: 'Oznámení o dnešním jídle',
@ -76,7 +78,7 @@ void oznamitPredem(SharedPreferences prefs, tz.Location l) async {
styleInformation: BigTextStyleInformation(''), styleInformation: BigTextStyleInformation(''),
ticker: 'today meal'); ticker: 'today meal');
// naplánovat // plan through lib
await flutterLocalNotificationsPlugin.zonedSchedule( await flutterLocalNotificationsPlugin.zonedSchedule(
0, 0,
title, title,
@ -87,7 +89,7 @@ void oznamitPredem(SharedPreferences prefs, tz.Location l) async {
uiLocalNotificationDateInterpretation: uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime); UILocalNotificationDateInterpretation.absoluteTime);
} on StateError catch (_) { } on StateError catch (_) {
// nenalezeno // no ordered meal found
} }
} }
// } // }
@ -102,10 +104,10 @@ void main() async {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
if (prefs.getBool("oznamit") ?? false) { if (prefs.getBool("oznamit") ?? false) {
oznamitPredem(prefs, l); setupNotification(prefs, l);
} }
// nastavit oznámení // notif library setup
const AndroidInitializationSettings initializationSettingsAndroid = const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('notif_icon'); AndroidInitializationSettings('notif_icon');
@ -115,7 +117,6 @@ void main() async {
InitializationSettings(android: initializationSettingsAndroid, iOS: ios); InitializationSettings(android: initializationSettingsAndroid, iOS: ios);
await flutterLocalNotificationsPlugin.initialize(initializationSettings); await flutterLocalNotificationsPlugin.initialize(initializationSettings);
// spustit aplikaci
runApp(const MyApp()); runApp(const MyApp());
} }
@ -124,23 +125,38 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return (Platform
debugShowCheckedModeBanner: false, .isAndroid) // run app based on current platform to make use of the platform's respective UI lib
localizationsDelegates: const [ ? MaterialApp(
AppLocalizationsDelegate(), debugShowCheckedModeBanner: false,
...GlobalMaterialLocalizations.delegates localizationsDelegates: const [
], AppLocalizationsDelegate(),
supportedLocales: const [Locale("cs", ""), Locale("en", "")], ...GlobalMaterialLocalizations.delegates
title: "OpenCanteen", ],
theme: ThemeData( supportedLocales: const [Locale("cs", ""), Locale("en", "")],
primarySwatch: Colors.purple, title: "OpenCanteen",
), theme: ThemeData(
darkTheme: ThemeData( primarySwatch: Colors.purple,
brightness: Brightness.dark, ),
primarySwatch: Colors.purple, darkTheme: ThemeData(
), brightness: Brightness.dark,
home: const LoginPage(), primarySwatch: Colors.purple,
); ),
home: const LoginPage(),
)
: const CupertinoApp(
debugShowCheckedModeBanner: false,
localizationsDelegates: [
AppLocalizationsDelegate(),
...GlobalMaterialLocalizations.delegates
],
supportedLocales: [Locale("cs", ""), Locale("en", "")],
title: "OpenCanteen",
theme: CupertinoThemeData(
primaryColor: Colors.purple,
),
home: LoginPage(),
);
} }
} }

View file

@ -1,6 +1,8 @@
import 'package:canteenlib/canteenlib.dart'; import 'package:canteenlib/canteenlib.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:opencanteen/okna/login.dart'; import 'package:opencanteen/okna/login.dart';
import 'package:opencanteen/pw/platformbutton.dart';
import 'package:opencanteen/pw/platformdialog.dart';
import 'package:opencanteen/util.dart'; import 'package:opencanteen/util.dart';
import '../../lang/lang.dart'; import '../../lang/lang.dart';
@ -13,100 +15,101 @@ class BurzaView extends StatefulWidget {
} }
class _BurzaViewState extends State<BurzaView> { class _BurzaViewState extends State<BurzaView> {
List<Widget> obsah = []; List<Widget> content = [];
double kredit = 0.0; double balance = 0.0;
Future<void> nactiBurzu(BuildContext context) async {
obsah = [const CircularProgressIndicator()]; Future<void> loadExchange(BuildContext context) async {
widget.canteen.ziskejUzivatele().then((kr) { content = [const CircularProgressIndicator()];
kredit = kr.kredit; var uzivatel = await widget.canteen.ziskejUzivatele().catchError((o) {
widget.canteen.ziskatBurzu().then((burza) {
setState(() {
obsah = [];
if (burza.isEmpty) {
obsah = [
Text(
Languages.of(context)!.noExchange,
style: const TextStyle(fontSize: 20),
),
Text(Languages.of(context)!.pullToReload)
];
} else {
for (var b in burza) {
obsah.add(
Padding(
padding: const EdgeInsets.only(top: 15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("${b.den.day}. ${b.den.month}."),
const SizedBox(width: 10),
Flexible(
child: Text(
b.nazev,
),
),
Text("${b.pocet}x"),
TextButton(
onPressed: () {
widget.canteen.objednatZBurzy(b).then((a) {
if (a) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(Languages.of(context)!.ordered),
content: Text(
Languages.of(context)!.orderSuccess),
actions: [
TextButton(
child: Text(Languages.of(context)!.ok),
onPressed: () =>
Navigator.of(context).pop(),
)
],
),
);
} else {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(
Languages.of(context)!.cannotOrder),
content: Text(
Languages.of(context)!.errorOrdering),
actions: [
TextButton(
child: Text(Languages.of(context)!.ok),
onPressed: () =>
Navigator.of(context).pop(),
)
],
),
);
}
nactiBurzu(context);
});
},
child: Text(Languages.of(context)!.order)),
],
),
),
);
}
}
});
});
}).catchError((o) {
if (!widget.canteen.prihlasen) { if (!widget.canteen.prihlasen) {
Navigator.pushReplacement( Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => const LoginPage())); context, platformRouter((c) => const LoginPage()));
}
return Uzivatel(kredit: 0);
});
balance = uzivatel.kredit;
var burza = await widget.canteen.ziskatBurzu();
setState(() {
content = [];
if (burza.isEmpty) {
content = [
Text(
Languages.of(context)!.noExchange,
style: const TextStyle(fontSize: 20),
),
Text(Languages.of(context)!.pullToReload)
];
} else {
for (var b in burza) {
content.add(
Padding(
padding: const EdgeInsets.only(top: 15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("${b.den.day}. ${b.den.month}."),
const SizedBox(width: 10),
Flexible(
child: Text(
b.nazev,
),
),
Text("${b.pocet}x"),
PlatformButton(
onPressed: () {
widget.canteen.objednatZBurzy(b).then(
(a) {
if (a) {
showDialog(
context: context,
builder: (context) => PlatformDialog(
title: Languages.of(context)!.ordered,
content: Languages.of(context)!.orderSuccess,
actions: [
PlatformButton(
text: Languages.of(context)!.ok,
onPressed: () =>
Navigator.of(context).pop(),
)
],
),
);
} else {
showDialog(
context: context,
builder: (context) => PlatformDialog(
title: Languages.of(context)!.cannotOrder,
content: Languages.of(context)!.errorOrdering,
actions: [
PlatformButton(
text: Languages.of(context)!.ok,
onPressed: () =>
Navigator.of(context).pop(),
)
],
),
);
}
loadExchange(context);
},
);
},
text: Languages.of(context)!.order,
),
],
),
),
);
}
} }
}); });
return;
} }
@override @override
void initState() { void initState() {
super.initState(); super.initState();
nactiBurzu(context); loadExchange(context);
} }
@override @override
@ -123,20 +126,20 @@ class _BurzaViewState extends State<BurzaView> {
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 10), const SizedBox(height: 10),
Text("${Languages.of(context)!.balance}$kredit"), Text("${Languages.of(context)!.balance}$balance"),
const SizedBox(height: 10), const SizedBox(height: 10),
SingleChildScrollView( SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
child: SizedBox( child: SizedBox(
height: MediaQuery.of(context).size.height / 1.3, height: MediaQuery.of(context).size.height / 1.3,
child: Column(children: obsah), child: Column(children: content),
), ),
) )
], ],
), ),
), ),
), ),
onRefresh: () => nactiBurzu(context)), onRefresh: () => loadExchange(context)),
); );
} }
} }

View file

@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:opencanteen/okna/login.dart'; import 'package:opencanteen/okna/login.dart';
import 'package:opencanteen/okna/nastaveni.dart'; import 'package:opencanteen/okna/nastaveni.dart';
import 'package:opencanteen/pw/platformbutton.dart';
import 'package:opencanteen/pw/platformdialog.dart';
import 'package:opencanteen/util.dart'; import 'package:opencanteen/util.dart';
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
@ -14,25 +16,25 @@ import 'package:url_launcher/url_launcher.dart';
import '../../lang/lang.dart'; import '../../lang/lang.dart';
class JidelnicekView extends StatefulWidget { class MealView extends StatefulWidget {
const JidelnicekView({Key? key, required this.canteen}) : super(key: key); const MealView({Key? key, required this.canteen}) : super(key: key);
final Canteen canteen; final Canteen canteen;
@override @override
State<JidelnicekView> createState() => _JidelnicekViewState(); State<MealView> createState() => _MealViewState();
} }
class _JidelnicekViewState extends State<JidelnicekView> { class _MealViewState extends State<MealView> {
List<Widget> obsah = [const CircularProgressIndicator()]; List<Widget> content = [const CircularProgressIndicator()];
DateTime den = DateTime.now(); DateTime day = DateTime.now();
String denTydne = ""; String dayOWeek = "";
double kredit = 0.0; double balance = 0.0;
bool _skipWeekend = false; bool _skipWeekend = false;
void kontrolaTyden(BuildContext context) async { void checkWeek(BuildContext context) async {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
if (prefs.getBool("tyden") ?? false) { if (prefs.getBool("tyden") ?? false) {
// Zjistit jestli je objednáno na přístí týden // Check if user has ordered a meal in the next week
var pristi = den.add(const Duration(days: 6)); var pristi = day.add(const Duration(days: 6));
for (var i = 0; i < 5; i++) { for (var i = 0; i < 5; i++) {
var jidelnicek = await widget.canteen var jidelnicek = await widget.canteen
.jidelnicekDen(den: pristi.add(Duration(days: i + 1))); .jidelnicekDen(den: pristi.add(Duration(days: i + 1)));
@ -47,8 +49,8 @@ class _JidelnicekViewState extends State<JidelnicekView> {
action: SnackBarAction( action: SnackBarAction(
onPressed: () => setState( onPressed: () => setState(
() { () {
den = pristi.add(Duration(days: i + 1)); day = pristi.add(Duration(days: i + 1));
nactiJidlo(); loadMeals();
}, },
), ),
label: Languages.of(context)!.jump, label: Languages.of(context)!.jump,
@ -61,288 +63,295 @@ class _JidelnicekViewState extends State<JidelnicekView> {
} }
} }
Future<void> nactiJidlo() async { Future<void> loadMeals() async {
obsah = [const CircularProgressIndicator()]; content = [const CircularProgressIndicator()];
switch (den.weekday) { switch (day.weekday) {
case 2: case 2:
denTydne = Languages.of(context)!.tuesday; dayOWeek = Languages.of(context)!.tuesday;
break; break;
case 3: case 3:
denTydne = Languages.of(context)!.wednesday; dayOWeek = Languages.of(context)!.wednesday;
break; break;
case 4: case 4:
denTydne = Languages.of(context)!.thursday; dayOWeek = Languages.of(context)!.thursday;
break; break;
case 5: case 5:
denTydne = Languages.of(context)!.friday; dayOWeek = Languages.of(context)!.friday;
break; break;
case 6: case 6:
denTydne = Languages.of(context)!.saturday; dayOWeek = Languages.of(context)!.saturday;
break; break;
case 7: case 7:
denTydne = Languages.of(context)!.sunday; dayOWeek = Languages.of(context)!.sunday;
break; break;
default: default:
denTydne = Languages.of(context)!.monday; dayOWeek = Languages.of(context)!.monday;
} }
widget.canteen.ziskejUzivatele().then((kr) { var uzivatel = await widget.canteen.ziskejUzivatele().catchError(
kredit = kr.kredit; (o) {
widget.canteen.jidelnicekDen(den: den).then((jd) async { if (!widget.canteen.prihlasen) {
setState(() { Navigator.pushReplacement(
obsah = []; context, platformRouter((c) => const LoginPage()));
if (jd.jidla.isEmpty) { }
obsah.add(Text( return Uzivatel(kredit: 0);
Languages.of(context)!.noFood, },
style: const TextStyle(fontSize: 15), );
)); balance = uzivatel.kredit;
} else { var jd = await widget.canteen.jidelnicekDen(den: day).catchError((_) {
for (var j in jd.jidla) { showInfo(context, Languages.of(context)!.errorContacting);
obsah.add( return Jidelnicek(DateTime.now(), []);
Padding( });
padding: const EdgeInsets.only(top: 15), setState(
child: InkWell( () {
child: Row( content = [];
mainAxisAlignment: MainAxisAlignment.spaceBetween, if (jd.jidla.isEmpty) {
children: [ content.add(Text(
Text(j.varianta), Languages.of(context)!.noFood,
const SizedBox(width: 10), style: const TextStyle(fontSize: 15),
Flexible( ));
child: Text( } else {
j.nazev, for (var j in jd.jidla) {
), content.add(
Padding(
padding: const EdgeInsets.only(top: 15),
child: InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(j.varianta),
const SizedBox(width: 10),
Flexible(
child: Text(
j.nazev,
), ),
Text((j.naBurze) ),
? Languages.of(context)!.inExchange Text((j.naBurze)
: "${j.cena}"), ? Languages.of(context)!.inExchange
Checkbox( : "${j.cena}"),
value: j.objednano, Checkbox(
fillColor: (j.lzeObjednat) value: j.objednano,
? MaterialStateProperty.all(Colors.purple) fillColor: (j.lzeObjednat)
: MaterialStateProperty.all(Colors.grey), ? MaterialStateProperty.all(Colors.purple)
onChanged: (v) async { : MaterialStateProperty.all(Colors.grey),
if (!j.lzeObjednat) { onChanged: (v) async {
showDialog( if (!j.lzeObjednat) {
context: context, showDialog(
builder: (context) { context: context,
return AlertDialog( builder: (context) {
title: Text(Languages.of(context)! return PlatformDialog(
.errorOrdering), title: Languages.of(context)!.errorOrdering,
content: Text( content: Languages.of(context)!.cannotOrder,
Languages.of(context)!.cannotOrder), actions: [
actions: [ PlatformButton(
TextButton( text: Languages.of(context)!.ok,
child: onPressed: () {
Text(Languages.of(context)!.ok), Navigator.of(context).pop();
onPressed: () { },
Navigator.of(context).pop(); )
}, ],
) );
], },
); );
}); } else {
} else { showDialog(
showDialog( context: context,
context: context, barrierDismissible: false,
barrierDismissible: false, builder: (_) => Dialog(
builder: (_) => Dialog( child: SizedBox(
child: SizedBox( height: 100,
height: 100, child: Row(
child: Row(children: [ children: [
const Padding(
padding: EdgeInsets.all(10),
child:
CircularProgressIndicator(),
),
Text(Languages.of(context)!
.ordering)
]),
),
));
widget.canteen.objednat(j).then((_) {
Navigator.of(context, rootNavigator: true)
.pop();
nactiJidlo();
}).catchError((o) {
Navigator.of(context, rootNavigator: true)
.pop();
showDialog(
context: context,
builder: (bc) => AlertDialog(
title: Text(Languages.of(context)!
.errorOrdering),
content: Text(o.toString()),
actions: [
TextButton(
child: Text(
Languages.of(context)!
.close),
onPressed: () {
Navigator.pop(bc);
},
)
],
));
});
}
})
],
),
onTap: () async {
if (!j.lzeObjednat) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title:
Text(Languages.of(context)!.errorOrdering),
content:
Text(Languages.of(context)!.cannotOrder),
actions: [
TextButton(
child: Text(Languages.of(context)!.ok),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
} else {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => Dialog(
child: SizedBox(
height: 100,
child: Row(children: [
const Padding( const Padding(
padding: EdgeInsets.all(10), padding: EdgeInsets.all(10),
child: CircularProgressIndicator(), child: CircularProgressIndicator(),
), ),
Text(Languages.of(context)!.ordering) Text(Languages.of(context)!.ordering)
]), ],
), ),
)); ),
widget.canteen.objednat(j).then((_) {
Navigator.of(context, rootNavigator: true).pop();
nactiJidlo();
}).catchError(
(o) {
Navigator.of(context, rootNavigator: true).pop();
showDialog(
context: context,
builder: (bc) => AlertDialog(
title:
Text(Languages.of(context)!.errorOrdering),
content: Text(o.toString()),
actions: [
TextButton(
child: Text(Languages.of(context)!.close),
onPressed: () {
Navigator.pop(bc);
},
)
],
), ),
); );
}, widget.canteen.objednat(j).then((_) {
); Navigator.of(context, rootNavigator: true).pop();
} loadMeals();
}, }).catchError(
onLongPress: () async { (o) {
if (!j.objednano || j.burzaUrl == null) return; Navigator.of(context, rootNavigator: true)
if (!j.naBurze) { .pop();
// pokud není na burze, radši se zeptáme showDialog(
var d = await showDialog( context: context,
context: context, builder: (bc) => PlatformDialog(
builder: (bc) => SimpleDialog( title: Languages.of(context)!.errorOrdering,
title: Text( content: o.toString(),
Languages.of(context)!.verifyExchange), actions: [
children: [ PlatformButton(
SimpleDialogOption( text: Languages.of(context)!.close,
onPressed: () { onPressed: () {
Navigator.pop(bc, true); Navigator.pop(bc);
}, },
child: Text(Languages.of(context)!.yes), )
), ],
SimpleDialogOption( ),
onPressed: () { );
Navigator.pop(bc, false); },
},
child: Text(Languages.of(context)!.no),
),
],
));
if (d) {
widget.canteen
.doBurzy(j)
.then((_) => nactiJidlo())
.catchError((o) {
showDialog(
context: context,
builder: (bc) => AlertDialog(
title:
Text(Languages.of(context)!.exchangeError),
content: SingleChildScrollView(
child: Text(o.toString())),
actions: [
TextButton(
child: Text(Languages.of(context)!.close),
onPressed: () {
Navigator.pop(bc);
},
)
],
),
); );
}); }
} },
} else { )
// jinak ne ],
widget.canteen.doBurzy(j).then((_) => nactiJidlo());
}
},
), ),
onTap: () async {
if (!j.lzeObjednat) {
showDialog(
context: context,
builder: (context) {
return PlatformDialog(
title: Languages.of(context)!.errorOrdering,
content: Languages.of(context)!.cannotOrder,
actions: [
PlatformButton(
text: Languages.of(context)!.ok,
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
} else {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => Dialog(
child: SizedBox(
height: 100,
child: Row(children: [
const Padding(
padding: EdgeInsets.all(10),
child: CircularProgressIndicator(),
),
Text(Languages.of(context)!.ordering)
]),
),
),
);
widget.canteen.objednat(j).then((_) {
Navigator.of(context, rootNavigator: true).pop();
loadMeals();
}).catchError(
(o) {
Navigator.of(context, rootNavigator: true).pop();
showDialog(
context: context,
builder: (bc) => PlatformDialog(
title: Languages.of(context)!.errorOrdering,
content: o.toString(),
actions: [
PlatformButton(
text: Languages.of(context)!.close,
onPressed: () {
Navigator.pop(bc);
},
)
],
),
);
},
);
}
},
onLongPress: () async {
if (!j.objednano || j.burzaUrl == null) return;
if (!j.naBurze) {
// if not in exchange, we ask
var d = await showDialog(
context: context,
builder: (bc) => PlatformDialog(
title: Languages.of(context)!.verifyExchange,
actions: [
PlatformButton(
onPressed: () {
Navigator.pop(bc, true);
},
text: Languages.of(context)!.yes,
),
PlatformButton(
onPressed: () {
Navigator.pop(bc, false);
},
text: Languages.of(context)!.no,
),
],
),
);
if (d) {
widget.canteen
.doBurzy(j)
.then((_) => loadMeals())
.catchError((o) {
showDialog(
context: context,
builder: (bc) => PlatformDialog(
title: Languages.of(context)!.exchangeError,
content: o.toString(),
actions: [
PlatformButton(
text: Languages.of(context)!.close,
onPressed: () {
Navigator.pop(bc);
},
)
],
),
);
});
}
} else {
// else no
widget.canteen.doBurzy(j).then((_) => loadMeals());
}
},
), ),
); ),
} );
} }
}); }
}); },
}).catchError((o) { );
if (!widget.canteen.prihlasen) { return;
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => const LoginPage()));
}
});
} }
Future<void> kliknuti(String value, BuildContext context) async { Future<void> click(String value, BuildContext context) async {
if (value == Languages.of(context)!.signOut) { if (value == Languages.of(context)!.signOut) {
await showDialog<bool>( await showDialog<bool>(
context: context, context: context,
builder: (c) => AlertDialog( builder: (c) => PlatformDialog(
title: Text(Languages.of(context)!.warning), title: Languages.of(context)!.warning,
content: Text(Languages.of(context)!.signOutWarn), content: Languages.of(context)!.signOutWarn,
actions: [ actions: [
TextButton( PlatformButton(
onPressed: () { onPressed: () {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
storage.deleteAll(); storage.deleteAll();
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(
context, context,
MaterialPageRoute(builder: (c) => const LoginPage()), platformRouter((c) => const LoginPage()),
(route) => false); (route) => false);
}, },
child: Text(Languages.of(context)!.yes)), text: Languages.of(context)!.yes),
TextButton( PlatformButton(
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
child: Text(Languages.of(context)!.no)) text: Languages.of(context)!.no,
)
], ],
), ),
); );
} else if (value == Languages.of(context)!.review) { } else if (value == Languages.of(context)!.review) {
launchUrl(Uri.parse("market://details?id=cz.hernikplays.opencanteen"), launchUrl(
Uri.parse((Platform.isAndroid)
? "market://details?id=cz.hernikplays.opencanteen"
: "https://apps.apple.com/cz/app/opencanteen/id1621124445"),
mode: LaunchMode.externalApplication); mode: LaunchMode.externalApplication);
} else if (value == Languages.of(context)!.reportBugs) { } else if (value == Languages.of(context)!.reportBugs) {
launchUrl(Uri.parse("https://forms.gle/jKN7QeFJwpaApSbC8"), launchUrl(Uri.parse("https://forms.gle/jKN7QeFJwpaApSbC8"),
@ -357,28 +366,29 @@ class _JidelnicekViewState extends State<JidelnicekView> {
"${Languages.of(context)!.copyright}\n${Languages.of(context)!.license}", "${Languages.of(context)!.copyright}\n${Languages.of(context)!.license}",
applicationVersion: packageInfo.version, applicationVersion: packageInfo.version,
children: [ children: [
TextButton( PlatformButton(
onPressed: (() => launchUrl( onPressed: (() => launchUrl(
Uri.parse("https://git.mnau.xyz/hernik/opencanteen"))), Uri.parse("https://git.mnau.xyz/hernik/opencanteen"),
child: Text(Languages.of(context)!.source)) mode: LaunchMode.externalApplication)),
text: Languages.of(context)!.source,
)
]); ]);
} else if (value == Languages.of(context)!.settings) { } else if (value == Languages.of(context)!.settings) {
Navigator.push( Navigator.push(context, platformRouter((c) => const AndroidNastaveni()));
context, MaterialPageRoute(builder: (c) => const AndroidNastaveni()));
} }
} }
void nactiNastaveni() async { void loadSettings() async {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
_skipWeekend = prefs.getBool("skip") ?? false; _skipWeekend = prefs.getBool("skip") ?? false;
if (!mounted) return; if (!mounted) return;
kontrolaTyden(context); checkWeek(context);
} }
void ulozitDoOffline() async { void saveOffline() async {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
if (prefs.getBool("offline") ?? false) { if (prefs.getBool("offline") ?? false) {
// vyčistit offline // clear offline storage
Directory appDocDir = await getApplicationDocumentsDirectory(); Directory appDocDir = await getApplicationDocumentsDirectory();
for (var f in appDocDir.listSync()) { for (var f in appDocDir.listSync()) {
if (f.path.contains("jidelnicek")) { if (f.path.contains("jidelnicek")) {
@ -386,11 +396,11 @@ class _JidelnicekViewState extends State<JidelnicekView> {
} }
} }
// uložit *pocet* jídelníčků pro offline použití // save X meal lists
var pocet = prefs.getInt("offline_pocet") ?? 1; var pocet = prefs.getInt("offline_pocet") ?? 1;
if (pocet > 7) pocet = 7; if (pocet > 7) pocet = 7;
for (var i = 0; i < pocet; i++) { for (var i = 0; i < pocet; i++) {
var d = den.add(Duration(days: i)); var d = day.add(Duration(days: i));
Jidelnicek? j; Jidelnicek? j;
try { try {
j = await widget.canteen.jidelnicekDen(den: d); j = await widget.canteen.jidelnicekDen(den: d);
@ -427,9 +437,9 @@ class _JidelnicekViewState extends State<JidelnicekView> {
@override @override
void didChangeDependencies() { void didChangeDependencies() {
super.didChangeDependencies(); super.didChangeDependencies();
nactiNastaveni(); loadSettings();
ulozitDoOffline(); saveOffline();
nactiJidlo(); loadMeals();
} }
@override @override
@ -440,7 +450,7 @@ class _JidelnicekViewState extends State<JidelnicekView> {
title: Text(Languages.of(context)!.menu), title: Text(Languages.of(context)!.menu),
actions: [ actions: [
PopupMenuButton( PopupMenuButton(
onSelected: ((String value) => kliknuti(value, context)), onSelected: ((String value) => click(value, context)),
itemBuilder: (BuildContext context) { itemBuilder: (BuildContext context) {
return { return {
Languages.of(context)!.reportBugs, Languages.of(context)!.reportBugs,
@ -459,62 +469,71 @@ class _JidelnicekViewState extends State<JidelnicekView> {
], ],
), ),
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: nactiJidlo, onRefresh: loadMeals,
child: Center( child: Center(
child: SizedBox( child: SizedBox(
width: MediaQuery.of(context).size.width - 50, width: MediaQuery.of(context).size.width - 50,
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 10), const SizedBox(height: 10),
Text("${Languages.of(context)!.balance}$kredit"), Text("${Languages.of(context)!.balance}$balance"),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Row(
IconButton( mainAxisAlignment: MainAxisAlignment.center,
onPressed: () { children: [
setState(() { IconButton(
den = den.subtract(const Duration(days: 1)); onPressed: () {
if (den.weekday == 7 && _skipWeekend) { setState(() {
den = den.subtract(const Duration(days: 2)); day = day.subtract(const Duration(days: 1));
} if (day.weekday == 7 && _skipWeekend) {
nactiJidlo(); day = day.subtract(const Duration(days: 2));
}); }
}, loadMeals();
icon: const Icon(Icons.arrow_left)), });
TextButton( },
icon: const Icon(Icons.arrow_left)),
PlatformButton(
onPressed: () async { onPressed: () async {
var datePicked = await showDatePicker( var datePicked = await showDatePicker(
context: context, context: context,
initialDate: den, initialDate: day,
currentDate: den, currentDate: day,
firstDate: DateTime(2019, 1, 1), firstDate: DateTime(2019, 1, 1),
lastDate: DateTime(den.year + 1, 12, 31), lastDate: DateTime(day.year + 1, 12, 31),
locale: Localizations.localeOf(context)); locale: Localizations.localeOf(context));
if (datePicked == null) return; if (datePicked == null) return;
setState(() { setState(() {
den = datePicked; day = datePicked;
nactiJidlo(); loadMeals();
}); });
}, },
child: Text( text: "${day.day}. ${day.month}. ${day.year} - $dayOWeek",
"${den.day}. ${den.month}. ${den.year} - $denTydne")), ),
IconButton( IconButton(
onPressed: () { onPressed: () {
setState(() { setState(() {
den = den.add(const Duration(days: 1)); day = day.add(const Duration(days: 1));
if (den.weekday == 6 && _skipWeekend) { if (day.weekday == 6 && _skipWeekend) {
den = den.add(const Duration(days: 2)); day = day.add(const Duration(days: 2));
} }
nactiJidlo(); loadMeals();
}); });
}, },
icon: const Icon(Icons.arrow_right), icon: const Icon(Icons.arrow_right),
), ),
IconButton( Tooltip(
onPressed: () => setState(() { message: Languages.of(context)!.todayTooltip,
den = DateTime.now(); child: IconButton(
nactiJidlo(); onPressed: () => setState(
}), () {
icon: const Icon(Icons.today)) day = DateTime.now();
]), loadMeals();
},
),
icon: const Icon(Icons.today),
),
)
],
),
SingleChildScrollView( SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
child: GestureDetector( child: GestureDetector(
@ -524,25 +543,27 @@ class _JidelnicekViewState extends State<JidelnicekView> {
.onPrimary .onPrimary
.withOpacity(0), .withOpacity(0),
height: MediaQuery.of(context).size.height / 1.3, height: MediaQuery.of(context).size.height / 1.3,
child: Column(children: obsah), child: Column(children: content),
), ),
onHorizontalDragEnd: (details) { onHorizontalDragEnd: (details) {
if (details.primaryVelocity?.compareTo(0) == -1) { if (details.primaryVelocity?.compareTo(0) == -1) {
setState(() { setState(() {
den = den.add(const Duration(days: 1)); day = day.add(const Duration(days: 1));
if (den.weekday == 6 && _skipWeekend) { if (day.weekday == 6 && _skipWeekend) {
den = den.add(const Duration(days: 2)); day = day.add(const Duration(days: 2));
} }
nactiJidlo(); loadMeals();
}); });
} else { } else {
setState(() { setState(
den = den.subtract(const Duration(days: 1)); () {
if (den.weekday == 7 && _skipWeekend) { day = day.subtract(const Duration(days: 1));
den = den.subtract(const Duration(days: 2)); if (day.weekday == 7 && _skipWeekend) {
} day = day.subtract(const Duration(days: 2));
nactiJidlo(); }
}); loadMeals();
},
);
} }
}, },
), ),

View file

@ -1,16 +1,17 @@
import 'dart:io';
import 'package:canteenlib/canteenlib.dart'; import 'package:canteenlib/canteenlib.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:opencanteen/okna/welcome.dart'; import 'package:opencanteen/okna/welcome.dart';
import 'package:opencanteen/pw/platformbutton.dart';
import 'package:opencanteen/pw/platformfield.dart';
import '../../lang/lang.dart'; import '../../lang/lang.dart';
import '../../loginmanager.dart'; import '../../loginmanager.dart';
import '../../main.dart'; import '../../main.dart';
import '../../util.dart'; import '../../util.dart';
import '../pw/platformswitch.dart';
import 'jidelnicek.dart'; import 'jidelnicek.dart';
import 'offline_jidelnicek.dart'; import 'offline_jidelnicek.dart';
@ -32,14 +33,14 @@ class _LoginPageState extends State<LoginPage> {
void initState() { void initState() {
super.initState(); super.initState();
LoginManager.getDetails().then((r) async { LoginManager.getDetails().then((r) async {
// žádat o oprávnění na android // request android notification access
flutterLocalNotificationsPlugin flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation< .resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>() AndroidFlutterLocalNotificationsPlugin>()
?.requestPermission(); ?.requestPermission();
if (r != null) { if (r != null) {
// Automaticky přihlásit // Autologin
showDialog( showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
@ -74,36 +75,26 @@ class _LoginPageState extends State<LoginPage> {
if (odsouhlasil == null || odsouhlasil != "ano") { if (odsouhlasil == null || odsouhlasil != "ano") {
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(
context, context,
MaterialPageRoute( platformRouter(
builder: (c) => WelcomePage(canteen: canteen), (c) => WelcomePage(canteen: canteen),
), ),
(route) => false); (route) => false);
} else { } else {
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(
context, context,
MaterialPageRoute( platformRouter(
builder: (context) => JidelnicekView(canteen: canteen), (context) => MealView(canteen: canteen),
), ),
(route) => false); (route) => false);
} }
} on PlatformException { } on PlatformException {
if (!mounted) return; if (!mounted) return;
Navigator.of(context).pop(); Navigator.of(context).pop();
ScaffoldMessenger.of(context).hideCurrentSnackBar(); showInfo(context, Languages.of(context)!.corrupted);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(Languages.of(context)!.corrupted),
),
);
} catch (_) { } catch (_) {
if (!mounted) return; if (!mounted) return;
Navigator.of(context).pop(); Navigator.of(context).pop();
ScaffoldMessenger.of(context).hideCurrentSnackBar(); showInfo(context, Languages.of(context)!.errorContacting);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(Languages.of(context)!.errorContacting),
),
);
goOffline(); goOffline();
} }
} }
@ -113,169 +104,150 @@ class _LoginPageState extends State<LoginPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(Languages.of(context)!.logIn), title: Text(Languages.of(context)!.logIn),
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
), ),
body: Center( body: Center(
child: SingleChildScrollView( child: SingleChildScrollView(
child: SizedBox( child: SizedBox(
width: MediaQuery.of(context).size.width - 50, width: MediaQuery.of(context).size.width - 50,
child: Column( child: Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[ children: <Widget>[
Text( Text(
Languages.of(context)!.appName, Languages.of(context)!.appName,
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: const TextStyle( style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 40), fontWeight: FontWeight.bold, fontSize: 40),
),
Text(
Languages.of(context)!.logIn,
textAlign: TextAlign.center,
),
PlatformField(
controller: userControl,
autofillHints: const [AutofillHints.username],
labelText: Languages.of(context)!.username,
),
PlatformField(
autofillHints: const [AutofillHints.password],
labelText: Languages.of(context)!.password,
controller: passControl,
obscureText: true,
),
const SizedBox(
height: 10,
),
DropdownButton(
isExpanded: true,
value: dropdownUrl,
items: instance.map<DropdownMenuItem<String>>((e) {
return DropdownMenuItem<String>(
value: e["url"],
child: Text(e["name"]!),
);
}).toList(),
onChanged: (String? value) {
setState(() {
if (value == "") {
_showUrl = true;
} else {
_showUrl = false;
}
dropdownUrl = value!;
});
},
),
AnimatedOpacity(
opacity: _showUrl ? 1.0 : 0.0,
duration: const Duration(milliseconds: 300),
child: PlatformField(
autofillHints: const [AutofillHints.url],
labelText: Languages.of(context)!.iCanteenUrl,
keyboardType: TextInputType.url,
controller: canteenControl,
), ),
Text( ),
Languages.of(context)!.logIn, Row(mainAxisAlignment: MainAxisAlignment.center, children: [
textAlign: TextAlign.center, PlatformSwitch(
), value: rememberMe,
TextField( onChanged: (value) {
controller: userControl,
autofillHints: const [AutofillHints.username],
decoration: InputDecoration(
labelText: Languages.of(context)!.username),
),
TextField(
autofillHints: const [AutofillHints.password],
decoration: InputDecoration(
labelText: Languages.of(context)!.password),
controller: passControl,
obscureText: true,
),
const SizedBox(
height: 10,
),
DropdownButton(
isExpanded: true,
value: dropdownUrl,
items: instance.map<DropdownMenuItem<String>>((e) {
return DropdownMenuItem<String>(
value: e["url"],
child: Text(e["name"]!),
);
}).toList(),
onChanged: (String? value) {
setState(() { setState(() {
if (value == "") { rememberMe = value;
_showUrl = true;
} else {
_showUrl = false;
}
dropdownUrl = value!;
}); });
}, },
), ),
AnimatedOpacity( Text(Languages.of(context)!.rememberMe)
opacity: _showUrl ? 1.0 : 0.0, ]),
duration: const Duration(milliseconds: 300), PlatformButton(
child: TextField( onPressed: () async {
autofillHints: const [AutofillHints.url], var canteenUrl = (dropdownUrl == "")
decoration: InputDecoration( ? canteenControl.text
labelText: Languages.of(context)!.iCanteenUrl), : dropdownUrl;
keyboardType: TextInputType.url, if (!canteenUrl.startsWith("https://") &&
controller: canteenControl, !canteenUrl.startsWith("http://")) {
), canteenUrl = "https://$canteenUrl";
), }
Row(mainAxisAlignment: MainAxisAlignment.center, children: [ var canteen = Canteen(canteenUrl);
Switch( try {
value: rememberMe, var l = await canteen.login(
onChanged: (value) { userControl.text, passControl.text);
setState(() { if (!l) {
rememberMe = value; if (!mounted) return;
}); showInfo(context, Languages.of(context)!.loginFailed);
}), return;
Text(Languages.of(context)!.rememberMe)
]),
TextButton(
onPressed: () async {
var canteenUrl = (dropdownUrl == "")
? canteenControl.text
: dropdownUrl;
if (!canteenUrl.startsWith("https://") &&
!canteenUrl.startsWith("http://")) {
canteenUrl = "https://$canteenUrl";
} }
var canteen = Canteen(canteenUrl); if (rememberMe) {
try { LoginManager.setDetails(
var l = await canteen.login( userControl.text, passControl.text, canteenUrl);
userControl.text, passControl.text); }
if (!l) { // souhlas
if (!mounted) return; const storage = FlutterSecureStorage();
ScaffoldMessenger.of(context).hideCurrentSnackBar(); var odsouhlasil = await storage.read(key: "oc_souhlas");
ScaffoldMessenger.of(context).showSnackBar( if (!mounted) return;
SnackBar( if (odsouhlasil == null || odsouhlasil != "ano") {
content: Navigator.pushAndRemoveUntil(
Text(Languages.of(context)!.loginFailed), context,
platformRouter(
(context) => WelcomePage(
canteen: canteen,
),
), ),
); (route) => false);
return; } else {
} Navigator.pushAndRemoveUntil(
if (rememberMe) { context,
LoginManager.setDetails( platformRouter(
userControl.text, passControl.text, canteenUrl); (context) => MealView(
} canteen: canteen,
// souhlas ),
const storage = FlutterSecureStorage(); ),
var odsouhlasil = (route) => false);
await storage.read(key: "oc_souhlas");
if (!mounted) return;
if (odsouhlasil == null || odsouhlasil != "ano") {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (c) => WelcomePage(
canteen: canteen,
)),
(route) => false);
} else {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => JidelnicekView(
canteen: canteen,
)),
(route) => false);
}
} on PlatformException {
if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(Languages.of(context)!.corrupted),
),
);
} on Exception catch (_) {
if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text(Languages.of(context)!.errorContacting),
),
);
goOffline();
} }
}, } on PlatformException {
child: Text(Languages.of(context)!.logIn)), if (!mounted) return;
], showInfo(context, Languages.of(context)!.corrupted);
), } on Exception catch (_) {
if (!mounted) return;
showInfo(
context, Languages.of(context)!.errorContacting);
//goOffline();
}
},
text: Languages.of(context)!.logIn),
],
), ),
), ),
)); ),
),
);
} }
/// Získá offline soubor a zobrazí údaje /// Switch to offline view
void goOffline() async { void goOffline() async {
if (!mounted) return; if (!mounted) return;
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(context,
context, platformRouter((context) => const OfflineMealView()), (route) => false);
MaterialPageRoute(
builder: ((context) => const AndroidOfflineJidelnicek())),
(route) => false);
} }
} }

View file

@ -5,6 +5,10 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart'; import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:opencanteen/pw/platformbutton.dart';
import 'package:opencanteen/pw/platformdialog.dart';
import 'package:opencanteen/pw/platformfield.dart';
import 'package:opencanteen/pw/platformswitch.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:timezone/timezone.dart' as tz; import 'package:timezone/timezone.dart' as tz;
@ -22,45 +26,48 @@ class AndroidNastaveni extends StatefulWidget {
} }
class _AndroidNastaveniState extends State<AndroidNastaveni> { class _AndroidNastaveniState extends State<AndroidNastaveni> {
bool _ukladatOffline = false; bool _saveOffline = false;
bool _preskakovatVikend = false; bool _skipWeekend = false;
bool _kontrolovatTyden = false; bool _checkWeek = false;
bool _oznameniObed = false; bool _notifyMeal = false;
bool _zapamatovany = false; bool _remember = false;
TimeOfDay _oznameniCas = TimeOfDay.now(); TimeOfDay _notifTime = TimeOfDay.now();
final TextEditingController _countController = final TextEditingController _countController =
TextEditingController(text: "1"); TextEditingController(text: "1");
SharedPreferences? preferences; SharedPreferences? preferences;
void najitNastaveni() async {
void loadSettings() async {
preferences = await SharedPreferences.getInstance(); preferences = await SharedPreferences.getInstance();
_zapamatovany = await LoginManager.zapamatovat(); _remember = await LoginManager.rememberme();
setState(() { setState(
_ukladatOffline = preferences!.getBool("offline") ?? false; () {
_preskakovatVikend = preferences!.getBool("skip") ?? false; _saveOffline = preferences!.getBool("offline") ?? false;
_kontrolovatTyden = preferences!.getBool("tyden") ?? false; _skipWeekend = preferences!.getBool("skip") ?? false;
_oznameniObed = preferences!.getBool("oznamit") ?? false; _checkWeek = preferences!.getBool("tyden") ?? false;
_countController.text = _notifyMeal = preferences!.getBool("oznamit") ?? false;
(preferences!.getInt("offline_pocet") ?? 1).toString(); _countController.text =
var casStr = preferences!.getString("oznameni_cas"); (preferences!.getInt("offline_pocet") ?? 1).toString();
if (casStr == null) { var casStr = preferences!.getString("oznameni_cas");
var now = DateTime.now(); if (casStr == null) {
_oznameniCas = TimeOfDay.fromDateTime( var now = DateTime.now();
DateTime.now().add(const Duration(hours: 1))); _notifTime = TimeOfDay.fromDateTime(
preferences!.setString("oznameni_cas", now.toString()); DateTime.now().add(const Duration(hours: 1)));
} else { preferences!.setString("oznameni_cas", now.toString());
_oznameniCas = TimeOfDay.fromDateTime(DateTime.parse(casStr)); } else {
} _notifTime = TimeOfDay.fromDateTime(DateTime.parse(casStr));
}); }
},
);
} }
void zmenitNastaveni(String key, bool value) async { void changeSetting(String key, bool value) async {
preferences!.setBool(key, value); preferences!.setBool(key, value);
} }
@override @override
void initState() { void initState() {
super.initState(); super.initState();
najitNastaveni(); loadSettings();
} }
@override @override
@ -70,168 +77,168 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
title: Text(Languages.of(context)!.settings), title: Text(Languages.of(context)!.settings),
), ),
body: Center( body: Center(
child: SizedBox( child: SizedBox(
width: MediaQuery.of(context).size.width / 1.1, width: MediaQuery.of(context).size.width / 1.1,
child: Column( child: Column(
children: [ children: [
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text(Languages.of(context)!.saveOffline), Text(Languages.of(context)!.saveOffline),
Switch( PlatformSwitch(
value: _ukladatOffline, value: _saveOffline,
activeColor: Colors.purple,
onChanged: (value) { onChanged: (value) {
setState(() { setState(() {
_ukladatOffline = value; _saveOffline = value;
cistit(value); clear(value);
zmenitNastaveni("offline", value); changeSetting("offline", value);
}); });
})
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(Languages.of(context)!.saveCount),
SizedBox(
width: 35,
child: TextField(
controller: _countController,
enabled: _ukladatOffline,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (c) {
var cislo = int.tryParse(c);
if (cislo != null) {
preferences!.setInt("offline_pocet", cislo);
}
}, },
), )
) ],
], ),
), Row(
Row( mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
children: [ Text(Languages.of(context)!.saveCount),
Text(Languages.of(context)!.skipWeekend), SizedBox(
Switch( width: 35,
activeColor: Colors.purple, child: PlatformField(
value: _preskakovatVikend, controller: _countController,
enabled: _saveOffline,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (c) {
var cislo = int.tryParse(c);
if (cislo != null) {
preferences!.setInt("offline_pocet", cislo);
}
},
),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(Languages.of(context)!.skipWeekend),
PlatformSwitch(
value: _skipWeekend,
onChanged: (value) { onChanged: (value) {
setState(() { setState(
_preskakovatVikend = value; () {
zmenitNastaveni("skip", value); _skipWeekend = value;
}); changeSetting("skip", value);
}) },
], );
), },
Row( )
mainAxisAlignment: MainAxisAlignment.spaceBetween, ],
children: [ ),
Flexible(child: Text(Languages.of(context)!.checkOrdered)), Row(
Switch( mainAxisAlignment: MainAxisAlignment.spaceBetween,
activeColor: Colors.purple, children: [
value: _kontrolovatTyden, Flexible(child: Text(Languages.of(context)!.checkOrdered)),
PlatformSwitch(
value: _checkWeek,
onChanged: (value) { onChanged: (value) {
setState(() { setState(
_kontrolovatTyden = value; () {
zmenitNastaveni("tyden", value); _checkWeek = value;
}); changeSetting("tyden", value);
}) },
], );
), },
Row( )
mainAxisAlignment: MainAxisAlignment.spaceBetween, ],
children: [ ),
Flexible(child: Text(Languages.of(context)!.notifyLunch)), Row(
Switch( mainAxisAlignment: MainAxisAlignment.spaceBetween,
activeColor: Colors.purple, children: [
value: _oznameniObed, Flexible(child: Text(Languages.of(context)!.notifyLunch)),
thumbColor: (!_zapamatovany PlatformSwitch(
? MaterialStateProperty.all(Colors.grey) value: _notifyMeal,
: null), thumbColor: (!_remember ? Colors.grey : null),
onChanged: (value) { onChanged: (value) {
if (!_zapamatovany) { if (!_remember) {
showDialog( showDialog(
context: context, context: context,
builder: (bc) => AlertDialog( builder: (bc) => PlatformDialog(
title: Text(Languages.of(context)!.error), title: Languages.of(context)!.error,
content: content: Languages.of(context)!.needRemember,
Text(Languages.of(context)!.needRemember), actions: [
actions: [ PlatformButton(
TextButton( text: Languages.of(context)!.ok,
child: Text(Languages.of(context)!.ok), onPressed: () {
onPressed: () { Navigator.of(context).pop();
Navigator.of(context).pop(); },
}, )
) ],
], ),
)); );
} else { } else {
setState(() { setState(() {
_oznameniObed = value; _notifyMeal = value;
if (_oznameniObed) { if (_notifyMeal) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => PlatformDialog(
title: title: Languages.of(context)!.warning,
Text(Languages.of(context)!.warning), content: Languages.of(context)!.notifyWarning,
content: Text( actions: [
Languages.of(context)!.notifyWarning), PlatformButton(
actions: [ text: Languages.of(context)!.ok,
TextButton( onPressed: () {
child: Navigator.of(context).pop();
Text(Languages.of(context)!.ok), },
onPressed: () { )
Navigator.of(context).pop(); ],
}, ),
) );
], createNotif(timeToDate(_notifTime));
));
vytvoritOznameni(casNaDate(_oznameniCas));
} }
zmenitNastaveni("oznamit", value); changeSetting("oznamit", value);
}); });
} }
}) },
], )
), ],
Text(Languages.of(context)!.notifyAt),
TextButton(
onPressed: () async {
if (_oznameniObed) {
var cas = await showTimePicker(
context: context, initialTime: _oznameniCas);
if (cas != null) {
var prefs = await SharedPreferences.getInstance();
prefs.setString("oznameni_cas",
casNaDate(cas).toString()); // aktualizovat vybraný čas
var den = casNaDate(cas);
debugPrint(den.isAfter(DateTime.now()).toString());
if (den.isAfter(DateTime.now())) {
// znovu vytvořit oznámení POUZE když je čas v budoucnosti
vytvoritOznameni(den);
}
}
setState(() {
_oznameniCas = cas ?? _oznameniCas;
});
}
},
child: Text(
"${(_oznameniCas.hour < 10 ? "0" : "") + _oznameniCas.hour.toString()}:${(_oznameniCas.minute < 10 ? "0" : "") + _oznameniCas.minute.toString()}",
style: TextStyle(
color: (!_oznameniObed) ? Colors.grey : Colors.purple),
), ),
), Text(Languages.of(context)!.notifyAt),
], PlatformButton(
onPressed: () async {
if (_notifyMeal) {
var cas = await showTimePicker(
context: context, initialTime: _notifTime);
if (cas != null) {
var prefs = await SharedPreferences.getInstance();
prefs.setString(
"oznameni_cas",
timeToDate(cas)
.toString()); // aktualizovat vybraný čas
var den = timeToDate(cas);
debugPrint(den.isAfter(DateTime.now()).toString());
if (den.isAfter(DateTime.now())) {
// znovu vytvořit oznámení POUZE když je čas v budoucnosti
createNotif(den);
}
}
setState(() {
_notifTime = cas ?? _notifTime;
});
}
},
text:
"${(_notifTime.hour < 10 ? "0" : "") + _notifTime.hour.toString()}:${(_notifTime.minute < 10 ? "0" : "") + _notifTime.minute.toString()}",
),
],
),
), ),
)), ),
); );
} }
void cistit(bool value) async { void clear(bool value) async {
if (!value) { if (!value) {
Directory appDocDir = await getApplicationDocumentsDirectory(); Directory appDocDir = await getApplicationDocumentsDirectory();
for (var f in appDocDir.listSync()) { for (var f in appDocDir.listSync()) {
@ -243,11 +250,10 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
} }
} }
void vytvoritOznameni(DateTime den) async { void createNotif(DateTime den) async {
await flutterLocalNotificationsPlugin.cancelAll(); await flutterLocalNotificationsPlugin.cancelAll();
var d = await LoginManager.getDetails(); // získat údaje var d = await LoginManager.getDetails(); // grab details
if (d != null) { if (d != null) {
// Nové oznámení
var c = Canteen(d["url"]!); var c = Canteen(d["url"]!);
if (await c.login(d["user"]!, d["pass"]!)) { if (await c.login(d["user"]!, d["pass"]!)) {
var jidla = await c.jidelnicekDen(); var jidla = await c.jidelnicekDen();
@ -264,7 +270,7 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
tz.getLocation(await FlutterNativeTimezone.getLocalTimezone()); tz.getLocation(await FlutterNativeTimezone.getLocalTimezone());
if (!mounted) return; if (!mounted) return;
await flutterLocalNotificationsPlugin.zonedSchedule( await flutterLocalNotificationsPlugin.zonedSchedule(
// Vytvoří nové oznámení pro daný čas a datum // schedules a notification
0, 0,
Languages.of(context)!.lunchNotif, Languages.of(context)!.lunchNotif,
"${jidlo.varianta} - ${jidlo.nazev}", "${jidlo.varianta} - ${jidlo.nazev}",
@ -274,7 +280,7 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
uiLocalNotificationDateInterpretation: uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime); UILocalNotificationDateInterpretation.absoluteTime);
} on StateError catch (_) { } on StateError catch (_) {
// nenalezeno // no meal found
} }
} }
} }

View file

@ -4,6 +4,7 @@ import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:opencanteen/okna/login.dart'; import 'package:opencanteen/okna/login.dart';
import 'package:opencanteen/pw/platformbutton.dart';
import 'package:opencanteen/util.dart'; import 'package:opencanteen/util.dart';
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
@ -12,90 +13,90 @@ import 'package:url_launcher/url_launcher.dart';
import '../../lang/lang.dart'; import '../../lang/lang.dart';
class AndroidOfflineJidelnicek extends StatefulWidget { class OfflineMealView extends StatefulWidget {
const AndroidOfflineJidelnicek({Key? key}) : super(key: key); const OfflineMealView({Key? key}) : super(key: key);
@override @override
State<AndroidOfflineJidelnicek> createState() => State<OfflineMealView> createState() => _OfflineMealViewState();
_AndroidOfflineJidelnicekState();
} }
class _AndroidOfflineJidelnicekState extends State<AndroidOfflineJidelnicek> { class _OfflineMealViewState extends State<OfflineMealView> {
List<Widget> obsah = [const CircularProgressIndicator()]; List<Widget> content = [const CircularProgressIndicator()]; // view content
var _skipWeekend = false; var _skipWeekend = false; // skip weekend setting
DateTime den = DateTime.now(); DateTime currentDay = DateTime.now(); // the day we are supposed to show
String denTydne = ""; String dayOWeek = ""; // the name of the day (to show to user)
List<List<OfflineJidlo>> data = []; List<List<OfflineMeal>> data = []; // meal data
var jidloIndex = 0; var mealIndex = 0; // index of the currently shown day
void nactiZeSouboru() async { /// Loads the offline data from local storage
void loadFromFile() async {
Directory appDocDir = await getApplicationDocumentsDirectory(); Directory appDocDir = await getApplicationDocumentsDirectory();
for (var f in appDocDir.listSync()) { for (var f in appDocDir.listSync()) {
if (f.path.contains("jidelnicek")) { if (f.path.contains("jidelnicek")) {
var soubor = File(f.path); var soubor = File(f.path);
var input = await soubor.readAsString(); var input = await soubor.readAsString();
var r = jsonDecode(input); var r = jsonDecode(input);
List<OfflineJidlo> jidla = []; List<OfflineMeal> jidla = [];
for (var j in r) { for (var j in r) {
jidla.add(OfflineJidlo( jidla.add(OfflineMeal(
nazev: j["nazev"], name: j["nazev"],
varianta: j["varianta"], variant: j["varianta"],
objednano: j["objednano"], ordered: j["objednano"],
cena: j["cena"], price: j["cena"],
naBurze: j["naBurze"], onExchange: j["naBurze"],
den: DateTime.parse(j["den"]))); day: DateTime.parse(j["den"])));
} }
data.add(jidla); data.add(jidla);
} }
} }
nactiJidlo(); loadFood();
} }
Future<void> nactiJidlo() async { Future<void> loadFood() async {
var jidelnicek = data[jidloIndex]; var jidelnicek = data[mealIndex];
den = jidelnicek[0].den; currentDay = jidelnicek[0].day;
switch (den.weekday) { switch (currentDay.weekday) {
case 2: case 2:
denTydne = Languages.of(context)!.tuesday; dayOWeek = Languages.of(context)!.tuesday;
break; break;
case 3: case 3:
denTydne = Languages.of(context)!.wednesday; dayOWeek = Languages.of(context)!.wednesday;
break; break;
case 4: case 4:
denTydne = Languages.of(context)!.thursday; dayOWeek = Languages.of(context)!.thursday;
break; break;
case 5: case 5:
denTydne = Languages.of(context)!.friday; dayOWeek = Languages.of(context)!.friday;
break; break;
case 6: case 6:
denTydne = Languages.of(context)!.saturday; dayOWeek = Languages.of(context)!.saturday;
break; break;
case 7: case 7:
denTydne = Languages.of(context)!.sunday; dayOWeek = Languages.of(context)!.sunday;
break; break;
default: default:
denTydne = Languages.of(context)!.monday; dayOWeek = Languages.of(context)!.monday;
} }
obsah = []; content = [];
for (OfflineJidlo j in jidelnicek) { for (OfflineMeal j in jidelnicek) {
obsah.add( content.add(
Padding( Padding(
padding: const EdgeInsets.only(top: 15), padding: const EdgeInsets.only(top: 15),
child: InkWell( child: InkWell(
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text(j.varianta), Text(j.variant),
const SizedBox(width: 10), const SizedBox(width: 10),
Flexible( Flexible(
child: Text( child: Text(
j.nazev, j.name,
), ),
), ),
Text((j.naBurze) Text((j.onExchange)
? Languages.of(context)!.inExchange ? Languages.of(context)!.inExchange
: "${j.cena}"), : "${j.price}"),
Checkbox( Checkbox(
value: j.objednano, value: j.ordered,
fillColor: MaterialStateProperty.all(Colors.grey), fillColor: MaterialStateProperty.all(Colors.grey),
onChanged: (v) async { onChanged: (v) async {
return; return;
@ -110,14 +111,17 @@ class _AndroidOfflineJidelnicekState extends State<AndroidOfflineJidelnicek> {
setState(() {}); setState(() {});
} }
void kliknuti(String value, BuildContext context) async { void click(String value, BuildContext context) async {
if (value == Languages.of(context)!.signOut) { if (value == Languages.of(context)!.signOut) {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
storage.deleteAll(); storage.deleteAll();
Navigator.pushReplacement( Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => const LoginPage())); context, platformRouter((c) => const LoginPage()));
} else if (value == Languages.of(context)!.review) { } else if (value == Languages.of(context)!.review) {
launchUrl(Uri.parse("market://details?id=cz.hernikplays.opencanteen"), launchUrl(
Uri.parse((Platform.isAndroid)
? "market://details?id=cz.hernikplays.opencanteen"
: "https://apps.apple.com/cz/app/opencanteen/id1621124445"),
mode: LaunchMode.externalApplication); mode: LaunchMode.externalApplication);
} else if (value == Languages.of(context)!.reportBugs) { } else if (value == Languages.of(context)!.reportBugs) {
launchUrl(Uri.parse("https://forms.gle/jKN7QeFJwpaApSbC8"), launchUrl(Uri.parse("https://forms.gle/jKN7QeFJwpaApSbC8"),
@ -126,31 +130,33 @@ class _AndroidOfflineJidelnicekState extends State<AndroidOfflineJidelnicek> {
var packageInfo = await PackageInfo.fromPlatform(); var packageInfo = await PackageInfo.fromPlatform();
if (!mounted) return; if (!mounted) return;
showAboutDialog( showAboutDialog(
context: context, context: context,
applicationName: "OpenCanteen", applicationName: "OpenCanteen",
applicationLegalese: applicationLegalese:
"${Languages.of(context)!.copyright}\n${Languages.of(context)!.license}", "${Languages.of(context)!.copyright}\n${Languages.of(context)!.license}",
applicationVersion: packageInfo.version, applicationVersion: packageInfo.version,
children: [ children: [
TextButton( PlatformButton(
onPressed: (() => launchUrl( onPressed: (() => launchUrl(
Uri.parse("https://git.mnau.xyz/hernik/opencanteen"))), Uri.parse("https://git.mnau.xyz/hernik/opencanteen"))),
child: Text(Languages.of(context)!.source)) text: Languages.of(context)!.source,
]); )
],
);
} }
} }
@override @override
void didChangeDependencies() { void didChangeDependencies() {
super.didChangeDependencies(); super.didChangeDependencies();
nactiNastaveni(); loadSettings();
} }
void nactiNastaveni() async { void loadSettings() async {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
_skipWeekend = prefs.getBool("skip") ?? false; _skipWeekend = prefs.getBool("skip") ?? false;
if (!mounted) return; if (!mounted) return;
nactiZeSouboru(); loadFromFile();
} }
@override @override
@ -161,7 +167,7 @@ class _AndroidOfflineJidelnicekState extends State<AndroidOfflineJidelnicek> {
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
actions: [ actions: [
PopupMenuButton( PopupMenuButton(
onSelected: ((String value) => kliknuti(value, context)), onSelected: ((String value) => click(value, context)),
itemBuilder: (BuildContext context) { itemBuilder: (BuildContext context) {
return { return {
Languages.of(context)!.reportBugs, Languages.of(context)!.reportBugs,
@ -195,69 +201,69 @@ class _AndroidOfflineJidelnicekState extends State<AndroidOfflineJidelnicek> {
IconButton( IconButton(
onPressed: () { onPressed: () {
if (data.length <= 1) return; if (data.length <= 1) return;
obsah = [const CircularProgressIndicator()]; content = [const CircularProgressIndicator()];
setState(() { setState(() {
if (den.weekday == 1 && _skipWeekend) { if (currentDay.weekday == 1 && _skipWeekend) {
// pokud je pondělí a chceme přeskočit víkend // pokud je pondělí a chceme přeskočit víkend
if (jidloIndex - 2 >= 0) { if (mealIndex - 2 >= 0) {
jidloIndex -= data.length - 3; mealIndex -= data.length - 3;
} else { } else {
jidloIndex = data.length - 1; mealIndex = data.length - 1;
} }
} else if (jidloIndex == 0) { } else if (mealIndex == 0) {
jidloIndex = data.length - 1; mealIndex = data.length - 1;
} else { } else {
jidloIndex -= 1; mealIndex -= 1;
} }
nactiJidlo(); loadFood();
}); });
}, },
icon: const Icon(Icons.arrow_left)), icon: const Icon(Icons.arrow_left)),
TextButton( PlatformButton(
onPressed: () async {}, onPressed: () async {},
child: Text( text:
"${den.day}. ${den.month}. ${den.year} - $denTydne")), "${currentDay.day}. ${currentDay.month}. ${currentDay.year} - $dayOWeek"),
IconButton( IconButton(
onPressed: () { onPressed: () {
if (data.length <= 1) return; if (data.length <= 1) return;
obsah = [const CircularProgressIndicator()]; content = [const CircularProgressIndicator()];
setState(() { setState(() {
if (den.weekday == 5 && _skipWeekend) { if (currentDay.weekday == 5 && _skipWeekend) {
// pokud je pondělí a chceme přeskočit víkend // pokud je pondělí a chceme přeskočit víkend
if (jidloIndex + 2 <= data.length - 1) { if (mealIndex + 2 <= data.length - 1) {
jidloIndex += 2; mealIndex += 2;
} else { } else {
jidloIndex = 0; mealIndex = 0;
} }
} else if (jidloIndex == data.length) { } else if (mealIndex == data.length) {
jidloIndex = 0; mealIndex = 0;
} else { } else {
jidloIndex += 1; mealIndex += 1;
} }
nactiJidlo(); loadFood();
}); });
}, },
icon: const Icon(Icons.arrow_right), icon: const Icon(Icons.arrow_right),
), ),
IconButton( IconButton(
onPressed: () { onPressed: () {
jidloIndex = 0; mealIndex = 0;
}, },
icon: const Icon(Icons.today)) icon: const Icon(Icons.today))
]), ]),
SingleChildScrollView( SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
child: Column( child: Column(
children: obsah, children: content,
), ),
), ),
], ],
), ),
), ),
), ),
onRefresh: () => Navigator.pushReplacement(context, onRefresh: () => Navigator.pushReplacement(
MaterialPageRoute(builder: ((context) => const LoginPage()))), context, platformRouter((context) => const LoginPage())),
), ),
); );
} }

View file

@ -4,6 +4,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:introduction_screen/introduction_screen.dart'; import 'package:introduction_screen/introduction_screen.dart';
import 'package:opencanteen/lang/lang.dart'; import 'package:opencanteen/lang/lang.dart';
import 'package:opencanteen/okna/jidelnicek.dart'; import 'package:opencanteen/okna/jidelnicek.dart';
import 'package:opencanteen/util.dart';
class WelcomePage extends StatefulWidget { class WelcomePage extends StatefulWidget {
const WelcomePage({Key? key, required this.canteen}) : super(key: key); const WelcomePage({Key? key, required this.canteen}) : super(key: key);
@ -68,8 +69,7 @@ class _WelcomePageState extends State<WelcomePage> {
await storage.write(key: "oc_souhlas", value: "ano"); await storage.write(key: "oc_souhlas", value: "ano");
if (!mounted) return; if (!mounted) return;
Navigator.of(context).pushAndRemoveUntil( Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute( platformRouter((c) => MealView(canteen: widget.canteen)),
builder: (c) => JidelnicekView(canteen: widget.canteen)),
(route) => false); (route) => false);
}, },
), ),

View file

@ -0,0 +1,18 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:opencanteen/pw/platformwidget.dart';
class PlatformButton extends PlatformWidget<TextButton, CupertinoButton> {
final String text;
final void Function()? onPressed;
const PlatformButton(
{super.key, required this.text, required this.onPressed});
@override
TextButton createAndroidWidget(BuildContext context) =>
TextButton(onPressed: onPressed, child: Text(text));
@override
CupertinoButton createIosWidget(BuildContext context) =>
CupertinoButton(onPressed: onPressed, child: Text(text));
}

View file

@ -0,0 +1,30 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:opencanteen/pw/platformwidget.dart';
class PlatformDialog extends PlatformWidget<AlertDialog, CupertinoAlertDialog> {
final String title;
final String? content;
final List<Widget> actions;
const PlatformDialog(
{super.key, required this.title, this.content, this.actions = const []});
@override
AlertDialog createAndroidWidget(BuildContext context) => AlertDialog(
title: Text(title),
content: (content != null)
? SingleChildScrollView(child: Text(content!))
: null,
actions: actions,
);
@override
CupertinoAlertDialog createIosWidget(BuildContext context) =>
CupertinoAlertDialog(
title: Text(title),
content: (content != null)
? SingleChildScrollView(child: Text(content!))
: null,
actions: actions,
);
}

54
lib/pw/platformfield.dart Normal file
View file

@ -0,0 +1,54 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:opencanteen/pw/platformwidget.dart';
class PlatformField extends PlatformWidget<TextField, CupertinoTextField> {
final TextEditingController? controller;
final bool? enabled;
final bool obscureText;
final String? labelText;
final bool autocorrect;
final TextInputType? keyboardType;
final List<TextInputFormatter> inputFormatters;
final void Function(String)? onChanged;
final List<String>? autofillHints;
const PlatformField({
super.key,
this.controller,
this.enabled,
this.labelText,
this.obscureText = false,
this.autocorrect = false,
this.keyboardType,
this.inputFormatters = const [],
this.onChanged,
this.autofillHints,
});
@override
TextField createAndroidWidget(BuildContext context) => TextField(
controller: controller,
enabled: enabled,
obscureText: obscureText,
decoration: InputDecoration(labelText: labelText),
autocorrect: autocorrect,
keyboardType: keyboardType,
inputFormatters: inputFormatters,
onChanged: onChanged,
autofillHints: autofillHints,
);
@override
CupertinoTextField createIosWidget(BuildContext context) =>
CupertinoTextField(
controller: controller,
enabled: enabled,
obscureText: obscureText,
prefix: (labelText == null) ? null : Text(labelText!),
autocorrect: autocorrect,
keyboardType: keyboardType,
inputFormatters: inputFormatters,
onChanged: onChanged,
);
}

View file

@ -0,0 +1,28 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:opencanteen/pw/platformwidget.dart';
class PlatformSwitch extends PlatformWidget<Switch, CupertinoSwitch> {
final bool value;
final void Function(bool)? onChanged;
final Color? thumbColor;
const PlatformSwitch(
{super.key,
required this.value,
required this.onChanged,
this.thumbColor});
@override
Switch createAndroidWidget(BuildContext context) => Switch(
value: value,
onChanged: onChanged,
thumbColor: MaterialStateProperty.all(thumbColor),
);
@override
CupertinoSwitch createIosWidget(BuildContext context) => CupertinoSwitch(
value: value,
onChanged: onChanged,
thumbColor: thumbColor,
);
}

View file

@ -0,0 +1,22 @@
import 'dart:io';
import 'package:flutter/material.dart';
/// Abstract class used to create widgets for the respective platform UI library
abstract class PlatformWidget<A extends Widget, I extends Widget>
extends StatelessWidget {
const PlatformWidget({super.key});
@override
Widget build(BuildContext context) {
if (Platform.isAndroid) {
return createAndroidWidget(context);
} else {
return createIosWidget(context);
}
}
A createAndroidWidget(BuildContext context);
I createIosWidget(BuildContext context);
}

View file

@ -1,7 +1,9 @@
import 'dart:io'; import 'dart:io';
import 'package:canteenlib/canteenlib.dart'; import 'package:canteenlib/canteenlib.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:opencanteen/okna/burza.dart'; import 'package:opencanteen/okna/burza.dart';
import 'package:opencanteen/okna/jidelnicek.dart'; import 'package:opencanteen/okna/jidelnicek.dart';
import 'lang/lang.dart'; import 'lang/lang.dart';
@ -28,8 +30,7 @@ Drawer drawerGenerator(BuildContext context, Canteen canteen, int p) {
title: Text(Languages.of(context)!.exchange), title: Text(Languages.of(context)!.exchange),
onTap: () => Navigator.push( onTap: () => Navigator.push(
context, context,
MaterialPageRoute( platformRouter((context) => BurzaView(canteen: canteen)),
builder: (context) => BurzaView(canteen: canteen)),
), ),
), ),
], ],
@ -49,8 +50,7 @@ Drawer drawerGenerator(BuildContext context, Canteen canteen, int p) {
title: Text(Languages.of(context)!.home), title: Text(Languages.of(context)!.home),
onTap: () => Navigator.push( onTap: () => Navigator.push(
context, context,
MaterialPageRoute( platformRouter((c) => MealView(canteen: canteen)),
builder: (c) => JidelnicekView(canteen: canteen)),
), ),
), ),
ListTile( ListTile(
@ -66,31 +66,60 @@ Drawer drawerGenerator(BuildContext context, Canteen canteen, int p) {
return drawer; return drawer;
} }
class OfflineJidlo { class OfflineMeal {
String nazev; String name;
String varianta; String variant;
bool objednano; bool ordered;
double cena; double price;
bool naBurze; bool onExchange;
DateTime den; DateTime day;
OfflineJidlo( OfflineMeal(
{required this.nazev, {required this.name,
required this.varianta, required this.variant,
required this.objednano, required this.ordered,
required this.cena, required this.price,
required this.naBurze, required this.onExchange,
required this.den}); required this.day});
} }
/// Vytvoří [DateTime] z [TimeOfDay] /// Parses [DateTime] from [TimeOfDay]
DateTime casNaDate(TimeOfDay c) { DateTime timeToDate(TimeOfDay c) {
var now = DateTime.now(); var now = DateTime.now();
return DateTime.parse( return DateTime.parse(
"${now.year}-${(now.month < 10 ? "0" : "") + now.month.toString()}-${(now.day < 10 ? "0" : "") + now.day.toString()} ${(c.hour < 10 ? "0" : "") + c.hour.toString()}:${(c.minute < 10 ? "0" : "") + c.minute.toString()}:00"); "${now.year}-${(now.month < 10 ? "0" : "") + now.month.toString()}-${(now.day < 10 ? "0" : "") + now.day.toString()} ${(c.hour < 10 ? "0" : "") + c.hour.toString()}:${(c.minute < 10 ? "0" : "") + c.minute.toString()}:00");
} }
/// List of instances to be used in the dropdown menu
List<Map<String, String>> instance = [ List<Map<String, String>> instance = [
{"name": "SŠTE Brno, Olomoucká", "url": "https://stravovani.sstebrno.cz"}, {"name": "SŠTE Brno, Olomoucká", "url": "https://stravovani.sstebrno.cz"},
{"name": "Jiné", "url": ""} {"name": "Jiné", "url": ""}
]; ];
/// Used to display either a toas or a snackbar
void showInfo(BuildContext context, String message) {
if (Platform.isAndroid) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 4),
),
);
} else {
Fluttertoast.showToast(
msg: message,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 3,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0,
);
}
}
Route platformRouter(Widget Function(BuildContext context) builder) =>
(Platform.isAndroid)
? MaterialPageRoute(builder: builder)
: CupertinoPageRoute(builder: builder);

View file

@ -232,6 +232,14 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
fluttertoast:
dependency: "direct main"
description:
name: fluttertoast
sha256: "7cc92eabe01e3f1babe1571c5560b135dfc762a34e41e9056881e2196b178ec1"
url: "https://pub.dev"
source: hosted
version: "8.1.2"
http: http:
dependency: transitive dependency: transitive
description: description:

View file

@ -6,10 +6,10 @@ publish_to: 'none'
# The following defines the version and build number for your application. # The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43 # A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +. # followed by an optional build number separated by a +.
version: 1.6.1+26 version: 1.7.0+27
environment: environment:
sdk: ">=2.16.1 <3.0.0" sdk: ">=2.18.2 <3.0.0"
dependencies: dependencies:
flutter: flutter:
@ -27,6 +27,7 @@ dependencies:
flutter_native_timezone: ^2.0.0 flutter_native_timezone: ^2.0.0
intl: ^0.17.0 intl: ^0.17.0
package_info_plus: ^1.4.3+1 package_info_plus: ^1.4.3+1
fluttertoast: ^8.1.2
dev_dependencies: dev_dependencies:
flutter_lints: ^2.0.1 flutter_lints: ^2.0.1