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,7 +125,9 @@ class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return (Platform
.isAndroid) // run app based on current platform to make use of the platform's respective UI lib
? MaterialApp(
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
localizationsDelegates: const [ localizationsDelegates: const [
AppLocalizationsDelegate(), AppLocalizationsDelegate(),
@ -140,6 +143,19 @@ class MyApp extends StatelessWidget {
primarySwatch: Colors.purple, primarySwatch: Colors.purple,
), ),
home: const LoginPage(), 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,17 +15,24 @@ 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) { if (!widget.canteen.prihlasen) {
Navigator.pushReplacement(
context, platformRouter((c) => const LoginPage()));
}
return Uzivatel(kredit: 0);
});
balance = uzivatel.kredit;
var burza = await widget.canteen.ziskatBurzu();
setState(() { setState(() {
obsah = []; content = [];
if (burza.isEmpty) { if (burza.isEmpty) {
obsah = [ content = [
Text( Text(
Languages.of(context)!.noExchange, Languages.of(context)!.noExchange,
style: const TextStyle(fontSize: 20), style: const TextStyle(fontSize: 20),
@ -32,7 +41,7 @@ class _BurzaViewState extends State<BurzaView> {
]; ];
} else { } else {
for (var b in burza) { for (var b in burza) {
obsah.add( content.add(
Padding( Padding(
padding: const EdgeInsets.only(top: 15), padding: const EdgeInsets.only(top: 15),
child: Row( child: Row(
@ -46,19 +55,19 @@ class _BurzaViewState extends State<BurzaView> {
), ),
), ),
Text("${b.pocet}x"), Text("${b.pocet}x"),
TextButton( PlatformButton(
onPressed: () { onPressed: () {
widget.canteen.objednatZBurzy(b).then((a) { widget.canteen.objednatZBurzy(b).then(
(a) {
if (a) { if (a) {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => PlatformDialog(
title: Text(Languages.of(context)!.ordered), title: Languages.of(context)!.ordered,
content: Text( content: Languages.of(context)!.orderSuccess,
Languages.of(context)!.orderSuccess),
actions: [ actions: [
TextButton( PlatformButton(
child: Text(Languages.of(context)!.ok), text: Languages.of(context)!.ok,
onPressed: () => onPressed: () =>
Navigator.of(context).pop(), Navigator.of(context).pop(),
) )
@ -68,14 +77,12 @@ class _BurzaViewState extends State<BurzaView> {
} else { } else {
showDialog( showDialog(
context: context, context: context,
builder: (context) => AlertDialog( builder: (context) => PlatformDialog(
title: Text( title: Languages.of(context)!.cannotOrder,
Languages.of(context)!.cannotOrder), content: Languages.of(context)!.errorOrdering,
content: Text(
Languages.of(context)!.errorOrdering),
actions: [ actions: [
TextButton( PlatformButton(
child: Text(Languages.of(context)!.ok), text: Languages.of(context)!.ok,
onPressed: () => onPressed: () =>
Navigator.of(context).pop(), Navigator.of(context).pop(),
) )
@ -83,10 +90,12 @@ class _BurzaViewState extends State<BurzaView> {
), ),
); );
} }
nactiBurzu(context); loadExchange(context);
});
}, },
child: Text(Languages.of(context)!.order)), );
},
text: Languages.of(context)!.order,
),
], ],
), ),
), ),
@ -94,19 +103,13 @@ class _BurzaViewState extends State<BurzaView> {
} }
} }
}); });
}); return;
}).catchError((o) {
if (!widget.canteen.prihlasen) {
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (c) => const LoginPage()));
}
});
} }
@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,43 +63,55 @@ 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()));
}
return Uzivatel(kredit: 0);
},
);
balance = uzivatel.kredit;
var jd = await widget.canteen.jidelnicekDen(den: day).catchError((_) {
showInfo(context, Languages.of(context)!.errorContacting);
return Jidelnicek(DateTime.now(), []);
});
setState(
() {
content = [];
if (jd.jidla.isEmpty) { if (jd.jidla.isEmpty) {
obsah.add(Text( content.add(Text(
Languages.of(context)!.noFood, Languages.of(context)!.noFood,
style: const TextStyle(fontSize: 15), style: const TextStyle(fontSize: 15),
)); ));
} else { } else {
for (var j in jd.jidla) { for (var j in jd.jidla) {
obsah.add( content.add(
Padding( Padding(
padding: const EdgeInsets.only(top: 15), padding: const EdgeInsets.only(top: 15),
child: InkWell( child: InkWell(
@ -124,22 +138,20 @@ class _JidelnicekViewState extends State<JidelnicekView> {
showDialog( showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
return AlertDialog( return PlatformDialog(
title: Text(Languages.of(context)! title: Languages.of(context)!.errorOrdering,
.errorOrdering), content: Languages.of(context)!.cannotOrder,
content: Text(
Languages.of(context)!.cannotOrder),
actions: [ actions: [
TextButton( PlatformButton(
child: text: Languages.of(context)!.ok,
Text(Languages.of(context)!.ok),
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
) )
], ],
); );
}); },
);
} else { } else {
showDialog( showDialog(
context: context, context: context,
@ -147,44 +159,45 @@ class _JidelnicekViewState extends State<JidelnicekView> {
builder: (_) => Dialog( builder: (_) => Dialog(
child: SizedBox( child: SizedBox(
height: 100, height: 100,
child: Row(children: [ child: Row(
children: [
const Padding( const Padding(
padding: EdgeInsets.all(10), padding: EdgeInsets.all(10),
child: child: CircularProgressIndicator(),
CircularProgressIndicator(),
), ),
Text(Languages.of(context)! Text(Languages.of(context)!.ordering)
.ordering) ],
]),
), ),
)); ),
),
);
widget.canteen.objednat(j).then((_) { widget.canteen.objednat(j).then((_) {
Navigator.of(context, rootNavigator: true) Navigator.of(context, rootNavigator: true).pop();
.pop(); loadMeals();
nactiJidlo(); }).catchError(
}).catchError((o) { (o) {
Navigator.of(context, rootNavigator: true) Navigator.of(context, rootNavigator: true)
.pop(); .pop();
showDialog( showDialog(
context: context, context: context,
builder: (bc) => AlertDialog( builder: (bc) => PlatformDialog(
title: Text(Languages.of(context)! title: Languages.of(context)!.errorOrdering,
.errorOrdering), content: o.toString(),
content: Text(o.toString()),
actions: [ actions: [
TextButton( PlatformButton(
child: Text( text: Languages.of(context)!.close,
Languages.of(context)!
.close),
onPressed: () { onPressed: () {
Navigator.pop(bc); Navigator.pop(bc);
}, },
) )
], ],
)); ),
}); );
},
);
} }
}) },
)
], ],
), ),
onTap: () async { onTap: () async {
@ -192,21 +205,20 @@ class _JidelnicekViewState extends State<JidelnicekView> {
showDialog( showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
return AlertDialog( return PlatformDialog(
title: title: Languages.of(context)!.errorOrdering,
Text(Languages.of(context)!.errorOrdering), content: Languages.of(context)!.cannotOrder,
content:
Text(Languages.of(context)!.cannotOrder),
actions: [ actions: [
TextButton( PlatformButton(
child: Text(Languages.of(context)!.ok), text: Languages.of(context)!.ok,
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
) )
], ],
); );
}); },
);
} else { } else {
showDialog( showDialog(
context: context, context: context,
@ -222,22 +234,22 @@ class _JidelnicekViewState extends State<JidelnicekView> {
Text(Languages.of(context)!.ordering) Text(Languages.of(context)!.ordering)
]), ]),
), ),
)); ),
);
widget.canteen.objednat(j).then((_) { widget.canteen.objednat(j).then((_) {
Navigator.of(context, rootNavigator: true).pop(); Navigator.of(context, rootNavigator: true).pop();
nactiJidlo(); loadMeals();
}).catchError( }).catchError(
(o) { (o) {
Navigator.of(context, rootNavigator: true).pop(); Navigator.of(context, rootNavigator: true).pop();
showDialog( showDialog(
context: context, context: context,
builder: (bc) => AlertDialog( builder: (bc) => PlatformDialog(
title: title: Languages.of(context)!.errorOrdering,
Text(Languages.of(context)!.errorOrdering), content: o.toString(),
content: Text(o.toString()),
actions: [ actions: [
TextButton( PlatformButton(
child: Text(Languages.of(context)!.close), text: Languages.of(context)!.close,
onPressed: () { onPressed: () {
Navigator.pop(bc); Navigator.pop(bc);
}, },
@ -252,42 +264,40 @@ class _JidelnicekViewState extends State<JidelnicekView> {
onLongPress: () async { onLongPress: () async {
if (!j.objednano || j.burzaUrl == null) return; if (!j.objednano || j.burzaUrl == null) return;
if (!j.naBurze) { if (!j.naBurze) {
// pokud není na burze, radši se zeptáme // if not in exchange, we ask
var d = await showDialog( var d = await showDialog(
context: context, context: context,
builder: (bc) => SimpleDialog( builder: (bc) => PlatformDialog(
title: Text( title: Languages.of(context)!.verifyExchange,
Languages.of(context)!.verifyExchange), actions: [
children: [ PlatformButton(
SimpleDialogOption(
onPressed: () { onPressed: () {
Navigator.pop(bc, true); Navigator.pop(bc, true);
}, },
child: Text(Languages.of(context)!.yes), text: Languages.of(context)!.yes,
), ),
SimpleDialogOption( PlatformButton(
onPressed: () { onPressed: () {
Navigator.pop(bc, false); Navigator.pop(bc, false);
}, },
child: Text(Languages.of(context)!.no), text: Languages.of(context)!.no,
), ),
], ],
)); ),
);
if (d) { if (d) {
widget.canteen widget.canteen
.doBurzy(j) .doBurzy(j)
.then((_) => nactiJidlo()) .then((_) => loadMeals())
.catchError((o) { .catchError((o) {
showDialog( showDialog(
context: context, context: context,
builder: (bc) => AlertDialog( builder: (bc) => PlatformDialog(
title: title: Languages.of(context)!.exchangeError,
Text(Languages.of(context)!.exchangeError), content: o.toString(),
content: SingleChildScrollView(
child: Text(o.toString())),
actions: [ actions: [
TextButton( PlatformButton(
child: Text(Languages.of(context)!.close), text: Languages.of(context)!.close,
onPressed: () { onPressed: () {
Navigator.pop(bc); Navigator.pop(bc);
}, },
@ -298,8 +308,8 @@ class _JidelnicekViewState extends State<JidelnicekView> {
}); });
} }
} else { } else {
// jinak ne // else no
widget.canteen.doBurzy(j).then((_) => nactiJidlo()); widget.canteen.doBurzy(j).then((_) => loadMeals());
} }
}, },
), ),
@ -307,42 +317,41 @@ class _JidelnicekViewState extends State<JidelnicekView> {
); );
} }
} }
}); },
}); );
}).catchError((o) { return;
if (!widget.canteen.prihlasen) {
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(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton( IconButton(
onPressed: () { onPressed: () {
setState(() { setState(() {
den = den.subtract(const Duration(days: 1)); day = day.subtract(const Duration(days: 1));
if (den.weekday == 7 && _skipWeekend) { if (day.weekday == 7 && _skipWeekend) {
den = den.subtract(const Duration(days: 2)); day = day.subtract(const Duration(days: 2));
} }
nactiJidlo(); loadMeals();
}); });
}, },
icon: const Icon(Icons.arrow_left)), icon: const Icon(Icons.arrow_left)),
TextButton( 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();
} }
} }
@ -134,16 +125,14 @@ class _LoginPageState extends State<LoginPage> {
Languages.of(context)!.logIn, Languages.of(context)!.logIn,
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
TextField( PlatformField(
controller: userControl, controller: userControl,
autofillHints: const [AutofillHints.username], autofillHints: const [AutofillHints.username],
decoration: InputDecoration( labelText: Languages.of(context)!.username,
labelText: Languages.of(context)!.username),
), ),
TextField( PlatformField(
autofillHints: const [AutofillHints.password], autofillHints: const [AutofillHints.password],
decoration: InputDecoration( labelText: Languages.of(context)!.password,
labelText: Languages.of(context)!.password),
controller: passControl, controller: passControl,
obscureText: true, obscureText: true,
), ),
@ -173,25 +162,25 @@ class _LoginPageState extends State<LoginPage> {
AnimatedOpacity( AnimatedOpacity(
opacity: _showUrl ? 1.0 : 0.0, opacity: _showUrl ? 1.0 : 0.0,
duration: const Duration(milliseconds: 300), duration: const Duration(milliseconds: 300),
child: TextField( child: PlatformField(
autofillHints: const [AutofillHints.url], autofillHints: const [AutofillHints.url],
decoration: InputDecoration( labelText: Languages.of(context)!.iCanteenUrl,
labelText: Languages.of(context)!.iCanteenUrl),
keyboardType: TextInputType.url, keyboardType: TextInputType.url,
controller: canteenControl, controller: canteenControl,
), ),
), ),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Row(mainAxisAlignment: MainAxisAlignment.center, children: [
Switch( PlatformSwitch(
value: rememberMe, value: rememberMe,
onChanged: (value) { onChanged: (value) {
setState(() { setState(() {
rememberMe = value; rememberMe = value;
}); });
}), },
),
Text(Languages.of(context)!.rememberMe) Text(Languages.of(context)!.rememberMe)
]), ]),
TextButton( PlatformButton(
onPressed: () async { onPressed: () async {
var canteenUrl = (dropdownUrl == "") var canteenUrl = (dropdownUrl == "")
? canteenControl.text ? canteenControl.text
@ -206,13 +195,7 @@ class _LoginPageState extends State<LoginPage> {
userControl.text, passControl.text); userControl.text, passControl.text);
if (!l) { if (!l) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentSnackBar(); showInfo(context, Languages.of(context)!.loginFailed);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content:
Text(Languages.of(context)!.loginFailed),
),
);
return; return;
} }
if (rememberMe) { if (rememberMe) {
@ -221,61 +204,50 @@ class _LoginPageState extends State<LoginPage> {
} }
// souhlas // souhlas
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
var odsouhlasil = var odsouhlasil = await storage.read(key: "oc_souhlas");
await storage.read(key: "oc_souhlas");
if (!mounted) return; if (!mounted) return;
if (odsouhlasil == null || odsouhlasil != "ano") { if (odsouhlasil == null || odsouhlasil != "ano") {
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(
context, context,
MaterialPageRoute( platformRouter(
builder: (c) => WelcomePage( (context) => WelcomePage(
canteen: canteen, canteen: canteen,
)), ),
),
(route) => false); (route) => false);
} else { } else {
Navigator.pushAndRemoveUntil( Navigator.pushAndRemoveUntil(
context, context,
MaterialPageRoute( platformRouter(
builder: (context) => JidelnicekView( (context) => MealView(
canteen: canteen, canteen: canteen,
)), ),
),
(route) => false); (route) => false);
} }
} on PlatformException { } on PlatformException {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentSnackBar(); showInfo(context, Languages.of(context)!.corrupted);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(Languages.of(context)!.corrupted),
),
);
} on Exception catch (_) { } on Exception catch (_) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).hideCurrentSnackBar(); showInfo(
ScaffoldMessenger.of(context).showSnackBar( context, Languages.of(context)!.errorContacting);
SnackBar( //goOffline();
content:
Text(Languages.of(context)!.errorContacting),
),
);
goOffline();
} }
}, },
child: Text(Languages.of(context)!.logIn)), 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;
_notifyMeal = preferences!.getBool("oznamit") ?? false;
_countController.text = _countController.text =
(preferences!.getInt("offline_pocet") ?? 1).toString(); (preferences!.getInt("offline_pocet") ?? 1).toString();
var casStr = preferences!.getString("oznameni_cas"); var casStr = preferences!.getString("oznameni_cas");
if (casStr == null) { if (casStr == null) {
var now = DateTime.now(); var now = DateTime.now();
_oznameniCas = TimeOfDay.fromDateTime( _notifTime = TimeOfDay.fromDateTime(
DateTime.now().add(const Duration(hours: 1))); DateTime.now().add(const Duration(hours: 1)));
preferences!.setString("oznameni_cas", now.toString()); preferences!.setString("oznameni_cas", now.toString());
} else { } else {
_oznameniCas = TimeOfDay.fromDateTime(DateTime.parse(casStr)); _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
@ -78,16 +85,16 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
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( Row(
@ -96,9 +103,9 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
Text(Languages.of(context)!.saveCount), Text(Languages.of(context)!.saveCount),
SizedBox( SizedBox(
width: 35, width: 35,
child: TextField( child: PlatformField(
controller: _countController, controller: _countController,
enabled: _ukladatOffline, enabled: _saveOffline,
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (c) { onChanged: (c) {
@ -115,123 +122,123 @@ class _AndroidNastaveniState extends State<AndroidNastaveni> {
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Text(Languages.of(context)!.skipWeekend), Text(Languages.of(context)!.skipWeekend),
Switch( PlatformSwitch(
activeColor: Colors.purple, value: _skipWeekend,
value: _preskakovatVikend,
onChanged: (value) { onChanged: (value) {
setState(() { setState(
_preskakovatVikend = value; () {
zmenitNastaveni("skip", value); _skipWeekend = value;
}); changeSetting("skip", value);
}) },
);
},
)
], ],
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Flexible(child: Text(Languages.of(context)!.checkOrdered)), Flexible(child: Text(Languages.of(context)!.checkOrdered)),
Switch( PlatformSwitch(
activeColor: Colors.purple, value: _checkWeek,
value: _kontrolovatTyden,
onChanged: (value) { onChanged: (value) {
setState(() { setState(
_kontrolovatTyden = value; () {
zmenitNastaveni("tyden", value); _checkWeek = value;
}); changeSetting("tyden", value);
}) },
);
},
)
], ],
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Flexible(child: Text(Languages.of(context)!.notifyLunch)), Flexible(child: Text(Languages.of(context)!.notifyLunch)),
Switch( PlatformSwitch(
activeColor: Colors.purple, value: _notifyMeal,
value: _oznameniObed, thumbColor: (!_remember ? Colors.grey : null),
thumbColor: (!_zapamatovany
? MaterialStateProperty.all(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: [
TextButton( PlatformButton(
child: Text(Languages.of(context)!.ok), 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(
Languages.of(context)!.notifyWarning),
actions: [ actions: [
TextButton( PlatformButton(
child: text: Languages.of(context)!.ok,
Text(Languages.of(context)!.ok),
onPressed: () { onPressed: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
) )
], ],
)); ),
vytvoritOznameni(casNaDate(_oznameniCas)); );
createNotif(timeToDate(_notifTime));
} }
zmenitNastaveni("oznamit", value); changeSetting("oznamit", value);
}); });
} }
}) },
)
], ],
), ),
Text(Languages.of(context)!.notifyAt), Text(Languages.of(context)!.notifyAt),
TextButton( PlatformButton(
onPressed: () async { onPressed: () async {
if (_oznameniObed) { if (_notifyMeal) {
var cas = await showTimePicker( var cas = await showTimePicker(
context: context, initialTime: _oznameniCas); context: context, initialTime: _notifTime);
if (cas != null) { if (cas != null) {
var prefs = await SharedPreferences.getInstance(); var prefs = await SharedPreferences.getInstance();
prefs.setString("oznameni_cas", prefs.setString(
casNaDate(cas).toString()); // aktualizovat vybraný čas "oznameni_cas",
var den = casNaDate(cas); timeToDate(cas)
.toString()); // aktualizovat vybraný čas
var den = timeToDate(cas);
debugPrint(den.isAfter(DateTime.now()).toString()); debugPrint(den.isAfter(DateTime.now()).toString());
if (den.isAfter(DateTime.now())) { if (den.isAfter(DateTime.now())) {
// znovu vytvořit oznámení POUZE když je čas v budoucnosti // znovu vytvořit oznámení POUZE když je čas v budoucnosti
vytvoritOznameni(den); createNotif(den);
} }
} }
setState(() { setState(() {
_oznameniCas = cas ?? _oznameniCas; _notifTime = cas ?? _notifTime;
}); });
} }
}, },
child: Text( text:
"${(_oznameniCas.hour < 10 ? "0" : "") + _oznameniCas.hour.toString()}:${(_oznameniCas.minute < 10 ? "0" : "") + _oznameniCas.minute.toString()}", "${(_notifTime.hour < 10 ? "0" : "") + _notifTime.hour.toString()}:${(_notifTime.minute < 10 ? "0" : "") + _notifTime.minute.toString()}",
style: TextStyle(
color: (!_oznameniObed) ? Colors.grey : Colors.purple),
),
), ),
], ],
), ),
)), ),
),
); );
} }
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"),
@ -132,25 +136,27 @@ class _AndroidOfflineJidelnicekState extends State<AndroidOfflineJidelnicek> {
"${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