repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/lessons_schedule/lessons_schedule_logic.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class LessonsScheduleLogic extends ChangeNotifier { final transformationController = TransformationController(); late AnimationController animationController; late Animation<Matrix4> animation; late TapDownDetails doubleTapDetails; bool showForToday = true; String baseUrl = 'https://energocollege.ru/vec_assistant/' '%D0%A0%D0%B0%D1%81%D0%BF%D0%B8%D1%81%D0%B0%D0%BD%D0%B8%D0%B5/'; String endUrl = '.jpg'; String dateFromUrl = ''; String imgUrl = ''; void onInitState(TickerProvider tickerProvider) { imgUrl = getUrl(forToday: true); animationController = AnimationController( vsync: tickerProvider, duration: const Duration(milliseconds: 300), )..addListener(() { transformationController.value = animation.value; }); } void onDispose() { animationController.dispose(); } void updateImgUrl() { imgUrl = getUrl(forToday: showForToday); notifyListeners(); } String get parseDateFromUrl { DateTime parsed = DateFormat('d-M-yyyy', 'ru').parse(dateFromUrl); DateFormat formatter = DateFormat('d MMMM yyyy'); return formatter.format(parsed); } String getUrl({required bool forToday}) { // get next day to show lesson schedule DateTime date = DateTime.now(); DateFormat formatter = DateFormat('d-M-yyyy'); // if we need to show lessons for tomorrow, then we plus days from now // isWeekend used for auto showing schedule for next day from screen start int plusDays = 0; int today = date.weekday; bool isWeekend = false; switch (today) { case DateTime.friday: plusDays = 3; break; case DateTime.saturday: plusDays = 2; isWeekend = true; break; case DateTime.sunday: plusDays = 1; isWeekend = true; break; default: plusDays = 1; break; } if (!forToday || isWeekend) { date = date.add(Duration(days: plusDays)); if (isWeekend) showForToday = false; } dateFromUrl = formatter.format(date); return baseUrl + formatter.format(date) + endUrl; } Future<void> chooseDate(BuildContext context) async { final DateTime? picked = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2018, 8), lastDate: DateTime.now().add(const Duration(days: 30)), ); if (picked != null) { dateFromUrl = '${picked.day}-${picked.month}-${picked.year}'; } imgUrl = baseUrl + dateFromUrl + endUrl; notifyListeners(); FirebaseAnalytics.instance.logEvent(name: 'full_schedule_date_chosen', parameters: { 'date': dateFromUrl, }); } void handleDoubleTapDown(TapDownDetails details) { // get details about offset of interactive viewer doubleTapDetails = details; } void handleDoubleTap() { Matrix4 endMatrix = Matrix4.identity(); Offset position = doubleTapDetails.localPosition; if (transformationController.value != Matrix4.identity()) { endMatrix = Matrix4.identity() ..translate(-position.dx * 2, -position.dy * 2) ..scale(3.5); } // animate zooming animation = Matrix4Tween( begin: transformationController.value, end: endMatrix, ).animate( CurveTween(curve: Curves.easeOut).animate(animationController), ); animationController.forward(from: 0); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/menu/menu_logic.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:intl/intl.dart'; import '../../utils/firebase_auth.dart'; class MenuLogic { static Future<bool> get isOpenDoorsDay async { DocumentSnapshot document = await FirebaseFirestore.instance .collection('misc_settings') .doc('open_doors') .get(); Timestamp timestamp = document['date']; String dateOpenDoors = DateFormat('d-MM-yyyy').format(timestamp.toDate()); String now = DateFormat('d-MM-yyyy').format(DateTime.now()); return dateOpenDoors == now && AccountDetails.getAccountLevel == AccountType.student; } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/menu/menu_screen.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '/utils/icons.dart'; import '/widgets/styled_widgets.dart'; import '../../utils/theme/theme.dart'; import '../../widgets/system_bar_cover.dart'; import 'menu_logic.dart'; class MenuScreen extends StatefulWidget { const MenuScreen({Key? key}) : super(key: key); @override State<MenuScreen> createState() => _MenuScreenState(); } class _MenuScreenState extends State<MenuScreen> { @override void initState() { FirebaseAnalytics.instance.setCurrentScreen(screenName: 'menu_screen'); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, appBar: StatusBarCover( height: MediaQuery.of(context).padding.top, ), body: SingleChildScrollView( padding: MediaQuery.of(context).padding.add(const EdgeInsets.all(10)), child: Column( mainAxisSize: MainAxisSize.min, children: [ // settings block StyledListTile( icon: Icon( Icons.settings_outlined, color: context.palette.accentColor, size: 32, ), title: 'Настройки', subtitle: 'Выбрать тему и стартовый экран', onTap: () async { await Navigator.pushNamed(context, '/settings'); }, ), // information block const Divider(), StyledListTile( icon: Icon( Icons.group_outlined, color: context.palette.accentColor, size: 32, ), title: 'Список преподавателей', subtitle: 'Их дисциплины, кабинеты', onTap: () async { await Navigator.pushNamed(context, '/teacher'); }, ), StyledListTile( icon: Icon( VpecIconPack.account_cog_outline, color: context.palette.accentColor, size: 32, ), title: 'Администрация колледжа', subtitle: 'По вопросам и предложениям', onTap: () async { await Navigator.pushNamed(context, '/administration'); }, ), FutureBuilder<bool>( future: MenuLogic.isOpenDoorsDay, initialData: false, builder: (BuildContext context, AsyncSnapshot<bool> snapshot) { if (snapshot.hasData) { if (snapshot.data!) { return StyledListTile( icon: Icon( Icons.rule_outlined, color: context.palette.accentColor, size: 32, ), title: 'Моя профессиональная направленность', subtitle: 'Узнать свою предрасположенность', onTap: () async { await Navigator.pushNamed(context, '/job_quiz'); }, ); } } return const SizedBox.shrink(); }, ), // documents block const Divider(), StyledListTile( title: 'Документы', subtitle: 'Список документов', icon: Icon( Icons.description_outlined, size: 32, color: context.palette.accentColor, ), onTap: () async { await Navigator.pushNamed(context, '/documents'); }, ), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/debug/debug_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '/models/document_model.dart'; import '/screens/login/login_logic.dart'; import '/screens/login/login_screen.dart'; import '../../utils/notifications/firebase_messaging.dart'; import '../../utils/routes/routes.dart'; import '../../widgets/loading_indicator.dart'; class DebugScreen extends StatelessWidget { const DebugScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Экран тестирования'), ), body: SafeArea( minimum: const EdgeInsets.all(12.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ FutureBuilder<String>( future: AppFirebaseMessaging.getToken(), builder: (context, snapshot) { if (!snapshot.hasData) return const LoadingIndicator(); return Column( children: [ SizedBox( width: double.infinity, child: OutlinedButton( onPressed: () => Clipboard.setData( ClipboardData(text: snapshot.data!), ), child: const Text('Copy FCM token'), ), ), ], ); }, ), const Divider(), SizedBox( width: double.infinity, child: OutlinedButton( onPressed: () => Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => const LoginScreen(), ), ), child: const Text('LoginScreen'), ), ), SizedBox( width: double.infinity, child: OutlinedButton( onPressed: () async { String docURL = await LoginLogic.getEntrantUrl(); Navigator.pushNamed( context, '/view_document', arguments: DocumentModel( title: 'Для абитуриента', subtitle: '', url: docURL, ), ); }, child: const Text('EntrantScreen'), ), ), SizedBox( width: double.infinity, child: OutlinedButton( onPressed: () async => Navigator.pushNamed( context, Routes.jobQuizScreen, ), child: const Text('JobQuiz'), ), ), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/view_document/view_document_ui.dart
import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_linkify/flutter_linkify.dart'; import 'package:uc_pdfview/uc_pdfview.dart'; import '/models/document_model.dart'; import '/utils/utils.dart'; import '/widgets/loading_indicator.dart'; import '/widgets/markdown_widget.dart'; import 'view_document_logic.dart'; @immutable class DocumentViewer extends StatelessWidget { const DocumentViewer({Key? key, required this.document}) : super(key: key); final DocumentModel document; @override Widget build(BuildContext context) { String docType = ViewDocumentLogic.getFileExtension(document.url); switch (docType) { case 'pdf': return buildPDFViewer(); case 'md': return buildMDViewer(); default: return buildError(); } } Widget buildPDFViewer() { return Center( child: FutureBuilder<Uint8List>( initialData: null, future: ViewDocumentLogic.getPDFData(document.url), builder: (context, pdfData) { if (!pdfData.hasData) return const LoadingIndicator(); return ColorFiltered( colorFilter: ViewDocumentLogic.documentColorFilter, child: UCPDFView( pdfData: pdfData.data, ), ); }, ), ); } Widget buildMDViewer() { return Center( child: FutureBuilder<String>( future: ViewDocumentLogic.getMDText(document.url), initialData: null, builder: (BuildContext context, AsyncSnapshot<String> snapshot) { if (!snapshot.hasData) return const LoadingIndicator(); return MarkdownWidget(data: snapshot.data!); }, ), ); } Widget buildError() { return Center( child: SelectableLinkify( text: 'Неподдерживаемый тип файла: ${ViewDocumentLogic.getFileExtension(document.url)}\nИсходная ссылка:\n${document.url}', textAlign: TextAlign.center, onOpen: (link) => openUrl(link.url), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/view_document/view_document_screen.dart
import 'package:flutter/material.dart'; import '/models/document_model.dart'; import '/utils/theme_helper.dart'; import '/utils/utils.dart'; import '../../widgets/system_bar_cover.dart'; import 'view_document_logic.dart'; import 'view_document_ui.dart'; @immutable class DocumentViewScreen extends StatelessWidget { const DocumentViewScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { late DocumentModel document; if (ModalRoute.of(context)!.settings.arguments is DocumentModel) { document = ModalRoute.of(context)!.settings.arguments as DocumentModel; } else { Navigator.popAndPushNamed(context, '/'); } ThemeHelper.colorSystemChrome(); bool isFilePDF = ViewDocumentLogic.getFileExtension(document.url) == 'pdf'; return Scaffold( // no extendBody due to documents being weird bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), appBar: AppBar( title: Text(document.title), actions: [ if (isFilePDF) IconButton( tooltip: 'Поделиться', onPressed: () => shareFile(document.url), icon: const Icon(Icons.share_outlined), ), if (isFilePDF) IconButton( tooltip: 'Открыть в другом приложении', onPressed: () => openUrl(document.url), icon: const Icon(Icons.open_in_new_outlined), ), ], ), body: DocumentViewer(document: document), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/view_document/view_document_logic.dart
import 'dart:convert' show utf8; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '/utils/hive_helper.dart'; import '/utils/theme_helper.dart'; class ViewDocumentLogic { static ColorFilter get documentColorFilter { const ColorFilter lightThemeFilter = ColorFilter.matrix([ //R G B A Const 0.96078, 0, 0, 0, 0, 0, 0.96078, 0, 0, 0, 0, 0, 0.96078, 0, 0, 0, 0, 0, 1, 0, ]); const ColorFilter darkThemeFilter = ColorFilter.matrix([ //R G B A Const -0.87843, 0, 0, 0, 255, 0, -0.87843, 0, 0, 255, 0, 0, -0.87843, 0, 255, 0, 0, 0, 1, 0, ]); return HiveHelper.getValue('alwaysLightThemeDocument') ?? !ThemeHelper.isDarkMode ? lightThemeFilter : ThemeHelper.isDarkMode ? darkThemeFilter : lightThemeFilter; } static Future<String> getMDText(String url) async { String text = await http.read(Uri.parse(url)); return utf8.decode(text.codeUnits); } static String getFileExtension(String path) { return path.split('/').last.split('.').last.split('?').first.toLowerCase(); } static bool isThisURLSupported(String url) { List<String> supportedExtensions = ['pdf', 'md']; return supportedExtensions.contains(getFileExtension(url)); } static Future<Uint8List> getPDFData(String url) async { return await http.readBytes(Uri.parse(url)); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/settings/settings_ui.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/screens/debug/debug_screen.dart'; import '/utils/hive_helper.dart'; import '/utils/icons.dart'; import '/widgets/styled_widgets.dart'; import '../../utils/firebase_auth.dart'; import '../../utils/theme/theme.dart'; import 'settings_logic.dart'; class AccountBlock extends StatefulWidget { const AccountBlock({Key? key}) : super(key: key); @override State<AccountBlock> createState() => _AccountBlockState(); } class _AccountBlockState extends State<AccountBlock> { @override Widget build(BuildContext context) { return Consumer<FirebaseAppAuth>( builder: (BuildContext context, auth, Widget? child) { return AnimatedSize( curve: Curves.fastOutSlowIn, duration: const Duration(milliseconds: 400), child: Column( children: [ StyledListTile( onTap: () => SettingsLogic.accountLogin(context), icon: Icon( Icons.account_circle_outlined, color: context.palette.accentColor, size: 32, ), title: 'Аккаунт', subtitle: auth.accountInfo.isLoggedIn ? SettingsLogic.getAccountModeText(context) : 'Нажмите, чтобы войти в аккаунт', ), HivedListTile( onTap: () => SettingsLogic.chooseGroup(context), icon: Icon( Icons.subject_outlined, color: context.palette.accentColor, size: 32, ), title: 'Выбрать группу', subtitleKey: 'chosenGroup', defaultValue: 'Нажмите, чтобы выбрать группу', ), if (auth.accountInfo.level == AccountType.admin) Column( children: [ HivedListTile( onTap: () => SettingsLogic.changeName(context), icon: Icon( Icons.edit_outlined, color: context.palette.accentColor, size: 32.0, ), title: 'Имя для объявлений', subtitleKey: 'username', defaultValue: 'Текущее: нет (нажмите, чтобы изменить)', ), StyledListTile( icon: Icon( Icons.tune_outlined, color: context.palette.accentColor, size: 32.0, ), title: 'Режим редактирования', subtitle: context.watch<AccountEditorMode>().isEditorModeActive ? 'Нажмите, чтобы выйти из режима редактирования' : 'Нажмите, чтобы войти в режим редактирования', onTap: () => context.read<AccountEditorMode>().toggleEditorMode(), ), StyledListTile( icon: Icon( Icons.construction_outlined, color: context.palette.accentColor, size: 32.0, ), title: 'Экран тестирования', subtitle: 'Для дебага функций', onTap: () => Navigator.push( context, CupertinoPageRoute( builder: (BuildContext context) => const DebugScreen(), ), ), ), ], ), ], ), ); }, ); } } class AppThemeListTile extends StatelessWidget { const AppThemeListTile({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return HivedListTile( title: 'Тема приложения', subtitleKey: 'theme', defaultValue: 'Системная тема', icon: Icon( Icons.brightness_6_outlined, size: 32.0, color: context.palette.accentColor, ), onTap: () async { await SettingsLogic.chooseTheme(context: context); }, ); } } class LaunchOnStartChooser extends StatelessWidget { const LaunchOnStartChooser({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return HivedListTile( onTap: () => SettingsLogic().chooseLaunchOnStart(context), subtitleKey: 'launchOnStartString', defaultValue: 'События', title: 'Открывать при запуске', icon: Icon( Icons.launch_outlined, color: context.palette.accentColor, size: 32.0, ), ); } } class AccountLoginUI extends StatelessWidget { const AccountLoginUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); return Column( children: [ AutofillGroup( child: Column( children: [ TextFormField( controller: emailController, autofillHints: const <String>[AutofillHints.username], textInputAction: TextInputAction.next, keyboardType: TextInputType.emailAddress, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Введите email'), ), const SizedBox(height: 10), TextFormField( controller: passwordController, autofillHints: const <String>[AutofillHints.password], textInputAction: TextInputAction.done, obscureText: true, keyboardType: TextInputType.visiblePassword, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Введите пароль'), ), ], ), ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: TextButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( child: const Text('Войти'), onPressed: () { SettingsLogic().makeLogin( context, email: emailController.text, password: passwordController.text, ); }, ), ), ], ), ], ); } } class AccountLogoutUI extends StatelessWidget { const AccountLogoutUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: OutlinedButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), const SizedBox(width: 10), Expanded( child: OutlinedButton( child: const Text('Выйти'), onPressed: () => SettingsLogic.accountLogout(context), ), ), ], ), ], ); } } class EditNameUI extends StatelessWidget { EditNameUI({ Key? key, }) : super(key: key); final TextEditingController nameController = TextEditingController(); @override Widget build(BuildContext context) { return Column( children: [ TextFormField( controller: nameController, textInputAction: TextInputAction.done, keyboardType: TextInputType.text, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Введите имя'), ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Expanded( child: TextButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( child: const Text('Сохранить'), onPressed: () { HiveHelper.saveValue( key: 'username', value: nameController.value.text.trim(), ); Navigator.pop(context); }, ), ), ], ), ], ); } } class ThemeChooserUI extends StatefulWidget { final Function lightThemeSelected; final Function darkThemeSelected; final Function defaultThemeSelected; final String hiveKey; final void Function(bool) alwaysLightThemeDocumentChanged; const ThemeChooserUI({ Key? key, required this.lightThemeSelected, required this.darkThemeSelected, required this.defaultThemeSelected, required this.hiveKey, required this.alwaysLightThemeDocumentChanged, }) : super(key: key); @override State<ThemeChooserUI> createState() => _ThemeChooserUIState(); } class _ThemeChooserUIState extends State<ThemeChooserUI> { int selectedItem = 0; bool documentLightThemeSwitchState = false; @override void initState() { selectedItem = HiveHelper.getValue(widget.hiveKey) == null ? 2 : HiveHelper.getValue(widget.hiveKey) == 'Светлая тема' ? 0 : 1; if (HiveHelper.getValue('alwaysLightThemeDocument') == null) { HiveHelper.saveValue(key: 'alwaysLightThemeDocument', value: false); } if (HiveHelper.getValue('alwaysLightThemeDocument')) { documentLightThemeSwitchState = true; } super.initState(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 6), child: Column( children: [ RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( Icons.brightness_5_outlined, color: context.palette.accentColor, ), ), title: Text( 'Светлая тема', style: Theme.of(context).textTheme.headline4, ), value: 0, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (dynamic value) { widget.lightThemeSelected(); setState(() { selectedItem = value; }); }, ), RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( Icons.brightness_2_outlined, color: context.palette.accentColor, ), ), title: Text( 'Тёмная тема', style: Theme.of(context).textTheme.headline4, ), value: 1, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (dynamic value) { setState(() { widget.darkThemeSelected(); setState(() { selectedItem = value; }); }); }, ), RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( Icons.phonelink_setup_outlined, color: context.palette.accentColor, ), ), title: Text( 'Системная тема', style: Theme.of(context).textTheme.headline4, ), value: 2, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (dynamic value) { widget.defaultThemeSelected(); setState(() { selectedItem = value; }); }, ), const Divider(), SwitchListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), value: documentLightThemeSwitchState, activeColor: context.palette.accentColor, secondary: Center( widthFactor: 1, child: Icon( Icons.description_outlined, color: context.palette.accentColor, ), ), title: Text( 'Всегда светлая тема для документов', style: Theme.of(context).textTheme.headline4, ), onChanged: (value) { widget.alwaysLightThemeDocumentChanged(value); setState(() { documentLightThemeSwitchState = value; }); }, ), ], ), ); } } class LaunchOnStartChooserUI extends StatefulWidget { const LaunchOnStartChooserUI({Key? key}) : super(key: key); @override State<LaunchOnStartChooserUI> createState() => _LaunchOnStartChooserUIState(); } class _LaunchOnStartChooserUIState extends State<LaunchOnStartChooserUI> { int selectedItem = HiveHelper.getValue('launchOnStart') ?? 0; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 6), child: Column( children: [ RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( VpecIconPack.news_outline, color: context.palette.accentColor, ), ), title: Text( 'События', style: Theme.of(context).textTheme.headline4, ), value: 0, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (int? value) { setState(() { HiveHelper.saveValue(key: 'launchOnStart', value: value); HiveHelper.saveValue( key: 'launchOnStartString', value: 'События', ); selectedItem = value!; }); }, ), RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( Icons.notifications_outlined, color: context.palette.accentColor, ), ), title: Text( 'Объявления', style: Theme.of(context).textTheme.headline4, ), value: 1, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (int? value) { setState(() { HiveHelper.saveValue(key: 'launchOnStart', value: value); HiveHelper.saveValue( key: 'launchOnStartString', value: 'Объявления', ); selectedItem = value!; }); }, ), RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( Icons.access_time_outlined, color: context.palette.accentColor, ), ), title: Text( 'Расписание занятий', style: Theme.of(context).textTheme.headline4, ), value: 2, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (int? value) { setState(() { HiveHelper.saveValue(key: 'launchOnStart', value: value); HiveHelper.saveValue( key: 'launchOnStartString', value: 'Расписание занятий', ); selectedItem = value!; }); }, ), RadioListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), secondary: Center( widthFactor: 1, child: Icon( Icons.layers_outlined, color: context.palette.accentColor, ), ), title: Text( 'Карта кабинетов', style: Theme.of(context).textTheme.headline4, ), value: 3, activeColor: context.palette.accentColor, groupValue: selectedItem, controlAffinity: ListTileControlAffinity.trailing, onChanged: (int? value) { setState(() { HiveHelper.saveValue(key: 'launchOnStart', value: value); HiveHelper.saveValue( key: 'launchOnStartString', value: 'Карта кабинетов', ); selectedItem = value!; }); }, ), ], ), ); } } class ChooseGroupUI extends StatelessWidget { const ChooseGroupUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<GroupsData>(builder: (context, logic, _) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ DropdownButtonFormField<String>( borderRadius: const BorderRadius.all(Radius.circular(20.0)), value: GroupsData.getGroupsNames.first, isExpanded: true, isDense: false, items: GroupsData.getGroupsNames .map<DropdownMenuItem<String>>( (group) => DropdownMenuItem<String>( value: group, child: Text(group), ), ) .toList(), onChanged: (value) => logic.onValueChanged( value, type: ChangedType.groupName, ), style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Специальность'), menuMaxHeight: 400, ), const SizedBox( height: 10, ), Row( children: [ Expanded( child: DropdownButtonFormField<String>( value: GroupsData.getCoursesNumbers.first, items: GroupsData.getCoursesNumbers .map<DropdownMenuItem<String>>( (course) => DropdownMenuItem<String>( value: course, child: Text(course), ), ) .toList(), onChanged: (value) => logic.onValueChanged( value, type: ChangedType.groupCourse, ), style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Курс'), menuMaxHeight: 400, ), ), const SizedBox(width: 10), Expanded( child: DropdownButtonFormField<String>( value: GroupsData.getGroupNumbers.first, items: GroupsData.getGroupNumbers .map<DropdownMenuItem<String>>( (groupNum) => DropdownMenuItem<String>( value: groupNum, child: Text(groupNum), ), ) .toList(), onChanged: (value) => logic.onValueChanged( value, type: ChangedType.groupNumber, ), style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Группа'), menuMaxHeight: 400, ), ), ], ), Padding( padding: const EdgeInsets.only(left: 12), child: SwitchListTile( contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), activeColor: context.palette.accentColor, value: logic.isAccelerated, title: Text( 'Ускоренная форма обучения', style: Theme.of(context).textTheme.headline3, ), onChanged: (value) => logic.onValueChanged( value, type: ChangedType.accelerated, ), ), ), const SizedBox(height: 10), Text( 'Будет выбрана группа:', style: Theme.of(context).textTheme.headline3, ), Builder(builder: (context) { return Text( logic.formedGroup, style: Theme.of(context).textTheme.headline6, textAlign: TextAlign.center, ); }), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: TextButton( onPressed: () => Navigator.pop(context), child: const Text('Закрыть'), ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( onPressed: logic.isSaveButtonEnabled ? () => logic.saveFormedGroup(context) : null, child: const Text('Сохранить'), ), ), ], ), ], ); }); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/settings/settings_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/widgets/styled_widgets.dart'; import '../../utils/firebase_auth.dart'; import '../../utils/theme/theme.dart'; import '../../utils/theme_helper.dart'; import '../../widgets/system_bar_cover.dart'; import 'settings_logic.dart'; import 'settings_ui.dart'; class SettingsScreen extends StatefulWidget { const SettingsScreen({Key? key}) : super(key: key); @override State<SettingsScreen> createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Scaffold( extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), appBar: AppBar( title: const Text('Настройки'), ), body: ListView( padding: const EdgeInsets.all(10), children: [ Card( child: MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => AccountEditorMode()), ChangeNotifierProvider(create: (_) => SettingsLogic()), ], builder: (context, child) => const AccountBlock(), ), ), const AppThemeListTile(), const LaunchOnStartChooser(), const Divider(), StyledListTile( icon: Icon( Icons.info_outlined, size: 32, color: context.palette.accentColor, ), title: 'О приложении', subtitle: 'Просмотреть техническую информацию', onTap: () => Navigator.pushNamed(context, '/about'), ), ], ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/settings/settings_logic.dart
import 'dart:async'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/utils/hive_helper.dart'; import '/utils/theme_helper.dart'; import '/utils/utils.dart'; import '../../utils/firebase_auth.dart'; import '../../utils/routes/routes.dart'; import '../../widgets/snackbars.dart'; import '../schedule/schedule_screen.dart'; import 'settings_ui.dart'; class SettingsLogic extends ChangeNotifier { // show roundedModalSheet() for account login static Future<void> accountLogin(BuildContext context) async { if (context.read<FirebaseAppAuth>().accountInfo.level != AccountType.entrant) { await showRoundedModalSheet( context: context, title: 'Выйти из аккаунта?', child: const AccountLogoutUI(), ); } else { await showRoundedModalSheet( context: context, title: 'Войти в аккаунт', child: const AccountLoginUI(), ); } } // login to firebase account with email and password void makeLogin( BuildContext context, { required String email, required password, }) async { try { // trying to login await FirebaseAuth.instance .signInWithEmailAndPassword(email: email, password: password); Navigator.pop(context); FirebaseAnalytics.instance.logEvent(name: 'login_successful'); } on FirebaseAuthException { Navigator.pop(context); showSnackBar(context, text: 'Данные введены неверно'); FirebaseAnalytics.instance.logEvent(name: 'login_incorrect_data'); } catch (e) { Navigator.pop(context); showSnackBar(context, text: e.toString()); FirebaseAnalytics.instance.logEvent(name: 'login_error', parameters: { 'code': e.toString(), }); } } static Future<void> accountLogout(BuildContext context) async { try { await FirebaseAuth.instance.signOut(); Navigator.pushNamedAndRemoveUntil( context, Routes.homeScreen, (route) => false, ); } catch (e) { showSnackBar(context, text: 'Ошибка выхода из аккаунта'); } } // show roundedModalSheet() for editing user's name // (name used for announcements post) static Future<void> changeName(BuildContext context) async { await showRoundedModalSheet( title: 'Изменить имя', context: context, child: EditNameUI(), ); } static String getAccountModeText(BuildContext context) { switch (context.read<FirebaseAppAuth>().accountInfo.level) { case AccountType.admin: return 'Администратор'; case AccountType.student: return 'Студент'; case AccountType.parent: return 'Родитель'; case AccountType.teacher: return 'Преподаватель'; case AccountType.entrant: return 'Абитуриент'; default: return 'Неизвестно'; } } static Future<void> chooseTheme({ required BuildContext context, }) async { await showRoundedModalSheet( context: context, title: 'Выберите тему', child: Consumer<ThemeNotifier>( builder: (BuildContext context, value, Widget? child) { return ThemeChooserUI( hiveKey: 'theme', lightThemeSelected: () { HiveHelper.saveValue(key: 'theme', value: 'Светлая тема'); value.changeTheme(ThemeMode.light); }, darkThemeSelected: () { HiveHelper.saveValue(key: 'theme', value: 'Тёмная тема'); value.changeTheme(ThemeMode.dark); }, defaultThemeSelected: () { HiveHelper.removeValue('theme'); value.changeTheme(ThemeMode.system); }, alwaysLightThemeDocumentChanged: (value) { HiveHelper.saveValue( key: 'alwaysLightThemeDocument', value: value, ); }, ); }, ), ); FirebaseAnalytics.instance.logEvent(name: 'settings_theme', parameters: { 'selected_theme' : context.read<ThemeNotifier>().themeMode.toString(), }); } Future<void> chooseLaunchOnStart(BuildContext context) async { await showRoundedModalSheet( context: context, title: 'Открывать при запуске', child: const LaunchOnStartChooserUI(), ); FirebaseAnalytics.instance.logEvent(name: 'settings_launch_on_start', parameters: { 'selected_item' : HiveHelper.getValue('launchOnStart') ?? 0, }); } static Future<void> chooseGroup(BuildContext context) async { await showRoundedModalSheet( context: context, title: 'Выберите группу', child: ChangeNotifierProvider<GroupsData>( create: (_) => GroupsData(), child: const ChooseGroupUI(), ), ); FirebaseAnalytics.instance.logEvent(name: 'settings_group', parameters: { 'selected_group' : HiveHelper.getValue('chosenGroup'), }); } } class GroupsData extends ChangeNotifier { /// Stores the formed group of [selectedGroup], [selectedCourse] /// and [selectedGroupNumber] String formedGroup = '00.00.00.00'; /// Stores user picked group in [ChooseGroupUI] /// In the final case, it is converted to the group identification /// /// e.x: **09.02.01**-1-18 String selectedGroup = getGroupsNames.first; /// Stores user picked course (1-4) in [ChooseGroupUI]. /// In the final case, it is converted to the year of admission to study /// /// e.x: 09.02.01-1-**18** String selectedCourse = getCoursesNumbers.first; /// Stores user picked group number (1-2) in [ChooseGroupUI] /// /// e.x: 09.02.01-**1**-18 String selectedGroupNumber = getGroupNumbers.first; /// Determines whether the form of study is accelerated or not. /// /// e.x: 13.02.09-1-21**у** bool isAccelerated = false; /// controls whether the save button is enabled or not. /// Updated by the [checkSaveButtonAvailable] method bool isSaveButtonEnabled = false; /// Stores groups names and their number identification in key-value type. /// /// Key is a group name /// /// Value is a group number identification static final Map<String, String> _groups = { 'Выберите группу': '00.00.00.00', 'Компьютерные системы и комплексы': '09.02.01', 'Электрические станции, сети и системы': '13.02.03', 'Релейная защита и автоматизация электроэнергетических систем': '13.02.06', 'Электроснабжение (по отраслям)': '13.02.07', 'Монтаж и эксплуатация линий электропередачи': '13.02.09', 'Экономика и бухгалтерский учет (по отраслям)': '38.02.01', 'Гостиничное дело': '43.02.14', 'Банковское дело': '38.02.07', 'Коммерция (по отраслям)': '38.02.04', }; /// Returns a list of group names in [_groups] collection /// /// See more info: [selectedGroup] static List<String> get getGroupsNames { return _groups.keys.toList(); } /// Returns a generated list of courses (1-4) /// /// See more info: [selectedCourse] static List<String> get getCoursesNumbers { return List.generate(4, (index) => (index + 1).toString()); } /// Returns a generated list of group numbers (1-4) /// /// See more info: [selectedGroupNumber] static List<String> get getGroupNumbers { return List.generate(4, (index) => (index + 1).toString()); } /// Returns a number identification of given group name, if /// group not found, then returns search error static String findGroupIdentification(String group) { return _groups[group] ?? 'Группа не найдена'; } /// Updates data for forming a group, used in [ChooseGroupUI]. /// /// [value] can be [String] and [bool] depends on [ChangedType]. void onValueChanged( dynamic value, { required ChangedType type, }) { switch (type) { case ChangedType.groupName: selectedGroup = value; // value is a String break; case ChangedType.groupCourse: selectedCourse = value; // value is a String break; case ChangedType.groupNumber: selectedGroupNumber = value; // value is a String break; case ChangedType.accelerated: isAccelerated = value; // value is a bool break; } updateFormedGroup(); } /// Returns the last two digits of the year of admission of this course String calculateYear(String inputCourse) { DateTime now = DateTime.now(); // if month any until September, then year of admission // first course is prev, else this int year = now.month < 9 ? now.year : now.year + 1; // calculate year of admission of given course [inputCourse] year -= int.parse(inputCourse); return year.toString().substring(2); } /// Updates the formed group based on [selectedGroup], /// [selectedGroupNumber] and [selectedCourse] void updateFormedGroup() { String groupID = findGroupIdentification(selectedGroup); String groupYear = calculateYear(selectedCourse); String appendix = isAccelerated ? 'у' : ''; formedGroup = '$groupID-' '$selectedGroupNumber-' '$groupYear' '$appendix'; checkSaveButtonAvailable(); } /// Checks whether the "save" button is available for use. /// If the group is not selected, then it does not work void checkSaveButtonAvailable() { isSaveButtonEnabled = selectedGroup != getGroupsNames.first; notifyListeners(); } /// Saves formed group to Hive to future using in [ScheduleScreen] void saveFormedGroup(BuildContext context) { HiveHelper.saveValue( key: 'chosenGroup', value: formedGroup, ); // close modal dialog Navigator.pop(context); } } /// Used in [GroupsData.onValueChanged] method. /// /// [groupName] - the data in the name of the group has changed, /// /// [groupCourse] - the data in the course of the group has changed, /// /// [groupNumber] - the data in the number of the group has changed, /// /// [accelerated] - the data in the accelerated type of the group has changed, enum ChangedType { groupName, groupCourse, groupNumber, accelerated, }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/teachers/teachers_ui.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/models/teacher_model.dart'; import '/widgets/loading_indicator.dart'; import '../../utils/theme/theme.dart'; import 'teacher_card/teacher_card.dart'; import 'teachers_logic.dart'; class SearchBar extends StatelessWidget { const SearchBar({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return TextFormField( autofocus: true, textInputAction: TextInputAction.search, style: Theme.of(context).textTheme.headline3, decoration: InputDecoration( hintText: Provider.of<TeachersLogic>(context, listen: true).visibleTextMode, border: InputBorder.none, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none, contentPadding: EdgeInsets.zero, hintStyle: Theme.of(context) .textTheme .headline3! .copyWith(color: context.palette.mediumEmphasis), ), onChanged: (value) { Provider.of<TeachersLogic>(context, listen: false).search(value); }, ); } } class FilterChips extends StatelessWidget { const FilterChips({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( width: double.infinity, color: context.palette.levelOneSurface, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: Wrap( direction: Axis.horizontal, spacing: 4.0, children: [ ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('Фамилия'), labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<TeachersLogic>().currentMode == SearchMode.familyName ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, selected: context.watch<TeachersLogic>().currentMode == SearchMode.familyName, onSelected: (_) => Provider.of<TeachersLogic>(context, listen: false) .setMode(SearchMode.familyName), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('Имя'), labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<TeachersLogic>().currentMode == SearchMode.firstName ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, selected: context.watch<TeachersLogic>().currentMode == SearchMode.firstName, onSelected: (_) => Provider.of<TeachersLogic>(context, listen: false) .setMode(SearchMode.firstName), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('Отчество'), labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<TeachersLogic>().currentMode == SearchMode.secondaryName ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, selected: context.watch<TeachersLogic>().currentMode == SearchMode.secondaryName, onSelected: (_) => Provider.of<TeachersLogic>(context, listen: false) .setMode(SearchMode.secondaryName), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('Предметы'), labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<TeachersLogic>().currentMode == SearchMode.lesson ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, selected: context.watch<TeachersLogic>().currentMode == SearchMode.lesson, onSelected: (_) => Provider.of<TeachersLogic>(context, listen: false) .setMode(SearchMode.lesson), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('Кабинеты'), labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<TeachersLogic>().currentMode == SearchMode.cabinet ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, selected: context.watch<TeachersLogic>().currentMode == SearchMode.cabinet, onSelected: (_) => Provider.of<TeachersLogic>(context, listen: false) .setMode(SearchMode.cabinet), ), ], ), ), ), ); } } class BuildTeachersList extends StatelessWidget { const BuildTeachersList({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Expanded( child: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( stream: Provider.of<TeachersLogic>(context, listen: true).stream, builder: ( BuildContext context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot, ) { if (!snapshot.hasData) return const LoadingIndicator(); return SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: ListView.builder( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: snapshot.data!.docs.length, itemBuilder: (context, index) { return TeacherCard( teacher: TeacherModel.fromMap( snapshot.data!.docs[index].data(), snapshot.data!.docs[index].id, ), ); }, ), ); }, ), ); } } class EditModeFAB extends StatelessWidget { const EditModeFAB({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return FloatingActionButton( child: const Icon( Icons.add_outlined, size: 24.0, ), onPressed: () => TeachersLogicEditMode().openAddNewDialog(context), ); } } class AddNewTeacherDialogUI extends StatefulWidget { const AddNewTeacherDialogUI({Key? key}) : super(key: key); @override State<AddNewTeacherDialogUI> createState() => _AddNewTeacherDialogUIState(); } class _AddNewTeacherDialogUIState extends State<AddNewTeacherDialogUI> { TextEditingController firstName = TextEditingController(); TextEditingController familyName = TextEditingController(); TextEditingController secondaryName = TextEditingController(); TextEditingController cabinet = TextEditingController(); TextEditingController lessons = TextEditingController(); @override Widget build(BuildContext context) { return Column( children: [ TextFormField( controller: familyName, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Фамилия'), ), const SizedBox(height: 10), TextFormField( controller: firstName, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Имя'), ), const SizedBox(height: 10), TextFormField( controller: secondaryName, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Отчество'), ), const SizedBox(height: 10), TextFormField( controller: lessons, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Занятия'), ), const SizedBox(height: 10), TextFormField( controller: cabinet, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Кабинет'), ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: TextButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( onPressed: () { TeachersLogicEditMode().addNewTeacher(TeacherModel( firstName: firstName.text, familyName: familyName.text, secondaryName: secondaryName.text, cabinet: cabinet.text, lesson: lessons.text, )); Navigator.pop(context); }, child: const Text('Добавить'), ), ), ], ), ], ); } } class SearchButton extends StatefulWidget { const SearchButton({Key? key}) : super(key: key); @override State<SearchButton> createState() => _SearchButtonState(); } class _SearchButtonState extends State<SearchButton> { @override Widget build(BuildContext context) { return Consumer<TeachersLogic>( builder: (BuildContext context, value, Widget? child) { return IconButton( onPressed: () => value.toggleSearch(), icon: Icon(value.isSearchMode ? Icons.close_outlined : Icons.search_outlined), ); }, ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/teachers/teachers_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/screens/teachers/teachers_logic.dart'; import '/utils/theme_helper.dart'; import '../../utils/firebase_auth.dart'; import '../../widgets/system_bar_cover.dart'; import 'teachers_ui.dart'; class TeacherScreen extends StatefulWidget { const TeacherScreen({Key? key}) : super(key: key); @override State<TeacherScreen> createState() => _TeacherScreenState(); } class _TeacherScreenState extends State<TeacherScreen> with TickerProviderStateMixin { @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Consumer<TeachersLogic>( builder: (BuildContext context, value, Widget? child) { return Scaffold( extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), appBar: AppBar( title: AnimatedSwitcher( duration: const Duration(milliseconds: 300), child: value.isSearchMode ? const SearchBar() : Row( children: const <Widget>[ Text('Преподаватели'), ], ), ), actions: const <Widget>[SearchButton()], ), body: GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: Column( children: [ AnimatedSize( curve: Curves.fastOutSlowIn, duration: const Duration(milliseconds: 400), reverseDuration: const Duration(milliseconds: 400), child: value.isSearchMode ? const FilterChips() : const SizedBox( width: double.infinity, ), ), const BuildTeachersList(), ], ), ), floatingActionButton: AccountEditorMode().isEditorModeActive ? const EditModeFAB() : null, ); }, ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/teachers/teachers_logic.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '/models/teacher_model.dart'; import '/utils/utils.dart'; import 'teachers_ui.dart'; enum SearchMode { firstName, familyName, secondaryName, lesson, cabinet, } extension StringExtension on String { String capitalize() { return "${this[0].toUpperCase()}${substring(1)}"; } } class TeachersLogic extends ChangeNotifier { Stream<QuerySnapshot<Map<String, dynamic>>> stream = FirebaseFirestore .instance .collection('teacher_list') .orderBy('familyName') .snapshots(); SearchMode currentMode = SearchMode.familyName; String visibleTextMode = 'Искать среди фамилий'; String documentField = 'familyName'; bool isSearchMode = false; void toggleSearch() { isSearchMode = !isSearchMode; notifyListeners(); } void search(String searchText) { if (searchText.isNotEmpty) { String searchKey = searchText.capitalize(); FirebaseAnalytics.instance.logEvent(name: 'teacher_search', parameters: { 'search_key' : searchKey, }); stream = FirebaseFirestore.instance .collection('teacher_list') .where(documentField, isGreaterThanOrEqualTo: searchKey) .where(documentField, isLessThan: "$searchKey\uf8ff") .snapshots(); } else { stream = FirebaseFirestore.instance .collection('teacher_list') .orderBy('familyName') .snapshots(); } notifyListeners(); } void setMode(SearchMode mode) { currentMode = mode; setVisibleText(mode); FirebaseAnalytics.instance.logEvent(name: 'teachers_search_mode', parameters: { 'selected_mode' : mode.toString(), }); notifyListeners(); } void setVisibleText(SearchMode mode) { switch (mode) { case SearchMode.firstName: visibleTextMode = 'Искать среди имён'; documentField = 'firstName'; break; case SearchMode.familyName: visibleTextMode = 'Искать среди фамилий'; documentField = 'familyName'; break; case SearchMode.secondaryName: visibleTextMode = 'Искать среди отчеств'; documentField = 'secondaryName'; break; case SearchMode.lesson: visibleTextMode = 'Искать среди предметов'; documentField = 'lesson'; break; case SearchMode.cabinet: visibleTextMode = 'Искать среди кабинетов'; documentField = 'cabinet'; break; } } } class TeachersLogicEditMode { void openAddNewDialog(BuildContext context) { showRoundedModalSheet( context: context, title: 'Добавить преподавателя', child: const AddNewTeacherDialogUI(), ); } void addNewTeacher(TeacherModel model) { CollectionReference schedule = FirebaseFirestore.instance.collection('teacher_list'); int docID = DateTime.now().millisecondsSinceEpoch; schedule.doc(docID.toString()).set(model.toMap(docID)); } }
0
mirrored_repositories/vpec/lib/screens/teachers
mirrored_repositories/vpec/lib/screens/teachers/teacher_card/teacher_editormode_logic.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import '/models/teacher_model.dart'; import '/utils/utils.dart'; import '/widgets/confirm_delete_dialog.dart'; import 'teacher_editormode_ui.dart'; class TeacherEditorModeLogic { static void showEditDialog(BuildContext context, TeacherModel model) { showRoundedModalSheet( context: context, title: 'Редактировать преподавателя', child: EditTeacherDialogUI(model: model), ); } static void editTeacher(TeacherModel model) { CollectionReference teachers = FirebaseFirestore.instance.collection('teacher_list'); teachers.doc(model.id).set( model.toMap(int.parse(model.id!)), ); } static void showConfirmDeleteDialog(BuildContext context, String id) { Navigator.pop(context); showRoundedModalSheet( context: context, title: 'Подтвердите действие', child: DeleteDialogUI(onDelete: () => confirmDelete(id)), ); } static void confirmDelete(String id) { CollectionReference teachers = FirebaseFirestore.instance.collection('teacher_list'); teachers.doc(id).delete(); } }
0
mirrored_repositories/vpec/lib/screens/teachers
mirrored_repositories/vpec/lib/screens/teachers/teacher_card/teacher_card.dart
import 'package:flutter/material.dart'; import '/models/teacher_model.dart'; import '../../../utils/firebase_auth.dart'; import 'teacher_editormode_logic.dart'; class TeacherCard extends StatelessWidget { final TeacherModel teacher; const TeacherCard({Key? key, required this.teacher}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: GestureDetector( onDoubleTap: () { if (AccountEditorMode().isEditorModeActive) { TeacherEditorModeLogic.showEditDialog(context, teacher); } }, child: Card( child: Padding( padding: const EdgeInsets.all(14.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(bottom: 5.0), child: Text( teacher.fullName!, style: Theme.of(context).textTheme.headline4, ), ), Padding( padding: const EdgeInsets.only(bottom: 2.0), child: Text( teacher.lesson!, style: Theme.of(context).textTheme.bodyText1, ), ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Spacer(), if (teacher.cabinet != '') Text( "Кабинет ${teacher.cabinet}", style: Theme.of(context).textTheme.subtitle1, ), ], ), ], ), ), ), ), ); } }
0
mirrored_repositories/vpec/lib/screens/teachers
mirrored_repositories/vpec/lib/screens/teachers/teacher_card/teacher_editormode_ui.dart
import 'package:flutter/material.dart'; import '/models/teacher_model.dart'; import 'teacher_editormode_logic.dart'; class EditTeacherDialogUI extends StatefulWidget { final TeacherModel model; const EditTeacherDialogUI({Key? key, required this.model}) : super(key: key); @override State<EditTeacherDialogUI> createState() => _EditTeacherDialogUIState(); } class _EditTeacherDialogUIState extends State<EditTeacherDialogUI> { TextEditingController firstName = TextEditingController(); TextEditingController familyName = TextEditingController(); TextEditingController secondaryName = TextEditingController(); TextEditingController cabinet = TextEditingController(); TextEditingController lessons = TextEditingController(); @override void initState() { firstName.text = widget.model.firstName!; familyName.text = widget.model.familyName!; secondaryName.text = widget.model.secondaryName!; cabinet.text = widget.model.cabinet!; lessons.text = widget.model.lesson!; super.initState(); } @override Widget build(BuildContext context) { return Column( children: [ TextFormField( controller: familyName, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Фамилия'), ), const SizedBox(height: 10), TextFormField( controller: firstName, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Имя'), ), const SizedBox(height: 10), TextFormField( controller: secondaryName, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Отчество'), ), const SizedBox(height: 10), TextFormField( controller: lessons, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Занятия'), ), const SizedBox(height: 10), TextFormField( controller: cabinet, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline3, decoration: const InputDecoration(labelText: 'Кабинет'), ), const SizedBox(height: 10), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () { TeacherEditorModeLogic.editTeacher(TeacherModel( firstName: firstName.text, familyName: familyName.text, secondaryName: secondaryName.text, cabinet: cabinet.text, lesson: lessons.text, id: widget.model.id, )); Navigator.pop(context); }, child: const Text('Редактировать'), ), ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ Expanded( child: TextButton( onPressed: () => TeacherEditorModeLogic.showConfirmDeleteDialog( context, widget.model.id!, ), child: const Text('Удалить'), ), ), const SizedBox(width: 10), Expanded( child: OutlinedButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), ], ), ], ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/scanner/scanner_screen.dart
import 'package:flutter/material.dart'; import '../../utils/theme_helper.dart'; import '../../widgets/system_bar_cover.dart'; import 'scanner_ui.dart'; class ScannerScreen extends StatelessWidget { const ScannerScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Scaffold( appBar: AppBar( title: const Text('Отсканируйте QR для входа'), ), extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), body: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: const [ ScannerWidget(), ManualLoginPrompt(), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/scanner/scanner_ui.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:mobile_scanner/mobile_scanner.dart'; import '/screens/login/login_logic.dart'; class ManualLoginPrompt extends StatelessWidget { const ManualLoginPrompt({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(16), child: Column( children: [ Text('или', style: Theme.of(context).textTheme.subtitle1), const SizedBox(height: 10), OutlinedButton( child: const Text( 'Введите данные вручную', style: TextStyle(fontSize: 16), ), onPressed: () => LoginLogic.openLogin(context), ), ], ), ); } } class ScannerWidget extends StatefulWidget { const ScannerWidget({ super.key, }); // formatted as https://example.com/ static const String domainAddress = 'https://energocollege.web.app/'; @override State<ScannerWidget> createState() => _ScannerWidgetState(); } class _ScannerWidgetState extends State<ScannerWidget> { bool didFindQr = false; @override Widget build(BuildContext context) { return Expanded( child: Stack( alignment: Alignment.center, children: [ MobileScanner( onDetect: (barcode, _) { if (didFindQr) return; if (barcode.type == BarcodeType.url) { String url = barcode.url!.url!; if (url.startsWith(ScannerWidget.domainAddress)) { didFindQr = true; FirebaseAnalytics.instance.logEvent(name: 'login_by_qr', parameters: { 'url': url, }); Navigator.pushNamed( context, url.replaceFirst(ScannerWidget.domainAddress, '/'), ); } } }, ), ColorFiltered( colorFilter: const ColorFilter.mode( Colors.black54, BlendMode.srcOut, ), child: Stack( fit: StackFit.expand, children: [ const DecoratedBox( decoration: BoxDecoration( color: Colors.black, backgroundBlendMode: BlendMode.dstOut, ), ), Center( child: SizedBox.square( dimension: MediaQuery.of(context).size.shortestSide * 0.6, child: const DecoratedBox( decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.all(Radius.circular(20)), ), ), ), ), ], ), ), SizedBox.square( dimension: MediaQuery.of(context).size.shortestSide * 0.6, child: DecoratedBox( decoration: BoxDecoration( border: Border.all(width: 4, color: Colors.white), borderRadius: const BorderRadius.all(Radius.circular(20)), ), ), ), ], ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/about_app/about_app_ui.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '/utils/icons.dart'; import '/utils/utils.dart'; import '/widgets/styled_widgets.dart'; import '../../utils/theme/theme.dart'; class AboutDeveloperCard extends StatelessWidget { final String name, post, nickname; final String? vkUrl, tgUrl; const AboutDeveloperCard({ Key? key, required this.name, required this.post, required this.nickname, this.vkUrl, this.tgUrl, }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ StyledListTile(title: name, subtitle: post), Padding( padding: const EdgeInsets.only(bottom: 8.0, right: 8.0, left: 18.0), child: Row( children: [ Text( nickname, style: Theme.of(context).textTheme.subtitle1, ), const Spacer(), if (vkUrl != null) IconButton( tooltip: 'Открыть страницу в VK', icon: Icon( VpecIconPack.vk, size: 32, color: context.palette.accentColor, ), onPressed: () { FirebaseAnalytics.instance.logEvent(name: 'developer_vk_opened', parameters: { 'url': vkUrl, }); openUrl(vkUrl!); }, ), if (tgUrl != null) IconButton( tooltip: 'Открыть страницу в Telegram', icon: Icon( VpecIconPack.telegram, size: 32, color: context.palette.accentColor, ), onPressed: () { FirebaseAnalytics.instance.logEvent(name: 'developer_tg_opened', parameters: { 'url': tgUrl, }); openUrl(tgUrl!); }, ), ], ), ), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/about_app/about_app_screen.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '/utils/utils.dart'; import '/widgets/styled_widgets.dart'; import 'about_app_ui.dart'; class AboutAppScreen extends StatelessWidget { const AboutAppScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('О приложении'), ), body: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Wrap( children: [ StyledListTile( icon: Icon( Icons.favorite_border_outlined, color: Theme.of(context).colorScheme.error, size: 32, ), title: 'Разработано студентами колледжа', subtitle: 'в рамках дипломного проекта', ), const AboutDeveloperCard( nickname: 'Tembeon', name: 'Рафиков Артур', post: 'Старший разработчик', vkUrl: 'https://vk.com/id504890843', tgUrl: 'https://t.me/tembeon', ), const AboutDeveloperCard( nickname: 'Lazurit11', name: 'Гордеев Владислав', post: 'Младший разработчик, UI/UX дизайнер', vkUrl: 'https://vk.com/id187849966', tgUrl: 'https://t.me/lazurit11', ), const Divider(), StyledListTile( title: 'Исходный код приложения', subtitle: 'Нажмите, чтобы открыть GitHub', onTap: () { FirebaseAnalytics.instance.logEvent(name: 'developer_group_opened'); openUrl('https://github.com/ShyroTeam/vpec'); }, ), StyledListTile( title: 'Лицензии библиотек', subtitle: 'Нажмите, чтобы открыть список лицензий', onTap: () { FirebaseAnalytics.instance.logEvent(name: 'developer_licenses_opened'); showLicensePage( context: context, applicationName: 'ВЭК', applicationLegalese: 'Создано для студентов и работников ' 'Волгоградского энергетического колледжа', ); }, ), ], ), ), ); } }
0
mirrored_repositories/whatsapp_clone
mirrored_repositories/whatsapp_clone/lib/random_image.dart
import 'package:flutter/material.dart'; ImageProvider randomImageUrl() { return AssetImage('assets/150x150.png'); }
0
mirrored_repositories/whatsapp_clone
mirrored_repositories/whatsapp_clone/lib/main.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/WhatsAppHome.dart'; import 'package:google_fonts/google_fonts.dart'; Future<void> main() async { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: "WhatApp" , theme: new ThemeData( backgroundColor: Color(0xff075E54), primaryColor: Color(0xff075E54), indicatorColor: Colors.white, primaryColorDark: Color(0xFF128C7E), accentColor: Color.fromRGBO(37 ,211, 102,-240), //cardColor: Color.fromRGBO(18, 140, 126,-240), fontFamily: GoogleFonts.lato().fontFamily, primaryIconTheme: IconThemeData( color: Colors.white, ), ), home: WhatsAppHome(), debugShowCheckedModeBanner: false, debugShowMaterialGrid: false, ); } }
0
mirrored_repositories/whatsapp_clone
mirrored_repositories/whatsapp_clone/lib/WhatsAppHome.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Model/FAB_remake.dart'; import 'package:whatsapp_clone/Model/Popup_menu.dart'; import 'Pages/Calls_screen.dart'; import 'Pages/Camera_screen.dart'; import 'Pages/Chat_screen.dart'; import 'Pages/Status.dart'; class WhatsAppHome extends StatefulWidget { @override _WhatsAppHomeState createState() => _WhatsAppHomeState(); } class _WhatsAppHomeState extends State<WhatsAppHome> with SingleTickerProviderStateMixin { TabController _tabController; _handleTabIndex() { setState(() {}); } @override void initState() { super.initState(); _tabController = new TabController(length: 4, vsync: this, initialIndex: 1); _tabController.animation.addListener(_handleTabIndex); } @override void dispose() { _tabController.animation.removeListener(_handleTabIndex); _tabController.dispose(); super.dispose(); } Widget build(BuildContext context) { final int _cameraTapIndex = 0; return Scaffold( appBar: AppBar( title: Text("WhatsApp"), elevation: 0.7, bottom: TabBar( controller: _tabController, indicatorColor: Colors.white, tabs: [ Tab(icon: Icon(Icons.camera_alt)), Tab( text: "CHATS", ), Tab( text: "STATUS", ), Tab( text: "CALLS", ), ], ), actions: <Widget>[ IconButton(icon: Icon(Icons.search), onPressed: () {}), // IconButton(icon: Icon(Icons.more_vert), onPressed: () {}), popupMenuButton(), ], ), body: TabBarView( controller: _tabController, children: <Widget>[ WillPopScope( // ignore: missing_return onWillPop: () { // shift to the right-handed-side tap; _tabController.animateTo(_cameraTapIndex + 1); }, child: CameraScreen(), ), ChatScreen(), StatusScreen(), CallScreen(), ], ), floatingActionButton: buildFloatingActionButton(context, _tabController), ); } } // ignore: camel_case_types // class Floating_button extends StatelessWidget { // const Floating_button({ // Key key, // }) : super(key: key); // @override // Widget build(BuildContext context) { // return FloatingActionButton( // backgroundColor: Theme.of(context).accentColor, // child: Icon( // Icons.message_outlined, // color: Colors.white, // ), // onPressed: () => print("Open Chats"), // ); // } // }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Pages/Camera_screen.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Model/Camera_Model.dart'; class CameraScreen extends StatelessWidget { @override Widget build(BuildContext context) { return CameraApp(); } }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Pages/Calls_screen.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Model/Call_model.dart'; class CallScreen extends StatelessWidget { @override Widget build(BuildContext context) { return ListView.builder( itemCount: calldata.length, itemBuilder: (context, i) => Column( children: [ Divider( height: 10.0, indent: 75.0, endIndent: 10, ), ListTile( onTap: () {}, leading: CircleAvatar( foregroundColor: Theme.of(context).primaryColor, backgroundColor: Colors.grey, backgroundImage: AssetImage(calldata[i].avatar), radius: 25, ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( calldata[i].name, style: TextStyle(fontWeight: FontWeight.bold), ), calldata[i].ucon ], ), subtitle: Container( padding: const EdgeInsets.only(top: 5.0), child: Text( calldata[i].date, style: TextStyle(fontWeight: FontWeight.bold), ), ), ) ], )); } }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Pages/Status.dart
import 'package:flutter/material.dart'; const listLeadingAvatarRadius = 25.0; final imagedp = "assets/images/dp.jpg"; class StatusScreen extends StatelessWidget { @override Widget build(BuildContext context) { return ListView.builder( itemCount: 1, itemBuilder: (context, index) { return ListTile( leading: Stack( children: [ CircleAvatar( radius: listLeadingAvatarRadius, backgroundImage: AssetImage(imagedp)), Positioned( right: 0.0, bottom: 0.0, child: CircleAvatar( radius: 10.0, backgroundColor: Theme.of(context).primaryColor, child: Icon( Icons.add, size: 20.0, color: Colors.white, ),) ) ], ), title: Text('My status'), subtitle: Text('Tap to add status update'), ); }); } }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Pages/Chat_screen.dart
import 'package:flutter/material.dart'; import '../Model/Chat_Model.dart'; class ChatScreen extends StatefulWidget { @override _ChatScreenState createState() => _ChatScreenState(); } class _ChatScreenState extends State<ChatScreen> { @override Widget build(BuildContext context) { return ListView.builder( itemCount: dummyData.length, itemBuilder: (context, i) => Column( children: [ Divider( height: 10.0, indent: 75.0, endIndent: 10, ), ListTile( onTap: () {}, leading: CircleAvatar( foregroundColor: Theme.of(context).primaryColor, backgroundColor: Colors.grey, backgroundImage: AssetImage(dummyData[i] .avatarUrl), //asset image for offline and network image for online radius: 25, ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( dummyData[i].name, style: TextStyle(fontWeight: FontWeight.bold), ), Text( dummyData[i].time, style: TextStyle(color: Colors.grey, fontSize: 15.0), ) ], ), subtitle: Container( padding: const EdgeInsets.only(top: 5.0), child: Text( dummyData[i].message, style: TextStyle(fontWeight: FontWeight.bold), ), ), ) ], ), ); } }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/SelContact.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Pages/Chat_screen.dart'; class SelectContact extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Select Contact'), actions: <Widget>[ IconButton( icon: Icon(Icons.search), onPressed: () {}, ), IconButton( icon: Icon(Icons.more_vert), onPressed: () {}, ), ], ), body: ListView.builder( itemBuilder: (context, index) { return ListTile( leading: CircleAvatar( child: Icon(Icons.person), ), title: Text('contact $index'), subtitle: Text('contact $index\'s status...'), onTap: () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute(builder: (context) { return ChatScreen(); })); }, ); }, ), ); } }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/Chat_Model.dart
class ChatModel { final String name; final String message; final String time; final String avatarUrl; ChatModel({this.name, this.message, this.time, this.avatarUrl}); } List<ChatModel> dummyData = [ ChatModel( name: "Virus", message: "Life is A Race", time: "12:00 pm", avatarUrl: "assets/images/virus.jpg", ), ChatModel( name: "Raju", message: "Bhai Naukri lag gyi meri", time: "11:00 am", avatarUrl: "assets/images/raju.jpg", ), ChatModel( name: "Farhan", message: "Abba Nhi Maan Rhe Yaar", time: "10:32 am", avatarUrl: "assets/images/farhan.jpg", ), ChatModel( name: "Chatur", message: "Jitna hasna hai has le", time: "10:15 am", avatarUrl: "assets/images/chatur.jpg", ), ChatModel( name: "Rancho", message: "Aal is Well", time: "10:00 am", avatarUrl: "assets/images/rancho.jpg", ), ChatModel( name: "Interviewer", message: "Salary Discuss karein", time: "09:30 am", avatarUrl: "assets/images/interviewer.jpg", ), ChatModel( name: "Pia", message: "Ghadi Chori ho gyi meri", time: "09:00 am", avatarUrl: "assets/images/priya.jpg", ), ChatModel( name: "Millimeter", message: "Bhaiya Uniform ke paise de do", time: "8:50 am", avatarUrl: "assets/images/mm.jpg", ), ChatModel( name: "Librarian", message: "Agli baar mil tu mujhe", time: "8:00 am", avatarUrl: "assets/images/lib.jpg", ), ChatModel( name: "Joy Lobo", message: "Give Me Some Sunshine", time: "04:30 am", avatarUrl: "assets/images/ss.jpg", ), ];
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/Popup_menu.dart
import 'package:flutter/material.dart'; Widget popupMenuButton() { return PopupMenuButton<String>( icon: Icon(Icons.more_vert), itemBuilder: (BuildContext context )=><PopupMenuEntry<String>>[ PopupMenuItem<String>( value:"1", child: Text("New group"), ), PopupMenuItem<String>( value:"2", child: Text("New broadcast"), ), PopupMenuItem<String>( value:"3", child: Text("WhatsApp Web"), ), PopupMenuItem<String>( value:"4", child: Text("Starred messages"), ), PopupMenuItem<String>( value:"5", child: Text("Payments"), ), PopupMenuItem<String>( value:"6", child: Text("Settings"), ) ], ); }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/FAB_remake.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Model/Camera_Model.dart'; import 'Contacts.dart'; import 'SelContact.dart'; bool getIsTabCamera(TabController tabController) { return tabController.animation.value < 0.7; } bool getIsChatList(TabController tabController) { return tabController.animation.value > 0.7 && tabController.animation.value < 1.7; } bool getIsStatusList(TabController tabController) { return tabController.animation.value > 1.7 && tabController.animation.value < 2.7; } bool getIsCallList(TabController tabController) { return tabController.animation.value > 2.7; } buildFloatingActionButton(BuildContext context, TabController tabController) { if (getIsChatList(tabController)) { return FloatingActionButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute(builder: (_) { return SelectContact(); })); }, child: Icon( Icons.message_rounded, color: Colors.white, ), ); } else if (getIsStatusList(tabController)) { return FloatingActionButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute(builder: (_) { return CameraApp(); })); }, child: Icon( Icons.camera_alt, ), ); } else if (getIsCallList(tabController)) { return FloatingActionButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute(builder: (_) { return SelectCallContact(); })); }, child: Icon( Icons.add_call, ), ); } return null; }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/Call_model.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class CallModel { final String name; final String date; final String avatar; final Icon ucon; CallModel({this.name, this.date, this.avatar,this.ucon}); } List<CallModel> calldata = [ CallModel( name: "Virus", date: "21 April, 8:15 am", avatar: "assets/images/virus.jpg", ucon: Icon(Icons.videocam,color: Color.fromRGBO(18, 140, 126,-240),), ), CallModel( name: "Millimeter", date: "21 April, 6:15 am", avatar: "assets/images/mm.jpg", ucon: Icon(Icons.call,color: Color.fromRGBO(18, 140, 126,-240),), ), CallModel( name: "Raju", date: "20 April, 2:18 pm", avatar: "assets/images/raju.jpg", ucon: Icon(Icons.videocam,color: Color.fromRGBO(18, 140, 126,-240),), ), CallModel( name: "Farhan", date: "19 April, 7:09 pm", avatar: "assets/images/farhan.jpg", ucon: Icon(Icons.call,color: Color.fromRGBO(18, 140, 126,-240),), ), CallModel( name: "Chatur", date: "15 April, 8:30 pm", avatar: "assets/images/chatur.jpg", ucon: Icon(Icons.call,color: Color.fromRGBO(18, 140, 126,-240),), ), CallModel( name: "Rancho", date: "11 April, 1:25 am", avatar: "assets/images/rancho.jpg", ucon: Icon(Icons.videocam,color: Color.fromRGBO(18, 140, 126,-240),), ), CallModel( name: "Pia", date: "1 April, 2:37 am", avatar: "assets/images/priya.jpg", ucon: Icon(Icons.videocam,color: Color.fromRGBO(18, 140, 126,-240),), ), ];
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/Camera_Model.dart
import 'package:camera_camera/camera_camera.dart'; import 'package:flutter/material.dart'; class CameraApp extends StatefulWidget { @override _CameraAppState createState() => _CameraAppState(); } class _CameraAppState extends State<CameraApp> { @override Widget build(BuildContext context) { return CameraCamera(onFile: (file) => print(file)); } }
0
mirrored_repositories/whatsapp_clone/lib
mirrored_repositories/whatsapp_clone/lib/Model/Contacts.dart
import 'package:flutter/material.dart'; class SelectCallContact extends StatelessWidget { @override Widget build(BuildContext context) { final listview = ListView.builder( itemBuilder: (context, index) { if (index == 0) { return ListTile( leading: CircleAvatar( child: Icon( Icons.people, color: Theme.of(context).iconTheme.color, ), backgroundColor: Theme.of(context).accentColor, ), title: Text('New group call'), ); } else if (index == 1) { return ListTile( leading: CircleAvatar( child: Icon( Icons.person_add, color: Theme.of(context).iconTheme.color, ), backgroundColor: Theme.of(context).accentColor, ), title: Text('New contact'), ); } return ListTile( leading: CircleAvatar( child: Icon(Icons.person), ), title: Text('Contact $index'), subtitle: Text('Contact $index status...'), trailing: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ IconButton( onPressed: () {}, icon: Icon(Icons.phone), ), IconButton( onPressed: () {}, icon: Icon(Icons.videocam), ), ], ), ); }, ); return Scaffold( appBar: AppBar( title: Text('Select Contact'), actions: <Widget>[ IconButton( icon: Icon(Icons.search), onPressed: () {}, ), IconButton( icon: Icon(Icons.more_vert), onPressed: () {}, ), ], ), body: listview, ); } }
0
mirrored_repositories/whatsapp_clone
mirrored_repositories/whatsapp_clone/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:whatsapp_clone/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/gesture_handlers
mirrored_repositories/gesture_handlers/lib/gesture_handlers.dart
library gesture_handlers; export 'src/gesture_handler.dart'; export 'src/gesture_handlers/any_tap_handler.dart'; export 'src/gesture_handlers/swipe_handler.dart'; export 'src/gesture_handlers/tap_handler.dart'; export 'src/gesture_navigation/gesture_bottom_sheet.dart'; export 'src/gesture_navigation/gesture_route_delegate.dart'; export 'src/gesture_navigation/gesture_route_transition_mixin.dart'; export 'src/gesture_navigation/gesture_routes.dart'; export 'src/gesture_navigation/navigator_gesture_recognizer.dart'; export 'src/gesture_navigation/swipe_gesture_transition.dart'; export 'src/gesture_navigation/swipe_route_handler.dart'; export 'src/gestures_binding.dart';
0
mirrored_repositories/gesture_handlers/lib
mirrored_repositories/gesture_handlers/lib/src/gesture_handler.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; class GestureListener extends StatefulWidget { final GestureHandler handler; final Widget child; final HitTestBehavior? behavior; final bool excludeFromSemantics; const GestureListener({ Key? key, required this.handler, required this.child, this.behavior, this.excludeFromSemantics = false, }) : super(key: key); @override State<GestureListener> createState() => _GestureListenerState(); } class _GestureListenerState extends State<GestureListener> { late Map<Type, GestureRecognizerFactory<GestureRecognizer>> gestures; @override void initState() { super.initState(); initGestures(); } @override void didUpdateWidget(covariant GestureListener oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.handler != widget.handler) { // if (oldWidget.disposeHandler) oldWidget.handler.dispose(); initGestures(); } } @override void dispose() { // if (widget.disposeHandler) widget.handler.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return RawGestureDetector( gestures: gestures, behavior: widget.behavior, excludeFromSemantics: widget.excludeFromSemantics, child: widget.child, ); } void initGestures() { gestures = widget.handler.recognizerFactories(); } } typedef RecognizerFactories = Map<Type, GestureRecognizerFactory>; abstract class GestureHandler { const GestureHandler(); // TODO: refactor? RecognizerFactories recognizerFactories(); @mustCallSuper void dispose() {} } mixin GestureHandlerComposerMixin on GestureHandler { List<GestureHandler> get handlers; @override RecognizerFactories recognizerFactories() { final recognizer = <Type, GestureRecognizerFactory>{}; for (final h in handlers) { final types = h.recognizerFactories(); for (final type in types.keys) { assert(!recognizer.containsKey(type), 'GestureRecognizerFactory of type $type already registered. Remove handler with this type or use another GestureHandlerComposer.'); recognizer[type] = types[type]!; } } return recognizer; } @override void dispose() { for (final i in handlers) { i.dispose(); } super.dispose(); } } class GestureHandlerComposer extends GestureHandler with GestureHandlerComposerMixin { @override final List<GestureHandler> handlers; const GestureHandlerComposer({required this.handlers}); } mixin AnimationGestureMixin on GestureHandler { double get value; set value(double value); double get lowerBound => 0.0; double get upperBound => 1.0; bool get isAtMin => value <= lowerBound; bool get isAtMax => value >= upperBound; bool get reverse => false; void reverseProgress(); void forwardProgress(); } mixin AnimationControllerGestureMixin implements AnimationGestureMixin { AnimationController get controller; @override double get value => controller.value; @override set value(double value) => controller.value = value; @override double get lowerBound => controller.lowerBound; @override double get upperBound => controller.upperBound; @override void reverseProgress() => controller.reverse(); @override void forwardProgress() => controller.forward(); } mixin DeactivatableGestureHandlerMixin on GestureHandler { bool get isDeactivated; // TODO: refactor @protected void onlyIfActivated<T>(Function callback, [List? args, Map<Symbol, dynamic>? kwargs]) { if (isDeactivated) return; Function.apply(callback, args, kwargs); } }
0
mirrored_repositories/gesture_handlers/lib
mirrored_repositories/gesture_handlers/lib/src/gestures_binding.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; /// Prints information about preventing cancel pointer with [GestureBinding.cancelPointer]. /// /// This flag only has an effect in debug mode. bool debugPrintPreventCancelPointer = false; /// [GestureBinding] implementation for prevent route [GestureHandler] active pointers canceling by [NavigatorState]. /// /// [NavigatorState] cancel active pointers after navigation. mixin NavigatorGesturesBinding on GestureBinding { final Map<int, int> _preventFromCancelPointers = {}; int get _preventedCounts => _preventFromCancelPointers.length; void preventPointerFromCancel(int pointer, [GestureRecognizer? recognizer]) { final prevents = (_preventFromCancelPointers[pointer] ?? 0) + 1; _preventFromCancelPointers[pointer] = prevents; assert(() { if (debugPrintPreventCancelPointer) { _debugLogDiagnostic( '${recognizer ?? ''} \npreventPointerFromCancel($pointer), prevented counts: $_preventedCounts.'); } return true; }()); } void removePointerFromCancelPrevent(int pointer, [GestureRecognizer? recognizer]) { final prevents = (_preventFromCancelPointers[pointer] ?? 0) - 1; if (prevents <= 0) { _preventFromCancelPointers.remove(pointer); } else { _preventFromCancelPointers[pointer] = prevents; } assert(() { if (debugPrintPreventCancelPointer) { _debugLogDiagnostic( '${recognizer ?? ''} \nremovePointerFromCancelPrevent($pointer), prevented counts: $_preventedCounts.'); } return true; }()); } @override void cancelPointer(int pointer) { if (_preventFromCancelPointers.containsKey(pointer)) { assert(() { if (debugPrintPreventCancelPointer) { _debugLogDiagnostic('pointer: $pointer prevented from canceling.'); } return true; }()); return; } super.cancelPointer(pointer); } } /// A concrete binding for applications based on the Widgets framework. /// /// This is the glue that binds the framework to the Flutter engine. class NavigatorGesturesFlutterBinding extends WidgetsFlutterBinding with NavigatorGesturesBinding { /// Returns an instance of the [WidgetsBinding], creating and /// initializing it if necessary. If one is created, it will be a /// [NavigatorGesturesFlutterBinding]. If one was previously initialized, then /// it will at least implement [WidgetsBinding]. /// /// You only need to call this method if you need the binding to be /// initialized before calling [runApp]. /// /// In the `flutter_test` framework, [testWidgets] initializes the /// binding instance to a [TestWidgetsFlutterBinding], not a /// [NavigatorGesturesFlutterBinding]. static WidgetsBinding ensureInitialized() { if (WidgetsBinding.instance == null) NavigatorGesturesFlutterBinding(); return WidgetsBinding.instance!; } } bool _debugLogDiagnostic(String message) { assert(() { debugPrint('[NavigatorGesturesBinding]: $message'); return true; }()); return true; }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_handlers/tap_handler.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import '../gesture_handler.dart'; abstract class TapHandler extends GestureHandler { const TapHandler(); @override RecognizerFactories recognizerFactories() { return { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( () => TapGestureRecognizer(debugOwner: this), initializeTapGestureRecognizer), }; } void initializeTapGestureRecognizer(TapGestureRecognizer instance); } class TapHandlerDelegate extends TapHandler { const TapHandlerDelegate({ this.onTapDown, this.onTapUp, this.onTap, this.onTapCancel, this.onSecondaryTap, this.onSecondaryTapDown, this.onSecondaryTapUp, this.onSecondaryTapCancel, this.onTertiaryTapDown, this.onTertiaryTapUp, this.onTertiaryTapCancel, }) : assert(onTapDown != null || onTapUp != null || onTap != null || onTapCancel != null || onSecondaryTap != null || onSecondaryTapDown != null || onSecondaryTapUp != null || onSecondaryTapCancel != null || onTertiaryTapDown != null || onTertiaryTapUp != null || onTertiaryTapCancel != null); @override void initializeTapGestureRecognizer(TapGestureRecognizer instance) { instance ..onTapDown = onTapDown ..onTapUp = onTapUp ..onTap = onTap ..onTapCancel = onTapCancel ..onSecondaryTap = onSecondaryTap ..onSecondaryTapDown = onSecondaryTapDown ..onSecondaryTapUp = onSecondaryTapUp ..onSecondaryTapCancel = onSecondaryTapCancel ..onTertiaryTapDown = onTertiaryTapDown ..onTertiaryTapUp = onTertiaryTapUp ..onTertiaryTapCancel = onTertiaryTapCancel; } final GestureTapDownCallback? onTapDown; final GestureTapUpCallback? onTapUp; final GestureTapCallback? onTap; final GestureTapCancelCallback? onTapCancel; final GestureTapCallback? onSecondaryTap; final GestureTapDownCallback? onSecondaryTapDown; final GestureTapUpCallback? onSecondaryTapUp; final GestureTapCancelCallback? onSecondaryTapCancel; final GestureTapDownCallback? onTertiaryTapDown; final GestureTapUpCallback? onTertiaryTapUp; final GestureTapCancelCallback? onTertiaryTapCancel; }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_handlers/swipe_handler.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import '../gesture_handler.dart'; import '../gesture_navigation/navigator_gesture_recognizer.dart'; enum DragDirection { horizontal, vertical, both } abstract class DragHandler extends GestureHandler { final DragDirection direction; final DragStartBehavior dragStartBehavior; DragHandler({required this.direction, this.dragStartBehavior = DragStartBehavior.start}); bool get handleHorizontal => direction != DragDirection.vertical; bool get handleVertical => direction != DragDirection.horizontal; @override RecognizerFactories recognizerFactories() { final recognizers = <Type, GestureRecognizerFactory>{}; if (handleHorizontal) { recognizers[HorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>( () => HorizontalDragGestureRecognizer(debugOwner: this), initializeDragGestureRecognizer); } if (handleVertical) { recognizers[VerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>( () => VerticalDragGestureRecognizer(debugOwner: this), initializeDragGestureRecognizer); } return recognizers; } void initializeDragGestureRecognizer(DragGestureRecognizer instance); } class DragHandlerDelegate extends DragHandler { DragHandlerDelegate({ required DragDirection direction, this.onDragDown, this.onDragStart, this.onDragUpdate, this.onDragEnd, this.onDragCancel, DragStartBehavior dragStartBehavior = DragStartBehavior.start, }) : super(direction: direction, dragStartBehavior: dragStartBehavior); @override void initializeDragGestureRecognizer(DragGestureRecognizer instance) { instance ..onDown = onDragDown ..onStart = onDragStart ..onUpdate = onDragUpdate ..onEnd = onDragEnd ..onCancel = onDragCancel ..dragStartBehavior = dragStartBehavior; } final GestureDragDownCallback? onDragDown; final GestureDragStartCallback? onDragStart; final GestureDragUpdateCallback? onDragUpdate; final GestureDragEndCallback? onDragEnd; final GestureDragCancelCallback? onDragCancel; } abstract class SwipeHandler extends DragHandler with DeactivatableGestureHandlerMixin { SwipeHandler({ required DragDirection direction, DragStartBehavior dragStartBehavior = DragStartBehavior.start, }) : super(direction: direction, dragStartBehavior: dragStartBehavior); @override bool get isDeactivated => false; @override void initializeDragGestureRecognizer(DragGestureRecognizer instance) { instance ..onDown = ((e) => onlyIfActivated(onDragDown, [e])) ..onStart = ((e) => onlyIfActivated(onDragStart, [e])) ..onUpdate = ((e) => onlyIfActivated(onDragUpdate, [e])) ..onEnd = ((e) => onlyIfActivated(onDragEnd, [e])) ..onCancel = (() => onlyIfActivated(onDragCancel)) ..dragStartBehavior = dragStartBehavior; } void onDragDown(DragDownDetails e) {} void onDragStart(DragStartDetails e) {} void onDragUpdate(DragUpdateDetails e) {} void onDragEnd(DragEndDetails e) {} void onDragCancel() {} } const kSwipeProgressThreshold = 0.5; const kSwipeFlingVelocity = 700.0; mixin AnimationSwipeHandlerMixin on SwipeHandler implements AnimationGestureMixin { double get minOpenFlingVelocity => kSwipeFlingVelocity; double get minCloseFlingVelocity => kSwipeFlingVelocity; double get openProgressThreshold => kSwipeProgressThreshold; double get closeProgressThreshold => kSwipeProgressThreshold; double get childSize; DragUpdateDetails? _lastUpdate; @override void onDragStart(DragStartDetails e) { _lastUpdate = null; } @override void onDragUpdate(DragUpdateDetails e) { _lastUpdate = e; final delta = e.primaryDelta! / childSize * (reverse ? -1.0 : 1.0); final newValue = (value + delta).clamp(lowerBound, upperBound); if (newValue == value) return; value = newValue; } @override void onDragEnd(DragEndDetails e) { final velocity = e.primaryVelocity! * (reverse ? -1.0 : 1.0); final minFlingVelocity = isForwardDirection(e, velocity) ? minOpenFlingVelocity : minCloseFlingVelocity; final progressThreshold = isForwardDirection(e, velocity) ? openProgressThreshold : closeProgressThreshold; if (velocity.abs() > minFlingVelocity) { if (!isAtMin && !isAtMax) flingVelocityAnimate(e, velocity); } else if (value < progressThreshold) { if (!isAtMin) reverseProgress(); } else { if (!isAtMax) forwardProgress(); } } bool isForwardDirection(DragEndDetails e, double velocity) { if (velocity != 0.0) return velocity > 0.0; if (_lastUpdate != null) return (_lastUpdate!.primaryDelta! * (reverse ? -1.0 : 1.0)) >= 0.0; return true; } void flingVelocityAnimate(DragEndDetails e, double velocity); @protected bool canAnimate(DragUpdateDetails e) { if (isDeactivated) return false; final delta = e.primaryDelta! * (reverse ? -1.0 : 1.0); return (delta > 0 && !isAtMax) || (delta < 0 && !isAtMin); } } mixin AnimationControllerSwipeHandlerMixin implements AnimationSwipeHandlerMixin, AnimationControllerGestureMixin { @override void flingVelocityAnimate(DragEndDetails e, double velocity) { final flingVelocity = velocity / childSize; controller.fling(velocity: flingVelocity); } @override void reverseProgress() => controller.reverse(); // or use controller.fling(velocity: -1.0); ? @override void forwardProgress() => controller.forward(); } class AnimationControllerSwipeHandler extends SwipeHandler with AnimationGestureMixin, AnimationControllerGestureMixin, AnimationSwipeHandlerMixin, AnimationControllerSwipeHandlerMixin { AnimationControllerSwipeHandler({ required this.controller, required this.getChildSize, this.openProgressThreshold = kSwipeProgressThreshold, this.closeProgressThreshold = kSwipeProgressThreshold, this.minOpenFlingVelocity = kSwipeFlingVelocity, this.minCloseFlingVelocity = kSwipeFlingVelocity, this.reverse = false, ValueGetter<bool>? isDeactivated, required DragDirection direction, DragStartBehavior dragStartBehavior = DragStartBehavior.start, }) : _isDeactivated = isDeactivated, super(direction: direction, dragStartBehavior: dragStartBehavior); @override final AnimationController controller; @override final double openProgressThreshold; @override final double closeProgressThreshold; @override final double minOpenFlingVelocity; @override final double minCloseFlingVelocity; @override final bool reverse; @override double get childSize => getChildSize(); final ValueGetter<double> getChildSize; @override bool get isDeactivated => _isDeactivated?.call() ?? false; final ValueGetter<bool>? _isDeactivated; } class CascadeSwipeHandler extends SwipeHandler { final List<AnimationSwipeHandlerMixin> handlers; final bool reverse; CascadeSwipeHandler({ required this.handlers, this.reverse = false, required DragDirection direction, DragStartBehavior dragStartBehavior = DragStartBehavior.start, }) : assert(handlers.every((i) => i.direction == direction)), super(direction: direction, dragStartBehavior: dragStartBehavior); @override RecognizerFactories recognizerFactories() { final recognizers = <Type, GestureRecognizerFactory>{}; if (handleHorizontal) { recognizers[RouteHorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<RouteHorizontalDragGestureRecognizer>( () => RouteHorizontalDragGestureRecognizer(debugOwner: this), initializeDragGestureRecognizer); } if (handleVertical) { recognizers[RouteVerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<RouteVerticalDragGestureRecognizer>( () => RouteVerticalDragGestureRecognizer(debugOwner: this), initializeDragGestureRecognizer); } return recognizers; } @override void dispose() { for (final i in handlers) { i.dispose(); } super.dispose(); } AnimationSwipeHandlerMixin? _activeHandler; @override void onDragDown(DragDownDetails e) => _activeHandler?.onDragDown(e); @override void onDragStart(DragStartDetails e) => _activeHandler?.onDragStart(e); @override void onDragUpdate(DragUpdateDetails e) { if (_activeHandler == null) _activeHandler = selectHandler(e); _activeHandler?.onDragUpdate(e); } @override void onDragEnd(DragEndDetails e) { _activeHandler?.onDragEnd(e); _activeHandler = null; } @override void onDragCancel() { _activeHandler?.onDragCancel(); _activeHandler = null; } AnimationSwipeHandlerMixin? selectHandler(DragUpdateDetails e) { if (handlers.isEmpty) return null; final delta = e.primaryDelta! * (reverse ? -1.0 : 1.0); if (delta == 0) return null; final items = delta > 0 ? handlers : handlers.reversed; for (final i in items) { if (canAnimate(i, e)) return i; } return null; } @protected bool canAnimate(AnimationSwipeHandlerMixin handler, DragUpdateDetails e) => handler.canAnimate(e); }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_handlers/any_tap_handler.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import '../gesture_handler.dart'; class AnyTapHandlerDelegate extends GestureHandler { const AnyTapHandlerDelegate({this.onAnyTapDown, this.onAnyTapUp}); final VoidCallback? onAnyTapDown; final VoidCallback? onAnyTapUp; @override RecognizerFactories recognizerFactories() { return { AnyTapGestureRecognizer: GestureRecognizerFactoryWithHandlers<AnyTapGestureRecognizer>( () => AnyTapGestureRecognizer(debugOwner: this), initializeAnyTapGestureRecognizer), }; } void initializeAnyTapGestureRecognizer(AnyTapGestureRecognizer instance) { instance.onAnyTapUp = onAnyTapUp; instance.onAnyTapDown = onAnyTapDown; } } /// Recognizes tap down by any pointer button. /// /// It is similar to [TapGestureRecognizer.onTapDown], but accepts any single /// button, which means the gesture also takes parts in gesture arenas. class AnyTapGestureRecognizer extends BaseTapGestureRecognizer { AnyTapGestureRecognizer({Object? debugOwner}) : super(debugOwner: debugOwner); VoidCallback? onAnyTapDown; VoidCallback? onAnyTapUp; @override bool isPointerAllowed(PointerDownEvent event) { if (onAnyTapDown == null && onAnyTapUp == null) return false; return super.isPointerAllowed(event); } @override void handleTapDown({PointerDownEvent? down}) { onAnyTapDown?.call(); } @override void handleTapUp({PointerDownEvent? down, PointerUpEvent? up}) { onAnyTapUp?.call(); } @override void handleTapCancel({PointerDownEvent? down, PointerCancelEvent? cancel, String? reason}) {} @override String get debugDescription => 'any tap'; }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/gesture_bottom_sheet.dart
import 'package:flutter/material.dart'; import 'gesture_route_delegate.dart'; import 'gesture_route_transition_mixin.dart'; import 'swipe_gesture_transition.dart'; import 'swipe_route_handler.dart'; const Duration _bottomSheetEnterDuration = Duration(milliseconds: 350); const Duration _bottomSheetExitDuration = Duration(milliseconds: 200); class GestureModalBottomSheetRoute<T> extends PopupRoute<T> with GestureRouteTransitionMixin<T> { GestureModalBottomSheetRoute({ required this.gestureDelegate, required this.builder, required this.capturedThemes, this.barrierLabel, this.backgroundColor, this.elevation, this.shape, this.clipBehavior, this.constraints, this.modalBarrierColor, this.isDismissible = true, RouteSettings? settings, }) : super(settings: settings); @override final GestureRouteDelegate gestureDelegate; final WidgetBuilder builder; final CapturedThemes capturedThemes; final Color? backgroundColor; final double? elevation; final ShapeBorder? shape; final Clip? clipBehavior; final BoxConstraints? constraints; final Color? modalBarrierColor; final bool isDismissible; @override Duration get transitionDuration => _bottomSheetEnterDuration; @override Duration get reverseTransitionDuration => _bottomSheetExitDuration; @override bool get barrierDismissible => isDismissible; @override final String? barrierLabel; @override Color get barrierColor => modalBarrierColor ?? Colors.black54; @override Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { // By definition, the bottom sheet is aligned to the bottom of the page // and isn't exposed to the top padding of the MediaQuery. final Widget bottomSheet = MediaQuery.removePadding( context: context, removeTop: true, child: Builder( builder: (BuildContext context) { final BottomSheetThemeData sheetTheme = Theme.of(context).bottomSheetTheme; return ModalBottomSheet<T>( route: this, backgroundColor: backgroundColor ?? sheetTheme.modalBackgroundColor ?? sheetTheme.backgroundColor, elevation: elevation ?? sheetTheme.modalElevation ?? sheetTheme.elevation, shape: shape, clipBehavior: clipBehavior, constraints: constraints, ); }, ), ); return capturedThemes.wrap(bottomSheet); } @override Widget buildPageTransitions( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return Align( alignment: Alignment.bottomCenter, child: SwipeGestureTransition(primaryRouteAnimation: animation, direction: kBottomTopTween, child: child), ); } } class ModalBottomSheet<T> extends StatefulWidget { const ModalBottomSheet({ Key? key, required this.route, this.backgroundColor, this.elevation, this.shape, this.clipBehavior, this.constraints, }) : super(key: key); final GestureModalBottomSheetRoute<T> route; final Color? backgroundColor; final double? elevation; final ShapeBorder? shape; final Clip? clipBehavior; final BoxConstraints? constraints; @override ModalBottomSheetState<T> createState() => ModalBottomSheetState<T>(); } class ModalBottomSheetState<T> extends State<ModalBottomSheet<T>> { GestureModalBottomSheetRoute<T> get route => widget.route; String _getRouteLabel(MaterialLocalizations localizations) { switch (Theme.of(context).platform) { case TargetPlatform.iOS: case TargetPlatform.macOS: return ''; case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: return localizations.dialogLabel; } } @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMaterialLocalizations(context)); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final String routeLabel = _getRouteLabel(localizations); return Semantics( scopesRoute: true, namesRoute: true, label: routeLabel, explicitChildNodes: true, child: ClipRect( child: Container( constraints: widget.constraints, // TODO: remove & use BottomSheet constraints child: BottomSheet( // animationController: route.controller, onClosing: () { if (route.isCurrent) { Navigator.pop(context); } }, builder: route.builder, backgroundColor: widget.backgroundColor, elevation: widget.elevation, shape: widget.shape, clipBehavior: widget.clipBehavior, // constraints: widget.constraints, enableDrag: false, ), ), ), ); } } Future<T?> showGestureBottomUpModal<T>({ required BuildContext context, required GestureRouteDelegate<T> gestureDelegate, required WidgetBuilder builder, Color? backgroundColor, double? elevation, ShapeBorder? shape, Clip? clipBehavior, BoxConstraints? constraints, Color? barrierColor, bool useRootNavigator = false, bool isDismissible = true, RouteSettings? routeSettings, }) { return createGestureBottomUpModalDelegate<T>( context: context, builder: builder, backgroundColor: backgroundColor, elevation: elevation, shape: shape, clipBehavior: clipBehavior, constraints: constraints, barrierColor: barrierColor, useRootNavigator: useRootNavigator, routeSettings: routeSettings, )(gestureDelegate); } ShowGestureRouteDelegate<T> createGestureBottomUpModalDelegate<T>({ required BuildContext context, required WidgetBuilder builder, Color? backgroundColor, double? elevation, ShapeBorder? shape, Clip? clipBehavior, BoxConstraints? constraints, Color? barrierColor, bool useRootNavigator = false, bool isDismissible = true, RouteSettings? routeSettings, }) { assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMaterialLocalizations(context)); return (GestureRouteDelegate<T> gestureDelegate) { final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator); return navigator.push(GestureModalBottomSheetRoute<T>( gestureDelegate: gestureDelegate, builder: builder, capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, backgroundColor: backgroundColor, elevation: elevation, shape: shape, clipBehavior: clipBehavior, constraints: constraints, isDismissible: isDismissible, modalBarrierColor: barrierColor, settings: routeSettings, )); }; }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/gesture_route_delegate.dart
import 'package:flutter/widgets.dart'; import '../gesture_handler.dart'; import 'gesture_route_transition_mixin.dart'; mixin GestureRouteDelegate<T> { GestureHandler get gestureHandler; GestureHandler? get barrierGestureHandler => gestureHandler; @protected GestureRouteTransitionMixin<T?>? route; bool get hasRoute => route != null; Future<T?> showRoute(); void closeRoute([T? result]) { assert(hasRoute); assert(route!.isCurrent); route!.navigator!.pop(result); } AnimationController createAnimationController(); @mustCallSuper void initRoute(GestureRouteTransitionMixin<T?> route) { assert(route.gestureDelegate == this); this.route = route; } @mustCallSuper void didPop(T? result) { if (userGestureInProgress) stopUserGesture(); } @mustCallSuper void disposeRoute() { assert(!userGestureInProgress); route = null; } @mustCallSuper void startUserGesture() { assert(route != null); route!.navigator!.didStartUserGesture(); } @mustCallSuper void stopUserGesture() { assert(route != null); route!.navigator!.didStopUserGesture(); } /// True if an gesture is currently underway for [route]. /// /// This just check the route's [NavigatorState.userGestureInProgress]. /// /// See also: /// /// * [userGestureEnabled], which returns true if a user-triggered gesture would be allowed. static bool isUserGestureInProgress(ModalRoute<dynamic> route) { return route.navigator!.userGestureInProgress; } bool get userGestureInProgress => isUserGestureInProgress(route!); /// Whether a gesture can be started by the user. /// /// Returns true if the user can swipe to a previous route. /// /// Returns false once [isUserGestureInProgress] is true, but /// [isUserGestureInProgress] can only become true if [userGestureEnabled] was /// true first. /// /// This should only be used between frames, not during build. bool get userGestureEnabled => _isUserGestureEnabled(route!); @protected bool _isUserGestureEnabled<R>(ModalRoute<R> route) { // If there's nothing to go back to, then obviously we don't support // the back gesture. if (route.isFirst) return false; // If the route wouldn't actually pop if we popped it, then the gesture // would be really confusing (or would skip internal routes), so disallow it. if (route.willHandlePopInternally) return false; // If attempts to dismiss this route might be vetoed such as in a page // with forms, then do not allow the user to dismiss the route with a swipe. if (route.hasScopedWillPopCallback) return false; // If we're being popped into, we also cannot be swiped until the pop above // it completes. This translates to our secondary animation being // dismissed. if (route.secondaryAnimation!.status != AnimationStatus.dismissed) return false; // If we're in a gesture already, we cannot start another. if (isUserGestureInProgress(route)) return false; return true; } }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/navigator_gesture_recognizer.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import '../gestures_binding.dart'; mixin NavigatorGesturesPreventingCancelingMixin on GestureRecognizer { static NavigatorGesturesBinding? getGestureBinding() { if (GestureBinding.instance is NavigatorGesturesBinding) return GestureBinding.instance as NavigatorGesturesBinding; return null; } void preventPointerFromCancel(int pointer) { getGestureBinding()?.preventPointerFromCancel(pointer, this); } void removePointerFromCancelPrevent(int pointer) { getGestureBinding()?.removePointerFromCancelPrevent(pointer, this); } } mixin NavigatorGesturesOneSequenceMixin on OneSequenceGestureRecognizer implements NavigatorGesturesPreventingCancelingMixin { @override void startTrackingPointer(int pointer, [Matrix4? transform]) { preventPointerFromCancel(pointer); super.startTrackingPointer(pointer, transform); } @override void stopTrackingPointer(int pointer) { removePointerFromCancelPrevent(pointer); super.stopTrackingPointer(pointer); } } class RouteHorizontalDragGestureRecognizer extends HorizontalDragGestureRecognizer with NavigatorGesturesPreventingCancelingMixin, NavigatorGesturesOneSequenceMixin { RouteHorizontalDragGestureRecognizer({Object? debugOwner, PointerDeviceKind? kind /*, Set<PointerDeviceKind>? supportedDevices */}) : super(debugOwner: debugOwner, kind: kind/*, supportedDevices: supportedDevices */); } class RouteVerticalDragGestureRecognizer extends VerticalDragGestureRecognizer with NavigatorGesturesPreventingCancelingMixin, NavigatorGesturesOneSequenceMixin { RouteVerticalDragGestureRecognizer({Object? debugOwner, PointerDeviceKind? kind /*, Set<PointerDeviceKind>? supportedDevices */}) : super(debugOwner: debugOwner, kind: kind/*, supportedDevices: supportedDevices */); }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/swipe_route_handler.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; import '../gesture_handler.dart'; import '../gesture_handlers/any_tap_handler.dart'; import '../gesture_handlers/swipe_handler.dart'; import 'gesture_route_delegate.dart'; import 'gesture_route_transition_mixin.dart'; import 'navigator_gesture_recognizer.dart'; typedef ShowGestureRouteDelegate<T> = Future<T?> Function(GestureRouteDelegate<T> gestureDelegate); class SwipeRouteHandler<T> extends SwipeHandler with AnimationGestureMixin, AnimationControllerGestureMixin, AnimationSwipeHandlerMixin, AnimationControllerSwipeHandlerMixin, GestureRouteDelegate<T> { SwipeRouteHandler({ required this.controllerFactory, required this.openRouteDelegate, required this.getChildSize, this.openProgressThreshold = kSwipeProgressThreshold, this.closeProgressThreshold = kSwipeProgressThreshold, this.minOpenFlingVelocity = kSwipeFlingVelocity, this.minCloseFlingVelocity = kSwipeFlingVelocity, this.reverse = false, ValueGetter<bool>? isDeactivated, required DragDirection direction, DragStartBehavior dragStartBehavior = DragStartBehavior.start, }) : _isDeactivated = isDeactivated, super(direction: direction, dragStartBehavior: dragStartBehavior); @override RecognizerFactories recognizerFactories() { // TODO: calls on each route. move to internal handler ? final recognizers = <Type, GestureRecognizerFactory>{}; if (handleHorizontal) { recognizers[RouteHorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<RouteHorizontalDragGestureRecognizer>( () => RouteHorizontalDragGestureRecognizer(debugOwner: this), initializeDragGestureRecognizer); } if (handleVertical) { recognizers[RouteVerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<RouteVerticalDragGestureRecognizer>( () => RouteVerticalDragGestureRecognizer(debugOwner: this), initializeDragGestureRecognizer); } return recognizers; } @override GestureHandler get gestureHandler => this; GestureHandler? _anyTapHandler; @override GestureHandler? get barrierGestureHandler { if (!hasRoute || !route!.barrierDismissible) return this; _anyTapHandler ??= AnyTapHandlerDelegate(onAnyTapUp: onDismiss); return GestureHandlerComposer(handlers: [this, _anyTapHandler!]); } @override bool get userGestureInProgress => hasRoute && super.userGestureInProgress; @override bool get userGestureEnabled => !isDeactivated && (!hasRoute || (route!.isActive && super.userGestureEnabled)); final ValueGetter<AnimationController> controllerFactory; @override AnimationController get controller => _controller!; AnimationController? _controller; bool get _hasController => _controller != null; @override double get value => _controller?.value ?? 0.0; @override final double openProgressThreshold; @override final double closeProgressThreshold; @override final double minOpenFlingVelocity; @override final double minCloseFlingVelocity; @override final bool reverse; @override double get childSize => getChildSize(); final ValueGetter<double> getChildSize; @override bool get isDeactivated => _isDeactivated?.call() ?? false; final ValueGetter<bool>? _isDeactivated; @override bool canAnimate(DragUpdateDetails e) { if (!userGestureEnabled) return false; final delta = e.primaryDelta! * (reverse ? -1.0 : 1.0); if (!_hasController) return delta > 0; return super.canAnimate(e); } final ValueGetter<ShowGestureRouteDelegate<T>> openRouteDelegate; @override Future<T?> showRoute() { final future = openRouteDelegate()(this); assert(hasRoute); return future; } @override void closeRoute([T? result]) { if (!hasRoute || !route!.isActive) return; super.closeRoute(result); } @override void onDragUpdate(DragUpdateDetails e) { if (!hasRoute) { if (!userGestureEnabled) return; if (!canAnimate(e)) return; showRoute(); if (!userGestureInProgress) startUserGesture(); } else { if (!userGestureInProgress) { if (!userGestureEnabled) return; startUserGesture(); } super.onDragUpdate(e); } } @override void onDragEnd(DragEndDetails e) { if (!userGestureInProgress) return; super.onDragEnd(e); if (userGestureInProgress) stopUserGesture(); checkControllerStatusAndPopIfNeeded(_controller?.status); } @override void onDragCancel() { if (!userGestureInProgress) return; super.onDragCancel(); if (userGestureInProgress) stopUserGesture(); } void onDismiss() { if (!hasRoute || !userGestureEnabled) return; startUserGesture(); reverseProgress(); stopUserGesture(); } @override AnimationController createAnimationController() { assert(_controller == null); _controller = controllerFactory(); _controller!.addStatusListener(checkControllerStatusAndPopIfNeeded); return _controller!; } void checkControllerStatusAndPopIfNeeded(AnimationStatus? status) { if (status == AnimationStatus.dismissed) { if ((route?.isActive ?? false) && userGestureInProgress) return; if (userGestureInProgress) stopUserGesture(); controller.removeStatusListener(checkControllerStatusAndPopIfNeeded); // preventing [TransitionRoute._handleStatusChanged] finalizeRoute conflict. WidgetsBinding.instance!.addPostFrameCallback((_) { closeRoute(); }); } } @override void disposeRoute() { _controller = null; super.disposeRoute(); } @override void dispose() { _anyTapHandler?.dispose(); super.dispose(); } }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/swipe_gesture_transition.dart
import 'package:flutter/widgets.dart'; final Animatable<Offset> kLeftRightTween = Tween<Offset>( begin: Offset.zero, end: const Offset(1.0, 0.0), ); final Animatable<Offset> kRightLeftTween = Tween<Offset>( begin: const Offset(1.0, 0.0), end: Offset.zero, ); final Animatable<Offset> kTopBottomTween = Tween<Offset>( begin: Offset.zero, end: const Offset(0.0, 1.0), ); final Animatable<Offset> kBottomTopTween = Tween<Offset>( begin: const Offset(0.0, 1.0), end: Offset.zero, ); class SwipeGestureTransition extends StatelessWidget { SwipeGestureTransition({ Key? key, required Animation<double> primaryRouteAnimation, required Animatable<Offset> direction, required this.child, }) : _primaryPositionAnimation = primaryRouteAnimation.drive(direction), super(key: key); /// When this page is coming in to cover another page. final Animation<Offset> _primaryPositionAnimation; final Widget child; @override Widget build(BuildContext context) { return SlideTransition( position: _primaryPositionAnimation, // transformHitTests: false, child: child, ); } }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/gesture_route_transition_mixin.dart
import 'package:flutter/semantics.dart'; import 'package:flutter/widgets.dart'; import '../gesture_handler.dart'; import 'gesture_route_delegate.dart'; mixin GestureRouteTransitionMixin<T> on ModalRoute<T> { GestureRouteDelegate get gestureDelegate; HitTestBehavior? get gestureBehavior => null; GestureHandler get gestureHandler => gestureDelegate.gestureHandler; GestureHandler? get barrierGestureHandler => gestureDelegate.barrierGestureHandler; @override AnimationController createAnimationController() => gestureDelegate.createAnimationController(); @override void install() { gestureDelegate.initRoute(this); super.install(); } @override bool didPop(T? result) { gestureDelegate.didPop(result); return super.didPop(result); } @override void dispose() { gestureDelegate.disposeRoute(); super.dispose(); } @override Widget buildTransitions( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { final transitionChild = buildPageTransitions(context, animation, secondaryAnimation, child); return buildGestureListener(context, animation, secondaryAnimation, transitionChild); } Widget buildGestureListener( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return GestureListener( handler: gestureDelegate.gestureHandler, behavior: gestureBehavior, excludeFromSemantics: true, child: child, ); } Widget buildPageTransitions( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child); @override void changedInternalState() { super.changedInternalState(); _modalBarrier?.markNeedsBuild(); } @override void changedExternalState() { super.changedExternalState(); _modalBarrier?.markNeedsBuild(); } // override ModalRoute behavior late OverlayEntry? _modalBarrier; Widget buildGestureModalBarrier(BuildContext context) { final gestureHandler = barrierGestureHandler; Widget barrier = buildModalBarrier(context, barrierDismissible && gestureHandler == null); if (gestureHandler != null) { barrier = Stack( children: [ barrier, GestureListener( handler: gestureHandler, behavior: HitTestBehavior.opaque, excludeFromSemantics: true, child: Container(), ), ], ); } return barrier; } Widget buildModalBarrier(BuildContext context, bool barrierDismissible) { Widget barrier; if (barrierColor != null && barrierColor!.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates assert(barrierColor != barrierColor!.withOpacity(0.0)); final Animation<Color?> color = animation!.drive( ColorTween( begin: barrierColor!.withOpacity(0.0), end: barrierColor, // changedInternalState is called if barrierColor updates ).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates ); barrier = AnimatedModalBarrier( color: color, dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates barrierSemanticsDismissible: semanticsDismissible, ); } else { barrier = ModalBarrier( dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates barrierSemanticsDismissible: semanticsDismissible, ); } if (filter != null) { barrier = BackdropFilter( filter: filter!, child: barrier, ); } barrier = IgnorePointer( ignoring: animation!.status == AnimationStatus.reverse || // changedInternalState is called when animation.status updates animation!.status == AnimationStatus.dismissed, // dismissed is possible when doing a manual pop gesture child: barrier, ); if (semanticsDismissible && this.barrierDismissible) { // To be sorted after the _modalScope. barrier = Semantics( sortKey: const OrdinalSortKey(1.0), child: barrier, ); } return barrier; } @override Iterable<OverlayEntry> createOverlayEntries() { final modalOverlays = List<OverlayEntry>.from(super.createOverlayEntries(), growable: false); if (barrierGestureHandler != null) { _modalBarrier = OverlayEntry(builder: (context) => buildGestureModalBarrier(context)); modalOverlays[0] = _modalBarrier!; } return modalOverlays; } }
0
mirrored_repositories/gesture_handlers/lib/src
mirrored_repositories/gesture_handlers/lib/src/gesture_navigation/gesture_routes.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'gesture_route_delegate.dart'; import 'gesture_route_transition_mixin.dart'; class MaterialGesturePageRoute<T> extends MaterialPageRoute<T> with GestureRouteTransitionMixin<T> { MaterialGesturePageRoute({ required this.gestureDelegate, required WidgetBuilder builder, RouteSettings? settings, bool maintainState = true, bool fullscreenDialog = false, }) : super(builder: builder, settings: settings, maintainState: maintainState, fullscreenDialog: fullscreenDialog); @override GestureRouteDelegate gestureDelegate; @override Widget buildPageTransitions( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { final PageTransitionsTheme theme = Theme.of(context).pageTransitionsTheme; return theme.buildTransitions<T>(this, context, animation, secondaryAnimation, child); } }
0
mirrored_repositories/gesture_handlers/example
mirrored_repositories/gesture_handlers/example/lib/main.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:gesture_handlers/gesture_handlers.dart'; void main() { // debugPrintRecognizerCallbacksTrace = true; // debugPrintPreventCancelPointer = true; /// [GestureBinding] implementation for prevent route [GestureHandler] active pointers canceling by [NavigatorState]. NavigatorGesturesFlutterBinding.ensureInitialized(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, /// override PageTransitionsTheme just for CupertinoPageTransition right to left animation. pageTransitionsTheme: const PageTransitionsTheme(builders: { TargetPlatform.android: RightToLeftTransitionBuilder(), TargetPlatform.iOS: RightToLeftTransitionBuilder(), TargetPlatform.fuchsia: RightToLeftTransitionBuilder(), TargetPlatform.linux: RightToLeftTransitionBuilder(), }), ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin { late final AnimationController persistentBottomController; late final SwipeRouteHandler secondSwipeHandler; late final AnimationControllerGestureMixin horizontalSwipeHandler; late final GestureHandler handlerComposer; Size get size => MediaQuery.of(context).size; double get persistentBottomHeight => 0.3 * size.height; double get bottomSheetHeight => 0.8 * size.height; bool get isPersistentBottomOpened => persistentBottomController.value.round() > 0; @override void initState() { super.initState(); persistentBottomController = AnimationController(duration: const Duration(milliseconds: 300), vsync: this); final persistentBottomSwipeHandler = AnimationControllerSwipeHandler( direction: DragDirection.vertical, reverse: true, controller: persistentBottomController, getChildSize: () => persistentBottomHeight, ); secondSwipeHandler = SwipeRouteHandler( controllerFactory: () => AnimationController(duration: const Duration(milliseconds: 500), vsync: this), openRouteDelegate: createBottomSheetDelegate, direction: DragDirection.vertical, openProgressThreshold: 0.3, reverse: true, getChildSize: () => bottomSheetHeight, ); horizontalSwipeHandler = SwipeRouteHandler( controllerFactory: () => AnimationController(duration: const Duration(milliseconds: 500), vsync: this), openRouteDelegate: openRightSheet, direction: DragDirection.horizontal, reverse: true, getChildSize: () => size.width, ); handlerComposer = GestureHandlerComposer( handlers: [ CascadeSwipeHandler( handlers: [ persistentBottomSwipeHandler, secondSwipeHandler, ], reverse: true, direction: DragDirection.vertical, ), horizontalSwipeHandler, TapHandlerDelegate(onTap: () { // persistentBottomSwipeHandler.controller.animateTo(isPersistentBottomOpened ? 0.0 : 1.0); secondSwipeHandler.showRoute(); }), ], ); } @override void dispose() { persistentBottomController.dispose(); handlerComposer.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final style = Theme.of(context).textTheme.headline6; return GestureListener( handler: handlerComposer, child: Scaffold( appBar: AppBar(title: Text(widget.title)), body: Center(child: Text('Swipe up \nSwipe left \nTap', textAlign: TextAlign.center, style: style)), bottomNavigationBar: buildPersistentBottom(context), ), ); } Widget buildPersistentBottom(BuildContext context) { return SizeTransition( sizeFactor: persistentBottomController, axisAlignment: -1.0, child: Card( margin: EdgeInsets.zero, color: Colors.white12, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(22.0))), child: Container( alignment: Alignment.center, height: persistentBottomHeight, padding: const EdgeInsets.all(16.0), child: const Text('swipe up to modal sheet'), ), ), ); } ShowGestureRouteDelegate createBottomSheetDelegate() { return createGestureBottomUpModalDelegate( context: context, constraints: BoxConstraints(maxHeight: bottomSheetHeight), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(22.0))), builder: (ctx) => Container( alignment: Alignment.center, child: const Text('Gesture Modal Bottom Sheet Route'), ), ); } ShowGestureRouteDelegate openRightSheet() { return (gestureDelegate) => Navigator.push( context, MaterialGesturePageRoute( gestureDelegate: gestureDelegate, builder: (ctx) => Scaffold( appBar: AppBar(title: const Text('Page Route')), body: Center(child: const Text('Material Gesture Page Route')), ), ), ); } } class RightToLeftTransitionBuilder extends PageTransitionsBuilder { const RightToLeftTransitionBuilder() : super(); @override Widget buildTransitions<T>(ModalRoute<T> route, BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { return CupertinoPageTransition( primaryRouteAnimation: animation, secondaryRouteAnimation: secondaryAnimation, linearTransition: true, child: child, ); } }
0
mirrored_repositories/gesture_handlers/example
mirrored_repositories/gesture_handlers/example/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:example/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/GETPOS-Flutter-App
mirrored_repositories/GETPOS-Flutter-App/lib/firebase_options.dart
// // File generated by FlutterFire CLI. // // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members // import 'dart:ui'; // import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; // import 'package:flutter/foundation.dart' // show defaultTargetPlatform, kIsWeb, TargetPlatform; // /// Default [FirebaseOptions] for use with your Firebase apps. // /// // /// Example: // /// ```dart // /// import 'firebase_options.dart'; // /// // ... // /// await Firebase.initializeApp( // /// options: DefaultFirebaseOptions.currentPlatform, // /// ); // /// ``` // class DefaultFirebaseOptions { // static FirebaseOptions get currentPlatform { // if (kIsWeb) { // return web; // } // switch (defaultTargetPlatform) { // case TargetPlatform.android: // return android; // case TargetPlatform.iOS: // return ios; // case TargetPlatform.macOS: // return macos; // case TargetPlatform.windows: // return windows; // // throw UnsupportedError( // // 'DefaultFirebaseOptions have not been configured for windows - ' // // 'you can reconfigure this by running the FlutterFire CLI again.', // // ); // case TargetPlatform.linux: // throw UnsupportedError( // 'DefaultFirebaseOptions have not been configured for linux - ' // 'you can reconfigure this by running the FlutterFire CLI again.', // ); // default: // throw UnsupportedError( // 'DefaultFirebaseOptions are not supported for this platform.', // ); // } // } // static const FirebaseOptions web = FirebaseOptions( // apiKey: 'AIzaSyBnZCNrKJn2VYgwcNAge39ng0bKOpvudAA', // appId: '1:710947816899:web:e7447b998b2606d79c6976', // messagingSenderId: '710947816899', // projectId: 'get-pos-49a30', // authDomain: 'get-pos-49a30.firebaseapp.com', // storageBucket: 'get-pos-49a30.appspot.com', // measurementId: 'G-W7DHG3QCES', // ); // static const FirebaseOptions android = FirebaseOptions( // apiKey: 'AIzaSyD8nD69qfA1pknANn9Fj-gtp8C8knXcKWo', // appId: '1:710947816899:android:51b9c734131da2419c6976', // messagingSenderId: '710947816899', // projectId: 'get-pos-49a30', // storageBucket: 'get-pos-49a30.appspot.com', // ); // static const FirebaseOptions ios = FirebaseOptions( // apiKey: 'AIzaSyAR5i1pjefmtabBXwStAhVqD6WPJGzcN9g', // appId: '1:710947816899:ios:382331a2135f6a359c6976', // messagingSenderId: '710947816899', // projectId: 'get-pos-49a30', // storageBucket: 'get-pos-49a30.appspot.com', // iosClientId: '710947816899-6p71jpi57rhep6ok0ea6r53h4eo97bul.apps.googleusercontent.com', // iosBundleId: 'com.nestorbird.nb-pos', // ); // static const FirebaseOptions macos = FirebaseOptions( // apiKey: 'AIzaSyAR5i1pjefmtabBXwStAhVqD6WPJGzcN9g', // appId: '1:710947816899:ios:d2c4978cd5ea266f9c6976', // messagingSenderId: '710947816899', // projectId: 'get-pos-49a30', // storageBucket: 'get-pos-49a30.appspot.com', // iosClientId: '710947816899-4fup9uksi2bpco8iaaurn3ku478u007b.apps.googleusercontent.com', // iosBundleId: 'com.nestorbird.nbPosx', // ); // static const FirebaseOptions windows = FirebaseOptions( // apiKey: 'AIzaSyD8nD69qfA1pknANn9Fj-gtp8C8knXcKWo', // appId: '1:710947816899:android:51b9c734131da2419c6976', // messagingSenderId: '710947816899', // projectId: 'get-pos-49a30', // storageBucket: 'get-pos-49a30.appspot.com', // ); // }
0
mirrored_repositories/GETPOS-Flutter-App
mirrored_repositories/GETPOS-Flutter-App/lib/main.dart
//import 'package:firebase_core/firebase_core.dart'; // import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_device_type/flutter_device_type.dart'; import 'package:get/get.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:nb_posx/core/tablet/login/login_landscape.dart'; import 'package:nb_posx/database/db_utils/db_instance_url.dart'; import 'package:nb_posx/network/api_constants/api_paths.dart'; import 'constants/app_constants.dart'; import 'core/mobile/splash/view/splash_screen.dart'; import 'core/tablet/home_tablet.dart'; import 'database/db_utils/db_hub_manager.dart'; import 'database/models/attribute.dart'; import 'database/models/category.dart'; import 'database/models/customer.dart'; import 'database/models/hub_manager.dart'; import 'database/models/option.dart'; import 'database/models/order_item.dart'; import 'database/models/park_order.dart'; import 'database/models/product.dart'; import 'database/models/sale_order.dart'; import 'utils/helpers/sync_helper.dart'; bool isUserLoggedIn = false; bool isTabletMode = false; void main() async { WidgetsFlutterBinding.ensureInitialized(); // await Firebase.initializeApp( // options: DefaultFirebaseOptions.currentPlatform, // ); // FlutterError.onError = (errorDetails) { // FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails); // }; // // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics // PlatformDispatcher.instance.onError = (error, stack) { // FirebaseCrashlytics.instance.recordError(error, stack, fatal: true); // return true; // }; //Initializing hive database await Hive.initFlutter(); //Registering hive database type adapters registerHiveTypeAdapters(); isUserLoggedIn = await DbHubManager().getManager() != null; instanceUrl = await DbInstanceUrl().getUrl(); await SyncHelper().launchFlow(isUserLoggedIn); // check for device isTabletMode = Device.get().isTablet; if (isTabletMode) { await SystemChrome.setPreferredOrientations( [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]); runApp(const TabletApp()); } else { await SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp], ); runApp(const MobileApp()); } } //Function to register all the Hive database adapters void registerHiveTypeAdapters() { //Registering customer adapter Hive.registerAdapter(CustomerAdapter()); //Registering hub manager adapter Hive.registerAdapter(HubManagerAdapter()); //Registering sale order adapter Hive.registerAdapter(SaleOrderAdapter()); //Registering ward adapter Hive.registerAdapter(CategoryAdapter()); //Registering product adapter Hive.registerAdapter(ProductAdapter()); Hive.registerAdapter(AttributeAdapter()); Hive.registerAdapter(OptionAdapter()); Hive.registerAdapter(ParkOrderAdapter()); Hive.registerAdapter(OrderItemAdapter()); } class MobileApp extends StatelessWidget { const MobileApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: APP_NAME, theme: ThemeData( primarySwatch: Colors.blue, ), home: const SplashScreen(), ); } } class TabletApp extends StatelessWidget { const TabletApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return GetMaterialApp( debugShowCheckedModeBanner: false, title: APP_NAME, theme: ThemeData( primarySwatch: Colors.blue, ), home: isUserLoggedIn ? HomeTablet() : const LoginLandscape(), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/network
mirrored_repositories/GETPOS-Flutter-App/lib/network/service/api_utils.dart
import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '../../constants/app_constants.dart'; import '../../database/db_utils/db_constants.dart'; import '../../database/db_utils/db_preferences.dart'; import '../../utils/helper.dart'; import '../api_constants/api_paths.dart'; import '../api_helper/api_exception.dart'; ///[APIUtils] class to provide utility for HTTP methods like get, post, patch, etc. class APIUtils { ///[getRequest] method to use get API call to server. ///param : [apiUrl] -> API URL ///param : [headers] -> API headers for the [apiUrl] static Future<Map<String, dynamic>> getRequest(String apiUrl) async { try { //Remote Call to API with url and headers http.Response apiResponse = await http.get(_apiPath(apiUrl)); //Checking for the response code and handling the result. return _returnResponse(apiResponse); } //Handling the condition when socket exception received. on SocketException { throw FetchDataException(FAILURE_OCCURED); } } static Future<Map<String, dynamic>> getRequestVerify(String apiUrl) async { try { //Remote Call to API with url and headers http.Response apiResponse = await http.get(_apiPathVerify(apiUrl)); //Checking for the response code and handling the result. return _returnResponse(apiResponse); } //Handling the condition when socket exception received. on SocketException { throw FetchDataException(FAILURE_OCCURED); } } static Future<Map<String, dynamic>> getRequestWithCompleteUrl( String apiUrl) async { try { //Remote Call to API with url and headers http.Response apiResponse = await http.get(Uri.parse(apiUrl)); //Checking for the response code and handling the result. return _returnResponse(apiResponse); } //Handling the condition when socket exception received. on SocketException { throw FetchDataException(FAILURE_OCCURED); } } ///[postRequest] function for GET requests with auth token as header ///and request type as form data. ///param : [apiUrl] -> API URL static Future<Map<String, dynamic>> postRequest( String apiUrl, dynamic requestBody, {bool enableHeader = true}) async { try { Helper.printJSONData(requestBody); //Getting response from api call http.Response apiResponse = await http.post(_apiPath(apiUrl), body: jsonEncode(requestBody), headers: enableHeader ? await _headers() : {}); print(apiResponse); //Checking for the response code and handling the result. return _returnResponse(apiResponse); } //Handling the condition when socket exception received. on SocketException { throw FetchDataException(FAILURE_OCCURED); } } static Future<Map<String, dynamic>> getRequestWithHeaders( String apiUrl) async { try { //Remote Call to API with url and headers http.Response apiResponse = await http.get(_apiPath(apiUrl), headers: await _headers()); //Checking for the response code and handling the result. return _returnResponse(apiResponse); } //Handling the condition when socket exception received. on SocketException { throw FetchDataException(FAILURE_OCCURED); } } static Uri _apiPath(String url) { //Parsing the apiURl to Uri Uri uri = Uri.parse(instanceUrl + url); log('API URL :: $uri'); return uri; } static Uri _apiPathVerify(String url) { //Parsing the apiURl to Uri Uri uri = Uri.parse( url); log('API URL :: $uri'); return uri; } static Future<Map<String, String>> _headers() async { //Getting auth token String authToken = await getToken(); debugPrint("TOKEN: $authToken"); //Creating http headers for api Map<String, String> headers = { 'Authorization': authToken, 'Content-Type': 'application/json' }; return headers; } ///Function to handle the response as per status code from api server static dynamic _returnResponse(http.Response response) { switch (response.statusCode) { case 200: var responseJson = jsonDecode(response.body); Helper.printJSONData(responseJson); return responseJson; case 400: throw BadRequestException(response.body.toString()); case 401: case 403: throw UnAuthorisedException(response.body.toString()); case 500: default: throw FetchDataException( "$SERVER_COMM_EXCEPTION : ${response.statusCode}"); } } ///Function for building the auth token to be used in api headers ///using API Key and API Secret. static Future<String> getToken() async { //Creating object for DBPreferences DBPreferences dbPreferences = DBPreferences(); //Getting API Key String apiKey = await dbPreferences.getPreference(ApiKey); //Getting API Secret String apiSecret = await dbPreferences.getPreference(ApiSecret); //Returning the final auth token as result return "token $apiKey:$apiSecret"; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/network
mirrored_repositories/GETPOS-Flutter-App/lib/network/api_constants/api_paths.dart
// ignore_for_file: constant_identifier_names import '../../constants/app_constants.dart'; import '../api_helper/api_server.dart'; ///Base API URL for development environment const DEV_URL = 'https://getpos.in/api/'; const DEV_ERP_URL = 'getpos.in'; // const DEV_URL = 'https://agriboratest.nestorhawk.com/api/'; ///Base API URL for staging/test environment const TEST_URL = 'https://tst.erp.nbpos.com/api/'; const TEST_ERP_URL = 'getpos.in'; ///Base API URL for production environment const PROD_URL = 'https://prd.erp.nbpos.com/api/'; const PROD_ERP_URL = 'getpos.in'; ///Default URL for POS instance String instanceUrl = ENVIRONMENT == ApiServer.DEV ? DEV_ERP_URL : ENVIRONMENT == ApiServer.TEST ? TEST_ERP_URL : PROD_ERP_URL; ///Base API URL for production environment // ignore: non_constant_identifier_names final BASE_URL = ENVIRONMENT == ApiServer.DEV ? DEV_URL : ENVIRONMENT == ApiServer.TEST ? TEST_URL : PROD_URL; ///LOGIN API PATH const LOGIN_PATH = 'method/nbpos.nbpos.api.login'; const Verify_URL = 'https://control-centre.nestorbird.com/api/method/control_centre.api.validate'; ///CUSTOMERS LIST API PATH const CUSTOMERS_PATH = 'method/nbpos.nbpos.api.get_customer_list_by_hubmanager'; const CUSTOMER_PATH = 'method/nbpos.nbpos.api.get_customer'; const CREATE_CUSTOMER_PATH = 'method/nbpos.nbpos.api.create_customer'; const NEW_GET_ALL_CUSTOMERS_PATH = 'method/nbpos.nbpos.api.get_all_customer'; //PRODUCTS LIST API PATH const PRODUCTS_PATH = 'method/nbpos.nbpos.api.get_item_list_by_hubmanager'; //CREATE SALE ORDER PATH const CREATE_SALES_ORDER_PATH = 'method/nbpos.nbpos.api.create_sales_order'; //TOPICS API (PRIVACY POLICY AND TERMS & CONDITIONS) const TOPICS_PATH = 'method/nbpos.nbpos.api.privacy_policy_and_terms'; //FORGET PASSWORD PATH const FORGET_PASSWORD = 'method/nbpos.nbpos.api.forgot_password'; //MY ACCOUNT API const MY_ACCOUNT_PATH = 'method/nbpos.nbpos.api.get_details_by_hubmanager'; //SALES HISTORY PATH const SALES_HISTORY = 'method/nbpos.nbpos.api.get_sales_order_list'; //MY ACCOUNT API const CHANGE_PASSWORD_PATH = 'method/nbpos.nbpos.api.change_password'; // New Product api with category and variants const CATEGORY_PRODUCTS_PATH = 'method/nbpos.custom_api.item_variant_api.get_items'; //PROMO CODES API PATH const GET_ALL_PROMO_CODES_PATH = '';
0
mirrored_repositories/GETPOS-Flutter-App/lib/network
mirrored_repositories/GETPOS-Flutter-App/lib/network/api_helper/api_status.dart
// ignore_for_file: constant_identifier_names enum ApiStatus { NO_INTERNET, INTERNET_AVAILABLE, REQUEST_SUCCESS, REQUEST_FAILURE, NO_DATA_AVAILABLE, NONE }
0
mirrored_repositories/GETPOS-Flutter-App/lib/network
mirrored_repositories/GETPOS-Flutter-App/lib/network/api_helper/api_server.dart
// ignore_for_file: constant_identifier_names enum ApiServer { DEV, TEST, PROD }
0
mirrored_repositories/GETPOS-Flutter-App/lib/network
mirrored_repositories/GETPOS-Flutter-App/lib/network/api_helper/api_exception.dart
///[ApiException] class for defining exceptions need to be thrown as per status code. // ignore_for_file: prefer_typing_uninitialized_variables class ApiException implements Exception { final _message; final _prefix; ApiException([this._message, this._prefix]); @override String toString() { return "$_prefix$_message"; } } ///[FetchDataException] -> When data or connection is lost in between. class FetchDataException extends ApiException { FetchDataException([String? message]) : super(message, "Error During Communication: "); } ///[BadRequestException] -> When the request body is not correct. class BadRequestException extends ApiException { BadRequestException([message]) : super(message, "Invalid Request: "); } ///[UnauthorisedException] -> When Unauthorized accessing. class UnAuthorisedException extends ApiException { UnAuthorisedException([message]) : super(message, "Unauthorised: "); }
0
mirrored_repositories/GETPOS-Flutter-App/lib/network
mirrored_repositories/GETPOS-Flutter-App/lib/network/api_helper/comman_response.dart
import 'api_status.dart'; ///[CommanResponse] class to handle the basic response from api class CommanResponse { bool? status; dynamic message; ApiStatus? apiStatus; //constructor CommanResponse( {this.status = true, this.message = 'success', this.apiStatus = ApiStatus.NONE}); //create class object from json CommanResponse.fromJson(Map<String, dynamic> json) { status = json['status']; message = json['message']; apiStatus = json['apiStatus']; } // convert object to json Map<String, dynamic> toJson() { final Map<String, dynamic> data = <String, dynamic>{}; data['status'] = status; data['message'] = message; data['apiStatus'] = apiStatus; return data; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/constants/asset_paths.dart
/// /// IMAGE ASSETS /// /// // ignore_for_file: constant_identifier_names const BACK_IMAGE = "assets/icons/back_arrow.svg"; const MENU_ICON = "assets/icons/menu_icon.svg"; const CROSS_ICON = "assets/icons/cross_icon.svg"; const CREATE_ORDER_IMAGE = "assets/icons/create_order.svg"; const PRODUCT_IMAGE = "assets/icons/product.svg"; const CUSTOMER_IMAGE = "assets/icons/customers.svg"; const MY_ACCOUNT_IMAGE = "assets/icons/profile_icon.svg"; const SALES_IMAGE = "assets/icons/order_history_icon.svg"; const FINANCE_IMAGE = "assets/icons/finances.svg"; const HOME_CUSTOMER_IMAGE = 'assets/icons/home_customer.svg'; const CREATE_ORDER_BASKET_IMAGE = 'assets/icons/create_order_basket.svg'; const CHANGE_PASSWORD_IMAGE = 'assets/icons/change_pass_icon.svg'; const DELETE_IMAGE = 'assets/icons/delete_icon.svg'; const LOGOUT_IMAGE = 'assets/icons/logout_icon.svg'; const PRODUCT_IMAGE_SMALL = 'assets/icons/product_icon_small.svg'; const PRODUCT_IMAGE_ = 'assets/icons/product_icon.svg'; const SEARCH_IMAGE = 'assets/icons/search_icon.svg'; const SUCCESS_IMAGE = 'assets/tablet_icons/7JtNbOOHJj.json'; const PAYMENT_CASH_ICON = 'assets/icons/cash_icon.svg'; const PAYMENT_CARD_ICON = 'assets/icons/card_icon.svg'; const CATEGORY_CLOSED_ICON = 'assets/icons/category_close_icon.svg'; const CATEGORY_OPENED_ICON = 'assets/icons/category_open_icon.svg'; const HOME_USER_IMAGE = "assets/icons/my_account.svg"; // const APP_LOGO = "assets/images/logo.png"; const LOGIN_IMAGE = "assets/tablet_icons/side_image.svg"; const PIZZA_IMAGE = "assets/images/pizza_img.png"; const BURGAR_IMAGE = "assets/images/burgar_img.png"; const HOME_TAB_ICON = "assets/tablet_icons/home_selected.svg"; const ORDER_TAB_ICON = "assets/tablet_icons/order_icon.svg"; const PRODUCE_TAB_ICON = "assets/tablet_icons/product_icon.svg"; const CUSTOMER_TAB_ICON = "assets/tablet_icons/customer_icon.svg"; const HISTORY_TAB_ICON = "assets/tablet_icons/history_icon.svg"; const PROFILE_TAB_ICON = "assets/tablet_icons/my_profile_icon.svg"; const EMPTY_CART_TAB_IMAGE = "assets/images/empty_cart.png"; const SEARCH_TAB_IMAGE = "assets/tablet_icons/search_icon.svg"; const MY_PROFILE_TAB_IMAGE = "assets/tablet_icons/operator_small_icon.svg"; const LOGOUT_TAB_IMAGE = "assets/tablet_icons/logout_icon.svg"; const FINANCE_TAB_IMAGE = "assets/tablet_icons/finance_icon.svg"; const FINANCE_ACTIVE_TAB_IMAGE = "assets/tablet_icons/finance_selected_icon.svg"; const CHANGE_PASS_TAB_IMAGE = "assets/tablet_icons/change_pass_icon.svg"; const CHANGE_PASS_ACTIVE_TAB_IMAGE = "assets/tablet_icons/change_pass_selected_icon.svg"; const APP_ICON = "assets/images/app_logo.png"; const APP_ICON_TABLET = "assets/images/app_logo_tablet.png"; // const CUSTOMER_SMALL_IMAGE = 'assets/icons/customer_small.svg'; // const FORWARD_ARROW_IMAGE = 'assets/icons/forward_arrow.svg'; // const PAYMENT_MPESA_ICON = 'assets/icons/mpesa_icon.svg'; // const PAYMENT_EWALLET_ICON = 'assets/icons/ewallet_icon.svg'; //New Product Listing Screen const FAB_MAIN_ICON = "assets/icons/fab_icon.svg"; const FAB_ACCOUNT_ICON = "assets/icons/fab_account.svg"; const FAB_CUSTOMERS_ICON = "assets/icons/fab_customers.svg"; const FAB_FINANCE_ICON = "assets/icons/fab_finance.svg"; const FAB_HISTORY_ICON = "assets/icons/fab_history.svg"; const FAB_HOME_ICON = "assets/icons/fab_home.svg"; const FAB_ORDERS_ICON = "assets/icons/fab_orders.svg"; const FAB_PRODUCTS_ICON = "assets/icons/fab_products.svg"; const NEW_ORDER_ICON = "assets/icons/add_icon.svg"; const CART_ICON = "assets/icons/cart_icon.svg";
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/constants/app_constants.dart
//****************************// // String Constants of the app //***************************// // ignore_for_file: constant_identifier_names import '../network/api_helper/api_server.dart'; const APP_NAME = 'NB POS'; String appCurrency = '₹'; const PLEASE_WAIT_TXT = 'Please wait...'; const ENVIRONMENT = ApiServer.DEV; const OFFLINE_DATA_FOR = 7; const APP_VERSION = "App version"; const APP_VERSION_FALLBACK = "1.0"; //LOGIN SCREEN const invalidPasswordMsg = "Enter at least 6 digits, should be one special characters,one uppercase,one lowercase,one digit."; // "Invalid Password \n1. Include at least 8 digits and three special characters \n2. Include at least one upper case characters (A-Z)\n3. Include at least one lower case character (a-z)\n4. Include a number (0-9)\n5. Include a symbol (!, #, \$, etc.)"; const passwordMismatch = "Password is mismatch"; const LOGIN_TXT = 'Log In'; const ACCESS_YOUR_ACCOUNT = 'Access your account'; const EMAIL_TXT = 'Email'; const PASSWORD_TXT = 'Password'; const URL_TXT = 'URL'; const URL_HINT = 'Enter ERP URL'; const EMAIL_HINT = 'Enter your email'; const PASSWORD_HINT = 'Enter your password'; const FORGET_PASSWORD_SMALL_TXT = 'Forgot Password?'; const BY_SIGNING_IN = 'By signing, you agree to our '; const TERMS_CONDITIONS = 'Terms & Conditions '; const AND_TXT = 'and '; const PRIVACY_POLICY = 'Privacy Policy '; const SOMETHING_WRONG = 'Something went wrong. Please try again'; const INVALID_EMAIL = 'Please enter valid email'; const INVALID_PASSWORD = 'Password should be at least of 6 characters'; const INVALID_URL = 'Please enter valid ERP URL'; const CLOSE_APP_QUESTION = 'Do you want to close the app?'; const OPTION_YES = 'Yes'; const OPTION_CONTINUE = "Continue"; const OPTION_NO = 'No'; const OPTION_OK = 'Ok'; const OPTION_CANCEL = 'Cancel'; //HOME SCREEN const HOME_TXT = 'Home'; const WELCOME_BACK = 'Welcome Back,'; const SYNC_NOW_TXT = 'Sync now'; const CREATE_ORDER_TXT = 'Create Order'; //Create Order Screen const PRODUCTS_TXT = 'Products'; const CUSTOMERS_TXT = 'Customers'; const MY_ACCOUNT_TXT = 'My Account'; const SALES_HISTORY_TXT = 'Order History'; const FINANCE_TXT = 'Finance'; //CREATE ORDER SCREEN const SELECT_CUSTOMER_TXT = 'Select Customer'; //Select Customer Screen const ADD_PRODUCT_TXT = 'Add Product'; const OUT_OF_STOCK = 'Out of stock'; //Create Order Screen const ITEMS_TXT = 'Items'; const PROCEED_TO_NXT_TXT = 'PROCCED TO NEXT'; const CHECKOUT_TXT = 'CHECKOUT'; const SELECT_CUSTOMER_ERROR = 'Please select the customer.'; const SELECT_PRODUCT_ERROR = 'Please add the products in cart.'; const SEARCH_PRODUCT_HINT_TXT = 'Search product / category'; //SELECT CUSTOMER SCREEN const SEARCH_HINT_TXT = 'Enter customer mobile number'; const SEARCH_CUSTOMER_MSG_TXT = 'Type in customer mobile number...'; const SELECT_CONTINUE_TXT = 'SELECT & CONTINUE'; // PRODUCT SCREEN const SEARCH_PRODUCT_TXT = 'Search product / category'; //ADD PRODUCTS SCREEN const ADD_PRODUCT_TITLE = 'Products'; const ADD_CONTINUE = 'ADD & CONTINUE'; const INSUFFICIENT_STOCK_ERROR = 'Insufficient stock for this product.'; const ADD_PRODUCTS_SEARCH_TXT = 'Search Product'; const ADD_PRODUCTS_AVAILABLE_STOCK_TXT = 'Available stock'; const ADD_PRODUCTS_STOCK_UPDATE_ON_TXT = 'Stock update on'; //CREATE ORDER SCREEN const CHANGE_CUSTOMER_TXT = 'Change customer'; const ADD_MORE_PRODUCTS = 'Add More Product'; //CHECKOUT SCREEN const CHECKOUT_TXT_SMALL = 'Checkout'; const CASH_PAYMENT_TXT = 'Cash'; const MPESA_PAYMENT_TXT = 'M-Pesa'; const EWALLET_PAYMENT_TXT = 'eWallet'; const CARD_PAYMENT_TXT = 'Card'; const CONFIRM_PAYMENT = 'Pay now'; const CASH_PAYMENT_MSG = 'Take the cash from the customer and click on confirm payment button'; const TRANSACTION_TXT = 'Transaction ID'; const ENTER_UR_TRANSACTION_ID = 'Enter your transaction ID'; const SELECT_PAYMENT_TYPE = 'Please select the payment type.'; const ENTER_MPESA_TRANS_ID = 'Please enter 10 alphanumeric M-Pesa transaction ID'; //SALE SUCCESSFUL SCREEN const SALES_SUCCESS_TXT = 'Order Successful'; const RETURN_TO_HOME_TXT = 'Home Page'; //MY ACCOUNT SCREEN const CHANGE_PASSWORD = 'Change Password'; const LOGOUT_TITLE = 'Logout'; const LOGOUT_QUESTION = 'Do you really want to logout?'; const OFFLINE_ORDER_MSG = 'Please sync your offline order first?'; //SALES HISTORY SCREEN const PARKED_ORDER_ID = 'Parked ID'; const SALES_ID = 'Order ID'; const ITEM_CODE_TXT = 'Item code'; const ITEM_TXT = 'Items'; //SALES DETAILS SCREEN const SALES_DETAILS_TXT = 'Order Details'; const SALE_AMOUNT_TXT = 'Order Amount'; const DATE_TIME = 'Date & Time'; const CUSTOMER_INFO = 'Customer Info'; const ITEMS_SUMMARY = 'Item(s) Summary'; const PAYMENT_STATUS = 'Status'; //FINANCE SCREEN const FINANCE_TITLE = 'Finance'; const CASH_BALANCE_TXT = 'Cash Balance'; //FORGOT PASSWORD SCREEN const FORGOT_PASSWORD_TITLE = 'Forgot password'; const FORGOT_EMAIL_TXT = 'Email'; const FORGOT_EMAIL_HINT = 'Enter your registered email'; const FORGOT_BTN_TXT = 'Continue'; const FORGOT_TXT_FIELD_EMPTY = 'Please provide registered email ID'; const FORGOT_SUB_MSG = 'A reset password link will be sent to your registered email ID to reset password.'; //VERIFY OTP SCREEN const VERIFY_OTP_TITLE = 'Verification link sent'; const VERIFY_OTP_MSG = 'A reset password link has been sent to your registered email id, kindly verify.'; const VERIFY_OTP_HINT = 'Enter otp'; const VERIFY_OTP_BTN_TXT = 'Back'; //CHANGE PASSWORD SCREEN const CHANGE_PASSWORD_TITLE = 'Change Password'; const CHANGE_PASSWORD_OTP_VERIFY_MSG = 'OTP verified successfully.'; const CHANGE_PASSWORD_SET_MSG = 'Set new password'; const CHANGE_NEW_PASSWORD_HINT = 'Enter new password'; const CHANGE_CONFIRM_PASSWORD_HINT = 'Re-enter new password'; const CHANGE_PASSWORD_BTN_TXT = 'Change Password'; const CHANGE_PASSWORD_INVALID_TEXT = 'New Password And Confirm Password Is Not Matched'; //PASSWORD UPDATED SCREEN const PASSWORD_UPDATED_TITLE = 'Password Updated!'; const PASSWORD_UPDATED_MSG = 'Password Has Been Updated Successfully'; const PASSWORD_UPDATED_BTN_TXT = 'Back To Home'; //SPLASH SCREEN const POWERED_BY_TXT = 'Powered by NestorBird'; //GENERAL MESSAGE CONSTANTS const NO_INTERNET = 'No internet connection'; const NO_INTERNET_LOADING_DATA_FROM_LOCAL = 'No internet connection. Loading data from local storage.'; const SOMTHING_WRONG_LOADING_LOCAL = 'Something went wrong. Loading data from local storage.'; const NO_DATA_FOUND = 'No data found.'; const SUCCESS = 'success'; const NO_INTERNET_CREATE_ORDER_SYNC_QUEUED = 'No internet available. Create order sync will take place later...'; const WEAK_PASSWORD = 'Password you choose is too weak'; const SOMETHING_WENT_WRONG = 'Something went wrong, Please try later...'; const FAILURE_OCCURED = 'Failure occured'; const SERVER_COMM_EXCEPTION = 'Error occured while communication with server with StatusCode'; // ERROR MSG const NO_PRODUCTS_FOUND_MSG = 'No products found'; const NO_ORDERS_FOUND_MSG = 'No orders found'; // height width margin constants const double APP_LOGO_WIDTH = 200; const double CARD_BORDER_SIDE_RADIUS_10 = 10; const double CARD_BORDER_SIDE_RADIUS_08 = 08; const double BORDER_CIRCULAR_RADIUS_06 = 06; const double BORDER_CIRCULAR_RADIUS_07 = 07; const double BORDER_CIRCULAR_RADIUS_08 = 08; const double BORDER_CIRCULAR_RADIUS_10 = 10; const double BORDER_CIRCULAR_RADIUS_20 = 20; const double BORDER_CIRCULAR_RADIUS_30 = 30; const double BORDER_WIDTH = 0.3; // HOME const double HOME_PROFILE_PIC_WIDTH = 130; const double HOME_PROFILE_PIC_RADIUS = 40; const double HOME_PROFILE_PIC_MARGIN = 18; const double HOME_TILE_HORIZONTAL_SPACING = 24; const double HOME_TILE_VERTICAL_SPACING = 20; const double HOME_TILE_PADDING_LEFT = 24; const double HOME_TILE_PADDING_TOP = 16; const double HOME_TILE_PADDING_RIGHT = 24; const double HOME_TILE_PADDING_BOTTOM = 32; const double HOME_TILE_ASSET_HEIGHT = 90; const int HOME_TILE_GRID_COUNT = 2; const double HOME_USER_PROFILE_LEFT_SPACING = 20; const double HOME_SWITCH_HEIGHT = 20; const double HOME_SWITCH_WIDTH = 50; const double HOME_SWITCH_BORDER_RADIUS = 25; const double HOME_SWITCH_TOGGLE_SIZE = 10; //FINANCE PADDINGS const double FINANCE_PADDING_LEFT = 16; const double FINANCE_PADDING_BOTTOM = 8; // MY ACCOUNT const double MY_ACCOUNT_ICON_WIDTH = 20; const double MY_ACCOUNT_ICON_PADDING_LEFT = 16; const double MY_ACCOUNT_ICON_PADDING_TOP = 8; const double MY_ACCOUNT_ICON_PADDING_RIGHT = 24; const double MY_ACCOUNT_ICON_PADDING_BOTTOM = 8; // SALE SUCCESS const double SALE_SUCCESS_IMAGE_HEIGHT = 120; const double SALE_SUCCESS_IMAGE_WIDTH = 150; // FONT SIZES const double LARGE_FONT_SIZE = 16; const double LARGE_PLUS_FONT_SIZE = 22; const double LARGE_ULTRA_PLUS_SIZE = 24; const double SMALL_MINUS_FONT_SIZE = 8; const double SMALL_FONT_SIZE = 10; const double SMALL_PLUS_FONT_SIZE = 12; const double MEDIUM_MINUS_FONT_SIZE = 13; const double MEDIUM_FONT_SIZE = 14; const double MEDIUM_PLUS_FONT_SIZE = 16; const double LARGE_MINUS_FONT_SIZE = 18;
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/text_field_widget.dart
import 'package:flutter/material.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; import '../utils/ui_utils/text_styles/edit_text_hint_style.dart'; class TextFieldWidget extends StatelessWidget { const TextFieldWidget( {Key? key, required TextEditingController txtCtrl, required String hintText, this.txtColor = DARK_GREY_COLOR, required this.boxDecoration, this.verticalContentPadding = 10, this.password = false}) : _txtCtrl = txtCtrl, _hintText = hintText, super(key: key); final TextEditingController _txtCtrl; final String _hintText; final bool password; final Color txtColor; final BoxDecoration boxDecoration; final double verticalContentPadding; @override Widget build(BuildContext context) { return Container( decoration: boxDecoration, child: TextFormField( style: getTextStyle( color: txtColor, fontSize: LARGE_MINUS_FONT_SIZE, fontWeight: FontWeight.w600), controller: _txtCtrl, cursorColor: DARK_GREY_COLOR, autocorrect: false, textInputAction: TextInputAction.next, // textAlignVertical: TextAlignVertical.bottom, obscureText: password, decoration: InputDecoration( hintText: _hintText, hintStyle: getHintStyle(), focusColor: DARK_GREY_COLOR, contentPadding: paddingXY(x: 16, y: verticalContentPadding), border: InputBorder.none, ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/app_logo.dart
// import 'package:nb_pos/constants/app_constants.dart'; // import 'package:nb_pos/constants/asset_paths.dart'; // import 'package:flutter/material.dart'; // Widget get appLogo => const Center( // child: SizedBox( // width: APP_LOGO_WIDTH, child: Image(image: AssetImage(APP_LOGO))));
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/item_options.dart
import 'package:flutter/material.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../core/mobile/add_products/ui/added_product_item.dart'; import '../database/models/attribute.dart'; import '../database/models/option.dart'; import '../database/models/order_item.dart'; import '../main.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/spacer_widget.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class ItemOptions extends StatefulWidget { OrderItem orderItem; ItemOptions({Key? key, required this.orderItem}) : super(key: key); @override State<ItemOptions> createState() => _ItemOptionsState(); } class _ItemOptionsState extends State<ItemOptions> { double itemTotal = 0; int qty = 0; _calculateItemPrice() { itemTotal = widget.orderItem.price; OrderItem item = widget.orderItem; if (widget.orderItem.attributes.isNotEmpty) { for (var attribute in item.attributes) { for (var option in attribute.options) { if (option.selected) { itemTotal = (itemTotal + option.price); } } } itemTotal = itemTotal * widget.orderItem.orderedQuantity; } else { itemTotal = item.price * widget.orderItem.orderedQuantity; } } @override void initState() { super.initState(); _calculateItemPrice(); } @override Widget build(BuildContext context) { return Center( child: Material( type: MaterialType.transparency, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, ), //height: MediaQuery.of(context).size.height * 0.8, width: isTabletMode ? MediaQuery.of(context).size.width / 2 : MediaQuery.of(context).size.width * 0.9, padding: morePaddingAll(), child: Column( mainAxisSize: MainAxisSize.min, children: [ SingleChildScrollView( child: Column( children: [ AddedProductItem( product: widget.orderItem, onDelete: () {}, disableDeleteOption: true, isUsedinVariantsPopup: true, onItemAdd: () { debugPrint("Stock count: ${widget.orderItem.stock}"); setState(() { if (widget.orderItem.orderedQuantity < widget.orderItem.stock || widget.orderItem.stock == 0) { widget.orderItem.orderedQuantity = widget.orderItem.orderedQuantity + 1; _calculateItemPrice(); // _selectedCustomerSection(); } }); }, onItemRemove: () { setState(() { if (widget.orderItem.orderedQuantity > 1) { widget.orderItem.orderedQuantity = widget.orderItem.orderedQuantity - 1; _calculateItemPrice(); } }); }, ), hightSpacer30, SizedBox( height: 200, child: ListView.builder( primary: false, itemCount: widget.orderItem.attributes.length, itemBuilder: (context, index) { return _optionSection( widget.orderItem.attributes[index]); }, ), ), ], )), Align( alignment: Alignment.bottomCenter, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: GREEN_COLOR, ), child: ListTile( dense: true, onTap: () { Navigator.pop(context, true); }, title: Text( "Item Total", style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, color: WHITE_COLOR, fontWeight: FontWeight.bold), ), subtitle: Text( "$appCurrency ${itemTotal.toStringAsFixed(2)}", style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w600, color: WHITE_COLOR)), trailing: Text("Add Item", style: getTextStyle( fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.bold, color: WHITE_COLOR)), ), ), ) ], ), ), ), ); } _optionsItems(Attribute attribute, int index) { Option option = attribute.options[index]; return InkWell( onTap: () => _handleOptionSelection(attribute, index), child: Padding( padding: verticalSpace(x: 5), child: Row( children: [ option.selected ? Visibility( visible: true, child: Container( clipBehavior: Clip.antiAlias, decoration: BoxDecoration( border: Border.all(color: MAIN_COLOR), // border: Border.all(color: Colors.yellow.shade800), color: MAIN_COLOR, // color: Colors.yellow.shade800, borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_06), ), child: const Icon( Icons.check, size: 18.0, color: WHITE_COLOR, )), ) : Container( clipBehavior: Clip.antiAlias, decoration: BoxDecoration( border: Border.all(color: BLACK_COLOR), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_06), ), child: const Icon( null, size: 20.0, ), ), widthSpacer(5), Text( option.name, style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.normal), ), const Spacer(), Text( "$appCurrency ${option.price.toStringAsFixed(2)}", style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.normal), ), ], ), ), ); } _optionSection(Attribute attribute) { return Padding( padding: isTabletMode ? horizontalSpace() : horizontalSpace(x: 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( attribute.name, style: getTextStyle(fontSize: MEDIUM_FONT_SIZE), ), SizedBox( height: attribute.options.length * 50, child: ListView.builder( primary: false, physics: const BouncingScrollPhysics(), padding: verticalSpace(), itemCount: attribute.options.length, itemBuilder: (context, index) { return _optionsItems(attribute, index); }, ), ), ], ), ); } _handleOptionSelection(Attribute attribute, int index) { Option option = attribute.options[index]; debugPrint("index: $index"); if (attribute.type == "Multiselect") { debugPrint("Checkbox type functionality"); if (attribute.moq > 0) { //TODO::: Do work here debugPrint( "check to see that atleast ${attribute.moq} options are selected"); } else { setState(() { option.selected = !option.selected; if (option.selected) { double optionsTotal = option.price * widget.orderItem.orderedQuantity; itemTotal = itemTotal + optionsTotal; //itemTotal = itemTotal * widget.orderItem.orderedQuantity; } else { double optionsTotal = option.price * widget.orderItem.orderedQuantity; itemTotal = itemTotal - optionsTotal; //itemTotal = itemTotal * widget.orderItem.orderedQuantity; } }); } } else { debugPrint("Radio button type functionality"); for (var i = 0; i < attribute.options.length; i++) { var opt = attribute.options[i]; if (i == index) { if (!opt.selected) { opt.selected = true; widget.orderItem.orderedPrice = widget.orderItem.orderedPrice + opt.price; } } else { if (opt.selected) { opt.selected = false; widget.orderItem.orderedPrice = widget.orderItem.orderedPrice - opt.price; } } } setState(() {}); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/product_shimmer_widget.dart
import 'package:flutter/material.dart'; import 'package:shimmer/shimmer.dart'; import '../utils/ui_utils/card_border_shape.dart'; class ProductShimmer extends StatefulWidget { const ProductShimmer({Key? key}) : super(key: key); @override State<ProductShimmer> createState() => _ProductShimmerState(); } class _ProductShimmerState extends State<ProductShimmer> { @override Widget build(BuildContext context) { return Shimmer.fromColors( baseColor: Colors.grey[300]!, highlightColor: Colors.grey[100]!, child: Card( shape: cardBorderShape(), elevation: 2.0, clipBehavior: Clip.antiAliasWithSaveLayer, child: Container( height: 500, ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/button.dart
import 'package:flutter/material.dart'; import 'package:nb_posx/utils/ui_utils/padding_margin.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; class ButtonWidget extends StatelessWidget { final GestureTapCallback onPressed; final String title; final Color colorBG; final double width; final double height; final double fontSize; final Color colorTxt; final double borderRadius; const ButtonWidget( {Key? key, required this.onPressed, this.colorBG = MAIN_COLOR, this.colorTxt = WHITE_COLOR, this.fontSize = 16, this.height = 50, required this.title, this.borderRadius = BORDER_CIRCULAR_RADIUS_07, this.width = 250}) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: onPressed, child: Container( margin: EdgeInsets.all(20), width: width, height: height, decoration: BoxDecoration( color: colorBG, borderRadius: BorderRadius.circular(borderRadius), ), child: Center( child: Text( title, // textAlign: TextAlign.center, style: getTextStyle( color: colorTxt, fontSize: fontSize, fontWeight: FontWeight.w600), ), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/long_button_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../constants/asset_paths.dart'; import '../utils/ui_utils/card_border_shape.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/spacer_widget.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class LongButton extends StatefulWidget { final String buttonTitle; final bool isAmountAndItemsVisible; String? totalAmount; String? totalItems; bool isTab; Function? onTap; LongButton( {Key? key, required this.isAmountAndItemsVisible, required this.buttonTitle, this.totalAmount, this.isTab=false, this.totalItems, this.onTap}) : super(key: key); @override State<LongButton> createState() => _LongButtonState(); } class _LongButtonState extends State<LongButton> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10), child: SizedBox( height: 60, child: Card( clipBehavior: Clip.antiAliasWithSaveLayer, shape: cardBorderShape(), child: Container( decoration: BoxDecoration( gradient: widget.isAmountAndItemsVisible ? LinearGradient( begin: const Alignment(0.0, 0.5), end: const Alignment(0.5, 0.5), stops: const [ 0.0, 0.0, ], colors: [ MAIN_COLOR, MAIN_COLOR.withOpacity(0.9) ]) : const LinearGradient( begin: Alignment(0.0, 0.5), end: Alignment(0.5, 0.5), stops: [0.0, 0.0], colors: [MAIN_COLOR, MAIN_COLOR], )), child: Padding( padding: mediumPaddingAll(), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.center, children: [ Visibility( visible: widget.isAmountAndItemsVisible, child: Expanded( flex: 20, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ SvgPicture.asset( CREATE_ORDER_BASKET_IMAGE, height: 25, width: 25, fit: BoxFit.contain, ), widthSpacer(5), Text( '${widget.totalItems}\n$ITEMS_TXT', style: getTextStyle( color: WHITE_COLOR, fontWeight: FontWeight.normal), ) ], ))), Visibility( visible: widget.isAmountAndItemsVisible, child: Expanded( flex: 25, child: Text( '$appCurrency${widget.totalAmount}', style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, color: WHITE_COLOR), maxLines: 2, overflow: TextOverflow.ellipsis, ))), Expanded( flex: 50, child: TextButton( onPressed: () => widget.onTap!(), child: Text(widget.buttonTitle, style: getTextStyle( fontSize:widget.isTab? MEDIUM_PLUS_FONT_SIZE:MEDIUM_MINUS_FONT_SIZE, fontWeight: FontWeight.bold, color: WHITE_COLOR, ))), ) ], ), ))))); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/main_drawer.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../constants/asset_paths.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/spacer_widget.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class MainDrawer extends StatelessWidget { List<Map> menuItem; MainDrawer({Key? key, required this.menuItem}) : super(key: key); @override Widget build(BuildContext context) { return Drawer( child: ListView( children: [ Container( color: MAIN_COLOR, padding: morePaddingAll(), child: Row( children: [ SvgPicture.asset( MENU_ICON, color: WHITE_COLOR, width: 20, ), widthSpacer(10), Text( "Menu", style: getTextStyle( color: WHITE_COLOR, fontSize: LARGE_FONT_SIZE, fontWeight: FontWeight.w400), ), const Spacer(), InkWell( onTap: () { Navigator.pop(context); }, child: Padding( padding: miniPaddingAll(), child: SvgPicture.asset( CROSS_ICON, color: WHITE_COLOR, width: 15, ), ), ) ], ), ), hightSpacer20, ListView.builder( itemCount: menuItem.length, shrinkWrap: true, itemBuilder: (context, position) { return _buildMenuItem(context, menuItem[position]["title"], menuItem[position]["action"]); }), // _buildMenuItem(context, "Create new sale", () async { // Navigator.pop(context); // Navigator.popUntil(context, (route) => route.isFirst); // Navigator.push(context, // MaterialPageRoute(builder: (context) => NewCreateOrder())); // }), // _buildMenuItem(context, "Parked orders", () async { // Navigator.pop(context); // // Navigator.popUntil(context, (route) => route.isFirst); // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => const OrderListScreen())); // }), // _buildMenuItem(context, "Home", () { // Navigator.popUntil(context, (route) => route.isFirst); // }), ], ), ); } _buildMenuItem(BuildContext context, String title, VoidCallback onTap) { return InkWell( onTap: onTap, child: Padding( padding: paddingXY(x: 15), child: Text( title, style: getTextStyle( fontWeight: FontWeight.w400, color: DARK_GREY_COLOR, fontSize: MEDIUM_FONT_SIZE), ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/customer_tile.dart
import 'package:flutter/material.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../database/models/customer.dart'; import '../main.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; typedef OnCheckChangedCallback = void Function(bool isChanged); // ignore: must_be_immutable class CustomerTile extends StatefulWidget { bool? isCheckBoxEnabled; bool? isDeleteButtonEnabled; bool? isSubtitle; bool? checkCheckBox; bool? checkBoxValue; bool? isHighlighted; int? selectedPosition; Function(bool)? onCheckChanged; Customer? customer; bool isNumVisible; CustomerTile( {Key? key, required this.isCheckBoxEnabled, required this.isDeleteButtonEnabled, required this.isSubtitle, required this.customer, this.checkCheckBox, this.checkBoxValue, this.onCheckChanged, this.isNumVisible = true, this.isHighlighted = false, this.selectedPosition}) : super(key: key); @override State<CustomerTile> createState() => _CustomerTileState(); } class _CustomerTileState extends State<CustomerTile> { bool isSelected = false; @override void initState() { isSelected = widget.isHighlighted!; super.initState(); } @override Widget build(BuildContext context) { var container = Container( margin: const EdgeInsets.fromLTRB(10, 10, 10, 10), padding: mediumPaddingAll(), decoration: BoxDecoration( color: isTabletMode ? const Color(0xFFF9F8FB) : isSelected ? OFF_WHITE_COLOR : WHITE_COLOR, border: Border.all( color: isSelected ? MAIN_COLOR : GREY_COLOR, width: isSelected ? 0.3 : 1.0), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_08)), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( // crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Padding( padding: horizontalSpace(), child: Text( widget.customer != null ? widget.customer!.name : "Guest", style: getTextStyle( fontSize: MEDIUM_PLUS_FONT_SIZE, color: MAIN_COLOR, fontWeight: widget.isHighlighted! ? FontWeight.bold : FontWeight.normal), maxLines: 2, overflow: TextOverflow.ellipsis), ), ), Visibility( visible: widget.isNumVisible, child: Padding( padding: miniPaddingAll(), child: Text( widget.customer != null ? widget.customer!.phone : "", style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, color: DARK_GREY_COLOR, fontWeight: FontWeight.bold), ), ), ), ], ), Padding( padding: horizontalSpace(), child: Text( widget.customer != null ? widget.customer!.email : "", style: getTextStyle( color: BLACK_COLOR, fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.normal), ), ), ], ), ); return widget.isCheckBoxEnabled! ? InkWell( onTap: () { if (widget.isCheckBoxEnabled!) { setState(() { isSelected = !isSelected; widget.onCheckChanged!(isSelected); }); } }, child: container, ) : container; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/right_header_curve.dart
import 'dart:io'; import 'package:flutter/material.dart'; import '../configs/theme_config.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class RightHeaderCurveWidget extends StatelessWidget { late double _widgetHeight; late double _curveHeight; RightHeaderCurveWidget({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { _widgetHeight = Platform.isIOS ? 3.5 : 3.8; _curveHeight = Platform.isIOS ? 4.2 : 3.8; return SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height / _widgetHeight, child: Stack( // overflow: Overflow.visible, children: [ CustomPaint( size: Size(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height / _curveHeight), painter: HeaderCurve(), ), Center( child: Text( "POS", style: getTextStyle(color: WHITE_COLOR, fontSize: 40.0), )) ], ), ); } } class HeaderCurve extends CustomPainter { @override void paint(Canvas canvas, Size size) { Paint paint0 = Paint() ..color = MAIN_COLOR ..style = PaintingStyle.fill ..strokeWidth = 1; Path path0 = Path(); path0.moveTo(0, 0); path0.lineTo(size.width * 0.9988750, size.height * 0.0009600); path0.lineTo(size.width * 0.9989125, size.height * 0.6018400); path0.quadraticBezierTo(size.width * 0.4941750, size.height * 1.1578000, size.width * 0.0012500, size.height * 0.5960000); path0.quadraticBezierTo( size.width * 0.0009375, size.height * 0.4470000, 0, 0); path0.close(); canvas.drawPath(path0, paint0); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return true; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/product_widget.dart
import 'dart:developer'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:intl/intl.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../constants/asset_paths.dart'; import '../database/models/product.dart'; import '../utils/helper.dart'; import '../utils/ui_utils/box_shadow.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class ProductWidget extends StatefulWidget { bool enableAddProductButton; String? title; Uint8List? asset; Product? product; Function? onAddToCart; ProductWidget( {Key? key, this.enableAddProductButton = false, this.title, this.asset, this.product, this.onAddToCart}) : super(key: key); @override State<ProductWidget> createState() => _ProductWidgetState(); } class _ProductWidgetState extends State<ProductWidget> { late double stockQty; String? price; String? productStockUpdateDate; @override void initState() { stockQty = widget.product!.stock > 0 ? widget.product!.stock : 0; price = Helper().formatCurrency(widget.product!.price); productStockUpdateDate = _getDateTimeString(); super.initState(); } @override Widget build(BuildContext context) { return InkWell( onTap: () {}, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_20), boxShadow: [boxShadow], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: widget.enableAddProductButton ? 100 : 120, decoration: BoxDecoration( color: MAIN_COLOR.withOpacity(.1), borderRadius: const BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(10), )), child: Center( child: _getProductImage(), ), ), Padding( padding: const EdgeInsets.only(left: 10, top: 5), child: Text( widget.product!.name, style: getTextStyle(fontSize: MEDIUM_MINUS_FONT_SIZE), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), Padding( padding: const EdgeInsets.only(left: 10, top: 2), child: Text("$ITEM_CODE_TXT - ${widget.product!.id}", style: getItalicStyle( color: LIGHT_GREY_COLOR, fontSize: SMALL_MINUS_FONT_SIZE, )), ), Padding( padding: const EdgeInsets.only(left: 10, top: 8, bottom: 5), child: Text("$appCurrency $price", style: getTextStyle( color: MAIN_COLOR, fontWeight: FontWeight.w600, fontSize: MEDIUM_MINUS_FONT_SIZE)), ), Padding( padding: leftSpace(x: 10), child: Text( "$ADD_PRODUCTS_AVAILABLE_STOCK_TXT - ${stockQty.round()}", style: getTextStyle( color: DARK_GREY_COLOR, fontWeight: FontWeight.w400)), ), Visibility( visible: !widget.enableAddProductButton, child: Padding( padding: const EdgeInsets.only(left: 10, top: 2), child: Text( "$ADD_PRODUCTS_STOCK_UPDATE_ON_TXT $productStockUpdateDate", maxLines: 2, style: getItalicStyle( color: LIGHT_GREY_COLOR, fontSize: SMALL_MINUS_FONT_SIZE, )), )), Visibility( visible: widget.enableAddProductButton, child: Padding( padding: const EdgeInsets.only(top: 6, bottom: 10), child: SizedBox( child: Container( color: GREY_COLOR, height: 0.2, ), ))), Visibility( visible: widget.enableAddProductButton, child: InkWell( child: Center( child: Text( stockQty < 1 ? OUT_OF_STOCK : ADD_PRODUCT_TXT, style: getTextStyle(fontWeight: FontWeight.w500), )), onTap: () => widget.onAddToCart!(), ), ) ], ), ), ); } _getProductImage() { if (widget.asset != null && widget.asset!.isNotEmpty) { return Image.memory( widget.asset!, height: widget.enableAddProductButton ? 60 : 70, ); } else { return SvgPicture.asset( PRODUCT_IMAGE, height: widget.enableAddProductButton ? 60 : 70, ); } } _getDateTimeString() { String productUpdateDate = DateFormat.yMd().add_jm().format(widget.product!.productUpdatedTime); log('Formatted Date : $productUpdateDate'); return productUpdateDate; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/header_curve.dart
import 'dart:io'; import 'package:flutter/material.dart'; import '../configs/theme_config.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; // ignore: must_be_immutable class HeaderCurveWidget extends StatelessWidget { late double _widgetHeight; late double _curveHeight; HeaderCurveWidget({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { _widgetHeight = Platform.isIOS ? 3.5 : 3.8; _curveHeight = Platform.isIOS ? 4.2 : 3.8; return SizedBox( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height / _widgetHeight, child: Stack( // overflow: Overflow.visible, children: [ CustomPaint( size: Size(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height / _curveHeight), painter: HeaderCurve(), ), Center( child: Text( "POS", style: getTextStyle(color: WHITE_COLOR, fontSize: 40.0), )) ], ), ); } } class HeaderCurve extends CustomPainter { @override void paint(Canvas canvas, Size size) { Paint paint0 = Paint() ..color = MAIN_COLOR ..style = PaintingStyle.fill ..strokeWidth = 1; Path path0 = Path(); path0.moveTo(0, 0); path0.lineTo(size.width * 0.9988750, size.height * 0.0009600); path0.lineTo(size.width * 0.9989125, size.height * 0.6018400); path0.quadraticBezierTo(size.width * 0.4941750, size.height * 1.1578000, size.width * 0.0012500, size.height * 0.5960000); path0.quadraticBezierTo( size.width * 0.0009375, size.height * 0.4470000, 0, 0); path0.close(); canvas.drawPath(path0, paint0); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return true; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/popup_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:hive/hive.dart'; import 'package:nb_posx/database/db_utils/db_constants.dart'; import 'package:nb_posx/database/models/category.dart'; import 'package:nb_posx/database/models/hub_manager.dart'; import 'package:nb_posx/database/models/order_item.dart'; import 'package:nb_posx/database/models/park_order.dart'; import 'package:nb_posx/database/models/product.dart'; import 'package:nb_posx/database/models/sale_order.dart'; import 'package:nb_posx/utils%20copy/helper.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../database/models/customer.dart'; import '../utils/ui_utils/card_border_shape.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/spacer_widget.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; class SimplePopup extends StatefulWidget { final String message; final String buttonText; final Function onOkPressed; final bool hasCancelAction; bool? barrier = false; SimplePopup( {Key? key, required this.message, this.barrier, required this.buttonText, required this.onOkPressed, this.hasCancelAction = false}) : super(key: key); @override State<SimplePopup> createState() => _SimplePopupState(); } Box<dynamic>? box; class _SimplePopupState extends State<SimplePopup> { @override Widget build(BuildContext context) { return WillPopScope( onWillPop: widget.barrier == true ? _onBackPressed : _onBack, child: Container( height: 100, margin: morePaddingAll(x: 20), child: Center( child: Card( shape: cardBorderShape(), child: Column( mainAxisSize: MainAxisSize.min, children: [ hightSpacer15, Text( widget.message, textAlign: TextAlign.center, style: getTextStyle(fontSize: MEDIUM_PLUS_FONT_SIZE), ), hightSpacer20, const Divider(), widget.hasCancelAction ? SizedBox( height: 30, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ InkWell( onTap: () => widget.onOkPressed(), child: SizedBox( width: MediaQuery.of(context).size.width / 2.5, child: Center( child: Text( widget.buttonText, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE), )))), const VerticalDivider( thickness: 1, ), InkWell( onTap: () => Navigator.of(context).pop(), child: SizedBox( width: MediaQuery.of(context).size.width / 2.5, child: Center( child: Text( OPTION_CANCEL, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE, color: DARK_GREY_COLOR), )))) ], ), ) : InkWell( onTap: () => widget.onOkPressed(), child: SizedBox( height: 20, width: MediaQuery.of(context).size.width - 30, child: Center( child: Text( widget.buttonText, style: getTextStyle( fontSize: MEDIUM_MINUS_FONT_SIZE), )))), hightSpacer10 ], ), )))); } /// HANDLE BACK BTN PRESS ON LOGIN SCREEN Future<bool> _onBackPressed() async { deleteCustomer(); deleteHubManager(); deleteProduct(); deleteSales(); deleteParkedOrder(); deleteCategory(); deleteCustomer(); deleteURL(); deleteOrderItem(); SystemNavigator.pop(); return false; } Future<bool> _onBack() async { return true; } } Future<void> deleteCustomer() async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); await box!.clear(); box!.close(); } Future<void> deleteHubManager() async { box = await Hive.openBox<HubManager>(HUB_MANAGER_BOX); await box!.clear(); box!.close(); } Future<void> deleteProduct() async { box = await Hive.openBox<Product>(PRODUCT_BOX); await box!.clear(); box!.close(); } Future<void> deleteSales() async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); await box!.clear(); box!.close(); } Future<void> deleteParkedOrder() async { box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); await box!.clear(); box!.close(); } Future<void> deleteCategory() async { box = await Hive.openBox<Category>(CATEGORY_BOX); await box!.clear(); box!.close(); } Future<void> deleteOrderItem() async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); await box!.clear(); box!.close(); } Future<void> deleteURL() async { box = await Hive.openBox<String>(URL_BOX); await box!.clear(); box!.close(); }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/shimmer_widget.dart
import 'package:flutter/material.dart'; import 'package:shimmer/shimmer.dart'; import '../utils/ui_utils/card_border_shape.dart'; class ShimmerWidget extends StatefulWidget { const ShimmerWidget({Key? key}) : super(key: key); @override ShimmerWidgetState createState() => ShimmerWidgetState(); } class ShimmerWidgetState extends State<ShimmerWidget> { @override Widget build(BuildContext context) { return Shimmer.fromColors( enabled: true, baseColor: Colors.grey[300]!, highlightColor: Colors.grey[100]!, child: Padding( padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10), child: Card( shape: cardBorderShape(), elevation: 2.0, clipBehavior: Clip.antiAliasWithSaveLayer, child: Container( color: Colors.grey[300]!, child: SizedBox( height: 65, width: MediaQuery.of(context).size.width, ), ))), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/custom_appbar.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../constants/asset_paths.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; class CustomAppbar extends StatelessWidget { final String title; final bool showBackBtn; final bool hideSidemenu; final Color backBtnColor; const CustomAppbar( {Key? key, required this.title, this.showBackBtn = true, this.hideSidemenu = false, this.backBtnColor = BLACK_COLOR}) : super(key: key); @override Widget build(BuildContext context) { TextStyle headerStyle = getTextStyle(fontSize: LARGE_MINUS_FONT_SIZE, color: DARK_GREY_COLOR); return Padding( padding: const EdgeInsets.only(top: 5, bottom: 5, left: 5), child: showBackBtn ? Row( children: [ InkWell( onTap: () => Navigator.pop(context), child: Padding( padding: smallPaddingAll(), child: SvgPicture.asset( BACK_IMAGE, color: backBtnColor, width: 25, ), ), ), const Spacer( flex: 2, ), Padding( padding: smallPaddingAll(), child: Text( title, style: headerStyle, ), ), const Spacer( flex: 2, ), hideSidemenu ? _getBlankSideMenu() : _getSideMenu(context) ], ) : Center( child: Padding( padding: smallPaddingAll(), child: Text( title, style: headerStyle, ), ), ), ); } _getBlankSideMenu() { // return Padding( // padding: mediumPaddingAll(), // child: SvgPicture.asset( // MENU_ICON, // color: WHITE_COLOR, // width: 20, // ), // ); return Container(width: 30); } _getSideMenu(context) { return InkWell( onTap: () { debugPrint("Menu Clicked "); Scaffold.of(context).openEndDrawer(); }, child: Padding( padding: mediumPaddingAll(), child: SvgPicture.asset( MENU_ICON, color: backBtnColor, width: 20, ), ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/search_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:get/get.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../constants/asset_paths.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; import '../utils/ui_utils/text_styles/edit_text_hint_style.dart'; import '../utils/ui_utils/textfield_border_decoration.dart'; // ignore: must_be_immutable class SearchWidget extends StatefulWidget { final String? searchHint; final TextEditingController? searchTextController; Function(String changedtext)? onTextChanged; Function(String text)? onSubmit; List<TextInputFormatter>? inputFormatters = []; final TextInputType keyboardType; VoidCallback? onTap; VoidCallback? submit; SearchWidget( {Key? key, this.searchHint, this.onTap, this.searchTextController, this.inputFormatters, this.onTextChanged, this.onSubmit, this.submit, this.keyboardType = TextInputType.text}) : super(key: key); @override State<SearchWidget> createState() => _SearchWidgetState(); } class _SearchWidgetState extends State<SearchWidget> { @override Widget build(BuildContext context) { return Container( decoration: searchTxtFieldBorderDecoration, child: TextField( onTap: widget.onTap, style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.normal), cursorColor: BLACK_COLOR, controller: widget.searchTextController, keyboardType: widget.keyboardType, inputFormatters: widget.inputFormatters, textAlignVertical: TextAlignVertical.center, textInputAction: TextInputAction.done, autocorrect: true, decoration: InputDecoration( hintText: widget.searchHint ?? SEARCH_HINT_TXT, contentPadding: const EdgeInsets.only(left: 10, right: 10), isDense: true, suffixIconColor: WHITE_COLOR, prefix: Padding(padding: leftSpace(x: 5)), suffixIcon: GestureDetector( onTap: () => widget.submit!(), child: SvgPicture.asset( SEARCH_IMAGE, width: 30, ), ), // suffixIcon: widget.searchTextController!.text.isNotEmpty // ? IconButton( // onPressed: () { // setState(() { // widget.searchTextController!.text = ""; // }); // }, // icon: Padding( // padding: rightSpace(), // child: const Icon( // Icons.close, // color: DARK_GREY_COLOR, // ), // )) // : null, hintStyle: getHintStyle(), focusColor: LIGHT_GREY_COLOR, border: InputBorder.none, ), onSubmitted: (text) => widget.onSubmit!(text), onChanged: (updatedText) { setState(() { widget.onTextChanged!(updatedText); }); }, ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/comman_tile_options.dart
import 'package:flutter/material.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../database/models/customer.dart'; import '../utils/ui_utils/card_border_shape.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; typedef OnCheckChangedCallback = void Function(bool isChanged); // ignore: must_be_immutable class CommanTileOptions extends StatefulWidget { bool? isCheckBoxEnabled; bool? isDeleteButtonEnabled; bool? isSubtitle; bool? checkCheckBox; bool? checkBoxValue; int? selectedPosition; Function(bool)? onCheckChanged; Customer? customer; CommanTileOptions( {Key? key, required this.isCheckBoxEnabled, required this.isDeleteButtonEnabled, required this.isSubtitle, required this.customer, this.checkCheckBox, this.checkBoxValue, this.onCheckChanged, this.selectedPosition}) : super(key: key); @override State<CommanTileOptions> createState() => _CommanTileOptionsState(); } class _CommanTileOptionsState extends State<CommanTileOptions> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10), child: Card( shape: cardBorderShape(), elevation: 2.0, child: ListTile( leading: SizedBox( height: 70, width: 70, child: Card( color: MAIN_COLOR.withOpacity(.1), shape: cardBorderShape(), elevation: 0.0, child: Container(), // child: Padding( // padding: mediumPaddingAll(), // child: widget.customer!.customerImageUrl!.isNotEmpty // ? Image.network(widget.customer!.customerImageUrl!) // : widget.customer!.profileImage.isEmpty // ? SvgPicture.asset( // HOME_CUSTOMER_IMAGE, // height: 30, // width: 30, // fit: BoxFit.contain, // ) // : Image.memory( // widget.customer!.profileImage, // // height: widget.enableAddProductButton ? 60 : 70, // )), ), ), title: Text(widget.customer!.name, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w600), maxLines: 2, overflow: TextOverflow.ellipsis), subtitle: Visibility( visible: widget.isSubtitle!, child: Text( widget.customer!.phone, style: getTextStyle( fontSize: SMALL_PLUS_FONT_SIZE, fontWeight: FontWeight.w500), )), trailing: _getTrailingWidget, ), ), ); } Widget? get _getTrailingWidget { if (widget.isCheckBoxEnabled!) { return InkWell( onTap: () => widget.onCheckChanged!(widget.checkBoxValue!), child: widget.checkBoxValue! ? Container( clipBehavior: Clip.antiAlias, decoration: BoxDecoration( border: Border.all(color: MAIN_COLOR), // border: Border.all(color: Colors.yellow.shade800), color: MAIN_COLOR, // color: Colors.yellow.shade800, borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_06), ), child: const Icon( Icons.check, size: 20.0, color: WHITE_COLOR, )) : Container( decoration: BoxDecoration( border: Border.all(color: BLACK_COLOR), borderRadius: BorderRadius.circular(BORDER_CIRCULAR_RADIUS_06), ), child: const Icon( null, size: 20.0, ), ), ); } else { return const Icon( Icons.delete_outline_sharp, size: 1, ); } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib
mirrored_repositories/GETPOS-Flutter-App/lib/widgets/search_widget_tablet.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../configs/theme_config.dart'; import '../constants/app_constants.dart'; import '../constants/asset_paths.dart'; import '../utils/ui_utils/padding_margin.dart'; import '../utils/ui_utils/text_styles/custom_text_style.dart'; import '../utils/ui_utils/text_styles/edit_text_hint_style.dart'; import '../utils/ui_utils/textfield_border_decoration.dart'; // ignore: must_be_immutable class SearchWidgetTablet extends StatefulWidget { final String? searchHint; final TextEditingController? searchTextController; Function(String changedtext)? onTextChanged; Function(String text)? onSubmit; TextInputType keyboardType; List<TextInputFormatter>? inputFormatter; FocusNode? focusNode; SearchWidgetTablet( {Key? key, this.searchHint,this.focusNode, this.searchTextController, this.onTextChanged, this.onSubmit, this.keyboardType = TextInputType.text, this.inputFormatter}) : super(key: key); @override State<SearchWidgetTablet> createState() => _SearchWidgetTabletState(); } class _SearchWidgetTabletState extends State<SearchWidgetTablet> { @override Widget build(BuildContext context) { return Container( decoration: searchTxtFieldBorderDecoration, child: TextField( focusNode: widget.focusNode, style: getTextStyle( fontSize: MEDIUM_FONT_SIZE, fontWeight: FontWeight.normal), cursorColor: BLACK_COLOR, controller: widget.searchTextController, textAlignVertical: TextAlignVertical.center, textInputAction: TextInputAction.done, autocorrect: true, decoration: InputDecoration( hintText: widget.searchHint ?? SEARCH_HINT_TXT, contentPadding: const EdgeInsets.only(left: 10, right: 10), isDense: true, prefixIconColor: WHITE_COLOR, prefix: Padding(padding: leftSpace(x: 10)), prefixIcon: SvgPicture.asset( SEARCH_IMAGE, width: 30, ), // suffixIcon: widget.searchTextController!.text.isNotEmpty // ? IconButton( // onPressed: () { // setState(() { // widget.searchTextController!.text = ""; // }); // }, // icon: Padding( // padding: rightSpace(), // child: const Icon( // Icons.close, // color: DARK_GREY_COLOR, // ), // )) // : null, hintStyle: getHintStyle(), focusColor: LIGHT_GREY_COLOR, border: InputBorder.none, ), onSubmitted: (text) => widget.onSubmit!(text), onChanged: (updatedText) => widget.onTextChanged!(updatedText), inputFormatters: widget.inputFormatter, ), ); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_categories.dart
import 'package:hive_flutter/hive_flutter.dart'; import '../models/category.dart'; import '../models/order_item.dart'; import 'db_constants.dart'; class DbCategory { late Box box; Future<void> addCategory(List<Category> list) async { box = await Hive.openBox<Category>(CATEGORY_BOX); for (Category cat in list) { await box.put(cat.id, cat); } } Future<List<Category>> getCategories() async { box = await Hive.openBox<Category>(CATEGORY_BOX); List<Category> list = []; for (var item in box.values) { var cat = item as Category; list.add(cat); } return list; } Future<void> reduceInventory(List<OrderItem> items) async { box = await Hive.openBox<Category>(CATEGORY_BOX); for (OrderItem orderItem in items) { for (var item in box.values) { Category cat = item as Category; if (cat.name == orderItem.group) { for (var catItem in cat.items) { if (catItem.name == orderItem.name && catItem.stock != -1 && catItem.stock != 0) { var availableQty = catItem.stock - orderItem.orderedQuantity; catItem.stock = availableQty; catItem.productUpdatedTime = DateTime.now(); await cat.save(); } } } } } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_parked_order.dart
import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; import '../models/order_item.dart'; import '../models/park_order.dart'; import 'db_constants.dart'; import 'db_order_item.dart'; class DbParkedOrder { late Box box; Future<String> createOrder(ParkOrder order) async { String res = await saveOrder(order); // DBPreferences().incrementOrderNo(order.id); DbOrderItem().reduceInventory(order.items); await box.close(); return res; } // Future<String> updateOrder(String newID, ParkOrder order) async { // box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); // String orderKey = _getOrderKey(order); // ParkOrder item = await box.get(orderKey); // item.id = newID; // item.save(); // return orderKey; // } Future<List<ParkOrder>> getOrders() async { // LazyBox box = await Hive.openLazyBox(PARKED_ORDER_BOX); box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); List<ParkOrder> list = []; for (var key in box.keys) { var item = await box.get(key); var order = item as ParkOrder; Future.forEach(order.items, (item) async { var product = item as OrderItem; OrderItem? pro = await DbOrderItem().getProductDetails(product.id); if (pro != null) { product.productImage = pro.productImage; } }); list.add(order); } // await box.close(); return list; } // Future<List<ParkOrder>> getOfflineOrders() async { // box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); // List<ParkOrder> list = []; // // print("TOTAL ORDERS: ${box.keys.length}"); // for (var key in box.keys) { // var item = await box.get(key); // var product = item as ParkOrder; // if (product.transactionSynced == false) list.add(product); // } // // await box.close(); // return list; // } // Future<double> getOfflineOrderCashBalance() async { // box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); // double cashBalance = 0; // // print("TOTAL ORDERS: ${box.keys.length}"); // for (var key in box.keys) { // var item = await box.get(key); // var product = item as ParkOrder; // if (product.transactionSynced == false) { // if (product.transactionId.isEmpty) { // cashBalance = cashBalance + product.orderAmount; // } // } // } // await box.close(); // return cashBalance; // } Future<String> saveOrder(ParkOrder order) async { box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); String orderKey = _getOrderKey(order); await box.put(orderKey, order); // await box.close(); return orderKey; } // Future<bool> saveOrders(List<ParkOrder> sales) async { // box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); // await Future.forEach(sales, (parkOrder) async { // ParkOrder order = parkOrder as ParkOrder; // String orderKey = _getOrderKey(order); // await box.put(orderKey, order); // }); // return true; // } Future<void> delete() async { box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); await box.clear(); await box.close(); } String _getOrderKey(ParkOrder order) { // return "${order.date}_${order.time}"; return "${order.transactionDateTime.millisecondsSinceEpoch}"; } Future<bool> deleteOrder(ParkOrder order) async { box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); String orderKey = _getOrderKey(order); ParkOrder parkOrder = box.get(orderKey); parkOrder.delete(); return true; } Future<bool> deleteOrderById(String orderId) async { try { box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); // String orderKey = _getOrderKey(order); ParkOrder parkOrder = box.get(orderId); parkOrder.delete(); } catch (e) { debugPrintStack(label: 'Delete order by ID'); } return true; } Future<bool> removeOrderItem(ParkOrder order, OrderItem item) async { try { box = await Hive.openBox<ParkOrder>(PARKED_ORDER_BOX); String orderKey = _getOrderKey(order); ParkOrder parkOrder = box.get(orderKey); for (OrderItem i in parkOrder.items) { if (i == item) { parkOrder.items.remove(i); break; } } return true; } catch (ex) { debugPrint("Exception occured while Removing item from order"); debugPrintStack(); return false; } } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_order_item.dart
import 'package:hive_flutter/hive_flutter.dart'; import '../models/order_item.dart'; import 'db_constants.dart'; class DbOrderItem { late Box box; Future<void> addProducts(List<OrderItem> list) async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); for (OrderItem item in list) { await box.put(item.id, item); } } Future<List<OrderItem>> getProducts() async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); List<OrderItem> list = []; for (var item in box.values) { var product = item as OrderItem; if (product.stock > 0 && product.price > 0) list.add(product); } return list; } Future<OrderItem?> getProductDetails(String key) async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); return box.get(key); } Future<void> reduceInventory(List<OrderItem> items) async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); for (OrderItem item in items) { OrderItem itemInDB = box.get(item.id) as OrderItem; var availableQty = itemInDB.stock - item.orderedQuantity; itemInDB.stock = availableQty; itemInDB.orderedQuantity = 0; itemInDB.productUpdatedTime = DateTime.now(); await itemInDB.save(); } } Future<int> deleteProducts() async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); return box.clear(); } Future<List<OrderItem>> getAllProducts() async { box = await Hive.openBox<OrderItem>(ORDER_ITEM_BOX); List<OrderItem> list = []; for (var item in box.values) { var product = item as OrderItem; if (product.stock > 0 && product.price > 0) list.add(product); } box.close(); return list; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_customer.dart
import 'package:hive_flutter/hive_flutter.dart'; import '../models/customer.dart'; import 'db_constants.dart'; class DbCustomer { late Box box; Future<void> addCustomers(List<Customer> list) async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); for (Customer c in list) { await box.put(c.id, c); } } Future<List<Customer>> getCustomers() async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); List<Customer> list = []; for (var item in box.values) { var customer = item as Customer; list.add(customer); } return list; } Future<List<Customer>> getOfflineCustomers() async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); List<Customer> list = []; for (var key in box.keys) { var item = await box.get(key); var customer = item as Customer; if (customer.isSynced == false) list.add(customer); } return list; } Future<List<Customer>> getCustomer(String mobileNo) async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); List<Customer> list = []; for (var item in box.values) { var customer = item as Customer; if (customer.phone == mobileNo) { list.add(customer); } } return list; } Future<List<Customer>> getCustomerNo(String mobileNo) async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); List<Customer> list = []; for (var item in box.values) { var customer = item as Customer; if (customer.phone.contains(mobileNo)) { list.add(customer); } } return list; } Future<Customer?> getCustomerDetails(String key) async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); return box.get(key); } Future<int> deleteCustomers() async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); return box.clear(); } Future<bool> deleteCustomer(String key) async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); Customer? customer = box.get(key); if (customer != null) customer.delete(); return true; } Future<void> updateCustomer(Customer customer) async { box = await Hive.openBox<Customer>(CUSTOMER_BOX); box.put(customer.id, customer); } // Future<int> deleteWardCustomer(String wardId) async { // box = await Hive.openBox<Customer>(CUSTOMER_BOX); // for (Customer customer in box.values) { // if (customer.ward.id == wardId) customer.delete(); // } // return 0; // } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_preferences.dart
import 'package:hive_flutter/hive_flutter.dart'; import 'db_constants.dart'; ///[DBPreferences] class to save the user preferences. ///We can save the preference as key - value pair. class DBPreferences { Box? prefBox; ///Function to save the preference into database. ///[key] -> Unique key to identify the value saved into database. ///NOTE : if [key] is not unique then it is replaced by existing one. ///[value] -> Data for the defined [key]. Future<void> savePreference(String key, dynamic value) async { //Open the PreferenceBox await _openPreferenceBox(); //Saving preference data into PreferenceBox database await prefBox!.put(key, value); //Close the PreferenceBox _closePreferenceBox(); } ///Function to get the saved user preference in database. ///[key] -> Unique key to be supplied to get the saved value. ///If key not exist then it will return blank string. Future<dynamic> getPreference(String key) async { //Open the PreferenceBox await _openPreferenceBox(); //Getting value by key. dynamic value = prefBox!.get(key, defaultValue: ''); //Close the PreferenceBox _closePreferenceBox(); //Return the value return value; } ///Open the PreferenceBox _openPreferenceBox() async { prefBox = await Hive.openBox(PREFERENCE_BOX); } ///Close the PreferenceBox _closePreferenceBox() async { //await prefBox!.close(); } Future<void> delete() async { prefBox = await Hive.openBox(PREFERENCE_BOX); await prefBox!.clear(); await prefBox!.close(); } Future<int> incrementOrderNo(String orderId) async { prefBox = await Hive.openBox(PREFERENCE_BOX); var list = orderId.split("-"); //String orderNo = list.last; String orderNo = list.elementAt(list.indexOf(list.last) - 1); if (orderNo.isEmpty) orderNo = "0001"; int newOrderNo = int.parse(orderNo) + 1; await savePreference(CURRENT_ORDER_NUMBER, "$newOrderNo"); return newOrderNo; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_instance_url.dart
import 'package:hive_flutter/hive_flutter.dart'; import 'package:nb_posx/database/db_utils/db_constants.dart'; import 'package:nb_posx/network/api_constants/api_paths.dart'; class DbInstanceUrl { late Box box; Future<void> saveUrl(String url) async { box = await Hive.openBox<String>(URL_BOX); await box.put(URL_KEY, url); } Future<String> getUrl() async { box = await Hive.openBox<String>(URL_BOX); String url = box.get(URL_KEY) ?? instanceUrl; return url; } Future<int> deleteUrl() async { box = await Hive.openBox<String>(URL_BOX); return await box.clear(); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_product.dart
import 'package:hive_flutter/hive_flutter.dart'; import '../models/order_item.dart'; import '../models/product.dart'; import 'db_constants.dart'; class DbProduct { late Box box; Future<void> addProducts(List<Product> list) async { box = await Hive.openBox<Product>(PRODUCT_BOX); for (Product item in list) { await box.put(item.id, item); } } Future<List<Product>> getProducts() async { box = await Hive.openBox<Product>(PRODUCT_BOX); List<Product> list = []; for (var item in box.values) { var product = item as Product; if (product.stock > 0 && product.price > 0) list.add(product); } return list; } Future<Product?> getProductDetails(String key) async { box = await Hive.openBox<Product>(PRODUCT_BOX); return box.get(key); } Future<void> reduceInventory(List<OrderItem> items) async { box = await Hive.openBox<Product>(PRODUCT_BOX); for (OrderItem item in items) { Product? itemInDB = await getProductDetails(item.id); var availableQty = itemInDB!.stock - item.orderedQuantity; itemInDB.stock = availableQty; // itemInDB.orderedQuantity = 0; itemInDB.productUpdatedTime = DateTime.now(); await itemInDB.save(); } } Future<int> deleteProducts() async { box = await Hive.openBox<Product>(PRODUCT_BOX); return box.clear(); } Future<List<Product>> getAllProducts() async { box = await Hive.openBox<Product>(PRODUCT_BOX); List<Product> list = []; for (var item in box.values) { var product = item as Product; if (product.stock > 0 && product.price > 0) list.add(product); } box.close(); return list; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_sale_order.dart
import 'package:hive_flutter/hive_flutter.dart'; import '../../constants/app_constants.dart'; import '../models/order_item.dart'; import '../models/product.dart'; import '../models/sale_order.dart'; import 'db_categories.dart'; import 'db_constants.dart'; import 'db_hub_manager.dart'; import 'db_order_item.dart'; import 'db_preferences.dart'; import 'db_product.dart'; class DbSaleOrder { late Box box; Future<String> createOrder(SaleOrder order) async { String res = await saveOrder(order); await DBPreferences().incrementOrderNo(order.id); await DbCategory().reduceInventory(order.items); if (order.transactionId.isEmpty) { await DbHubManager().updateCashBalance(order.orderAmount); } await box.close(); return res; } Future<String> updateOrder(String newID, SaleOrder order) async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); String orderKey = _getOrderKey(order); SaleOrder item = await box.get(orderKey); item.transactionSynced = true; item.id = newID; item.save(); return orderKey; } Future<List<SaleOrder>> getOrders() async { // LazyBox box = await Hive.openLazyBox(SALE_ORDER_BOX); box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); List<SaleOrder> list = []; for (var key in box.keys) { var item = await box.get(key); var order = item as SaleOrder; Future.forEach(order.items, (item) async { var product = item as Product; Product? pro = await DbProduct().getProductDetails(product.id); if (pro != null) { product.productImage = pro.productImage; } }); list.add(order); } // await box.close(); return list; } Future<List<SaleOrder>> getOfflineOrders() async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); List<SaleOrder> list = []; // print("TOTAL ORDERS: ${box.keys.length}"); for (var key in box.keys) { var item = await box.get(key); var product = item as SaleOrder; if (product.transactionSynced == false) list.add(product); } await box.close(); return list; } Future<double> getOfflineOrderCashBalance() async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); double cashBalance = 0; // print("TOTAL ORDERS: ${box.keys.length}"); for (var key in box.keys) { var item = await box.get(key); var product = item as SaleOrder; if (product.transactionSynced == false) { if (product.transactionId.isEmpty) { cashBalance = cashBalance + product.orderAmount; } } } await box.close(); return cashBalance; } Future<String> saveOrder(SaleOrder order) async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); String orderKey = _getOrderKey(order); await box.put(orderKey, order); // await box.close(); return orderKey; } Future<bool> saveOrders(List<SaleOrder> sales) async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); await Future.forEach(sales, (saleOrder) async { SaleOrder order = saleOrder as SaleOrder; String orderKey = _getOrderKey(order); await box.put(orderKey, order); }); return true; } Future<void> delete() async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); await box.clear(); await box.close(); } String _getOrderKey(SaleOrder order) { // return "${order.date}_${order.time}"; return "${order.tracsactionDateTime.millisecondsSinceEpoch}"; } Future<bool> modifySevenDaysOrdersFromToday() async { box = await Hive.openBox<SaleOrder>(SALE_ORDER_BOX); List<SaleOrder> list = []; for (var key in box.keys) { var item = await box.get(key); var order = item as SaleOrder; Future.forEach(order.items, (item) async { var product = item as OrderItem; OrderItem? pro = await DbOrderItem().getProductDetails(product.id); if (pro != null) { product.productImage = pro.productImage; } }); list.add(order); } DateTime todaysDateTime = DateTime.now(); int deleteCounter = 0; var dataUpto = todaysDateTime.subtract(const Duration(days: OFFLINE_DATA_FOR)); var salesData = list.where((element) => element.tracsactionDateTime.isBefore(dataUpto) && element.transactionSynced == true); int itemsToDelete = salesData.length; await Future.forEach(salesData, (order) async { var orderData = order as SaleOrder; await orderData.delete(); itemsToDelete += 1; }); // await box.close(); return itemsToDelete == deleteCounter; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_constants.dart
//***********************// //Hive Database Constants //**********************// // ignore_for_file: constant_identifier_names const CUSTOMER_BOX = 'customers'; const HUB_MANAGER_BOX = 'hub_manager'; const PRODUCT_BOX = 'products'; const SALE_ORDER_BOX = 'sale_orders'; const PARKED_ORDER_BOX = 'parked_orders'; const PREFERENCE_BOX = 'preferences'; const CATEGORY_BOX = 'categories'; const ATTRIBUTE_BOX = 'attributes'; const OPTION_BOX = 'options'; const ORDER_ITEM_BOX = 'order_items'; const URL_BOX = 'url'; //Temporary Variables const WardOne = 'SHM0134'; const WardTwo = 'ANV0145'; //Hive Box type ID constants //(NOTE : These IDs should be unique for all the Hive Boxes. Repeated ID will be overrided by existing one). const ProductsBoxTypeId = 10; const SaleOrderBoxTypeId = 11; const PreferencesTypeId = 12; const ParkOrderBoxTypeId = 13; const CategoryBoxTypeId = 14; const AttributeBoxTypeId = 15; const OptionBoxTypeId = 16; const HubManagerBoxTypeId = 17; const CustomerBoxTypeId = 18; const OrderItemBoxTypeId = 19; //PreferenceBox Constants const SelectedWard = 'SELECTED_WARDS'; const HubManagerUser = 'HUB_MANAGER'; const IsDataAdded = 'IS_DATA_ADDED_STOCKS'; const ApiKey = 'API_KEY'; const ApiSecret = 'API_SECRET'; const HubManagerId = 'HUB_MANAGAER_ID'; const SalesSeries = 'SALES_SERIES'; // const SelectedCustomerPref = 'SELECTED_CUSTOMER'; // const SelectedProductsPref = 'SELECTED_PRODUCTS'; const CUSTOMER_LAST_SYNC_DATETIME = 'CUSTOMER_LAST_SYNC_DATETIME'; const PRODUCT_LAST_SYNC_DATETIME = 'PRODUCT_LAST_SYNC_DATETIME'; const CURRENT_ORDER_NUMBER = 'CURRENT_ORDER_NUMBER'; const URL_KEY = 'URL_KEY';
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/db_utils/db_hub_manager.dart
import '../models/hub_manager.dart'; import 'db_constants.dart'; import 'package:hive_flutter/hive_flutter.dart'; class DbHubManager { late Box box; Future<void> addManager(HubManager manager) async { box = await Hive.openBox<HubManager>(HUB_MANAGER_BOX); box.add(manager); } Future<HubManager?> getManager() async { box = await Hive.openBox<HubManager>(HUB_MANAGER_BOX); if (box.length > 0) { return box.getAt(0); } return null; } updateCashBalance(double orderAmount) async { box = await Hive.openBox<HubManager>(HUB_MANAGER_BOX); HubManager manager = box.get(0) as HubManager; manager.cashBalance = manager.cashBalance + orderAmount; await manager.save(); } Future<int> delete() async { box = await Hive.openBox<HubManager>(HUB_MANAGER_BOX); return box.clear(); } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/order_item.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'order_item.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class OrderItemAdapter extends TypeAdapter<OrderItem> { @override final int typeId = 19; @override OrderItem read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return OrderItem( id: fields[0] as String, name: fields[1] as String, group: fields[3] as String, description: fields[4] as String, stock: fields[5] as double, price: fields[2] as double, attributes: (fields[6] as List).cast<Attribute>(), orderedQuantity: fields[7] as double, orderedPrice: fields[10] as double, productImage: fields[8] as Uint8List, productUpdatedTime: fields[9] as DateTime, productImageUrl: fields[11] == null ? '' : fields[11] as String?, tax: fields[12] == null ? 0.0 : fields[12] as double, ); } @override void write(BinaryWriter writer, OrderItem obj) { writer ..writeByte(13) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.price) ..writeByte(3) ..write(obj.group) ..writeByte(4) ..write(obj.description) ..writeByte(5) ..write(obj.stock) ..writeByte(6) ..write(obj.attributes) ..writeByte(7) ..write(obj.orderedQuantity) ..writeByte(8) ..write(obj.productImage) ..writeByte(9) ..write(obj.productUpdatedTime) ..writeByte(10) ..write(obj.orderedPrice) ..writeByte(11) ..write(obj.productImageUrl) ..writeByte(12) ..write(obj.tax); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is OrderItemAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/park_order.dart
import 'dart:convert'; import 'package:hive_flutter/hive_flutter.dart'; import '../db_utils/db_constants.dart'; import 'customer.dart'; import 'hub_manager.dart'; import 'order_item.dart'; part 'park_order.g.dart'; @HiveType(typeId: ParkOrderBoxTypeId) class ParkOrder extends HiveObject { @HiveField(0) String id; @HiveField(1) String date; @HiveField(2) String time; @HiveField(3) Customer customer; @HiveField(4) HubManager manager; @HiveField(5) List<OrderItem> items; @HiveField(6) double orderAmount; @HiveField(7) DateTime transactionDateTime; ParkOrder({ required this.id, required this.date, required this.time, required this.customer, required this.manager, required this.items, required this.orderAmount, required this.transactionDateTime, }); ParkOrder copyWith({ String? id, String? date, String? time, Customer? customer, HubManager? manager, List<OrderItem>? items, double? orderAmount, DateTime? transactionDateTime, }) { return ParkOrder( id: id ?? this.id, date: date ?? this.date, time: time ?? this.time, customer: customer ?? this.customer, manager: manager ?? this.manager, items: items ?? this.items, orderAmount: orderAmount ?? this.orderAmount, transactionDateTime: transactionDateTime ?? this.transactionDateTime, ); } Map<String, dynamic> toMap() { return { 'id': id, 'date': date, 'time': time, 'customer': customer.toMap(), 'manager': manager.toMap(), 'items': items.map((x) => x.toMap()).toList(), 'orderAmount': orderAmount, 'transactionDateTime': transactionDateTime, }; } factory ParkOrder.fromMap(Map<String, dynamic> map) { return ParkOrder( id: map['id'], date: map['date'], time: map['time'], customer: Customer.fromMap(map['customer']), manager: HubManager.fromMap(map['manager']), items: List<OrderItem>.from(map['items']?.map((x) => OrderItem.fromMap(x))), orderAmount: map['orderAmount'], transactionDateTime: map['transactionDateTime'], ); } String toJson() => json.encode(toMap()); factory ParkOrder.fromJson(String source) => ParkOrder.fromMap(json.decode(source)); @override String toString() { return 'ParkOrder(id: $id, date: $date, time: $time, customer: $customer, manager: $manager, items: $items, orderAmount: $orderAmount)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is ParkOrder && other.id == id && other.date == date && other.time == time && other.customer == customer && other.manager == manager && other.items == items && other.transactionDateTime == transactionDateTime && other.orderAmount == orderAmount; } @override int get hashCode { return id.hashCode ^ date.hashCode ^ time.hashCode ^ customer.hashCode ^ manager.hashCode ^ items.hashCode ^ transactionDateTime.hashCode ^ orderAmount.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/sale_order.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'sale_order.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class SaleOrderAdapter extends TypeAdapter<SaleOrder> { @override final int typeId = 11; @override SaleOrder read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return SaleOrder( id: fields[0] as String, date: fields[1] as String, time: fields[2] as String, customer: fields[3] as Customer, manager: fields[4] as HubManager, items: (fields[5] as List).cast<OrderItem>(), orderAmount: fields[6] as double, transactionId: fields[7] as String, transactionSynced: fields[8] as bool, tracsactionDateTime: fields[9] as DateTime, paymentMethod: fields[10] == null ? '' : fields[10] as String, paymentStatus: fields[11] == null ? 'Unpaid' : fields[11] as String, ); } @override void write(BinaryWriter writer, SaleOrder obj) { writer ..writeByte(12) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.date) ..writeByte(2) ..write(obj.time) ..writeByte(3) ..write(obj.customer) ..writeByte(4) ..write(obj.manager) ..writeByte(5) ..write(obj.items) ..writeByte(6) ..write(obj.orderAmount) ..writeByte(7) ..write(obj.transactionId) ..writeByte(8) ..write(obj.transactionSynced) ..writeByte(9) ..write(obj.tracsactionDateTime) ..writeByte(10) ..write(obj.paymentMethod) ..writeByte(11) ..write(obj.paymentStatus); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is SaleOrderAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/hub_manager.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'hub_manager.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class HubManagerAdapter extends TypeAdapter<HubManager> { @override final int typeId = 17; @override HubManager read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return HubManager( id: fields[0] as String, name: fields[1] as String, emailId: fields[2] as String, phone: fields[3] as String, cashBalance: fields[4] as double, profileImage: fields[5] as Uint8List, ); } @override void write(BinaryWriter writer, HubManager obj) { writer ..writeByte(6) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.emailId) ..writeByte(3) ..write(obj.phone) ..writeByte(4) ..write(obj.cashBalance) ..writeByte(5) ..write(obj.profileImage); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is HubManagerAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/option.dart
import 'dart:convert'; import 'package:hive_flutter/hive_flutter.dart'; import '../db_utils/db_constants.dart'; part 'option.g.dart'; @HiveType(typeId: OptionBoxTypeId) class Option extends HiveObject { @HiveField(0) String id; @HiveField(1) String name; @HiveField(2) double price; @HiveField(3) bool selected; @HiveField(4) double tax; Option({ required this.id, required this.name, required this.price, required this.selected, required this.tax, }); Option copyWith({ String? id, String? name, double? price, bool? selected, double? tax, }) { return Option( id: id ?? this.id, name: name ?? this.name, price: price ?? this.price, selected: selected ?? this.selected, tax: tax ?? this.tax, ); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'price': price, 'selected': selected, 'tax': tax }; } factory Option.fromMap(Map<String, dynamic> map) { return Option( id: map['id'] ?? '', name: map['name'] ?? '', price: map['price']?.toDouble() ?? 0.0, selected: map['selected'] ?? false, tax: map['tax'] ?? 0.0 ); } String toJson() => json.encode(toMap()); factory Option.fromJson(String source) => Option.fromMap(json.decode(source)); @override String toString() { return 'Option(id: $id, name: $name, price: $price, selected: $selected, tax: $tax)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Option && other.id == id && other.name == name && other.price == price && other.selected == selected; } @override int get hashCode { return id.hashCode ^ name.hashCode ^ price.hashCode ^ selected.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/customer.dart
import 'dart:convert'; import 'package:hive/hive.dart'; import '../db_utils/db_constants.dart'; part 'customer.g.dart'; @HiveType(typeId: CustomerBoxTypeId) class Customer extends HiveObject { @HiveField(0) String id; @HiveField(1) String name; @HiveField(2) String email; @HiveField(3) String phone; @HiveField(4) bool isSynced; @HiveField(5) DateTime modifiedDateTime; Customer( {required this.id, required this.name, required this.email, required this.phone, required this.isSynced, required this.modifiedDateTime}); Customer copyWith({ String? id, String? name, String? email, String? phone, bool? isSynced, DateTime? modifiedDateTime, }) { return Customer( id: id ?? this.id, name: name ?? this.name, email: email ?? this.email, phone: phone ?? this.phone, isSynced: isSynced ?? this.isSynced, modifiedDateTime: modifiedDateTime ?? this.modifiedDateTime); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'email': email, 'phone': phone, 'isSynced': isSynced, 'modifiedDateTime': modifiedDateTime }; } factory Customer.fromMap(Map<String, dynamic> map) { return Customer( id: map['id'], name: map['name'], email: map['email'], phone: map['phone'], isSynced: map['isSynced'], modifiedDateTime: map['modifiedDateTime']); } String toJson() => json.encode(toMap()); factory Customer.fromJson(String source) => Customer.fromMap(json.decode(source)); @override String toString() { return 'Customer(id: $id, name: $name, email: $email, phone: $phone, isSynced: $isSynced, modifiedDateTime: $modifiedDateTime)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Customer && other.id == id && other.name == name && other.email == email && other.phone == phone && other.isSynced == isSynced && other.modifiedDateTime == modifiedDateTime; } @override int get hashCode { return id.hashCode ^ name.hashCode ^ email.hashCode ^ phone.hashCode ^ isSynced.hashCode ^ modifiedDateTime.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/category.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:hive_flutter/hive_flutter.dart'; import '../db_utils/db_constants.dart'; import 'product.dart'; part 'category.g.dart'; @HiveType(typeId: CategoryBoxTypeId) class Category extends HiveObject { @HiveField(0) String id; @HiveField(1) String name; @HiveField(2) Uint8List image; @HiveField(3) List<Product> items; String? imageUrl; bool isExpanded; Category( {required this.id, required this.name, required this.image, required this.items, this.isExpanded = false, this.imageUrl = ''}); Category copyWith({ String? id, String? name, Uint8List? image, List<Product>? items, }) { return Category( id: id ?? this.id, name: name ?? this.name, image: image ?? this.image, items: items ?? this.items, ); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'image': image, 'items': items.map((x) => x.toMap()).toList(), }; } factory Category.fromMap(Map<String, dynamic> map) { return Category( id: map['id'] ?? '', name: map['name'] ?? '', image: map['image'] ?? '', items: List<Product>.from(map['items']?.map((x) => Product.fromMap(x))), ); } String toJson() => json.encode(toMap()); factory Category.fromJson(String source) => Category.fromMap(json.decode(source)); @override String toString() { return 'Category(id: $id, name: $name, image: $image, items: $items)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is Category && other.id == id && other.name == name && other.image == image && listEquals(other.items, items); } @override int get hashCode { return id.hashCode ^ name.hashCode ^ image.hashCode ^ items.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/option.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'option.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class OptionAdapter extends TypeAdapter<Option> { @override final int typeId = 16; @override Option read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return Option( id: fields[0] as String, name: fields[1] as String, price: fields[2] as double, selected: fields[3] as bool, tax: fields[4] as double, ); } @override void write(BinaryWriter writer, Option obj) { writer ..writeByte(5) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.price) ..writeByte(3) ..write(obj.selected) ..writeByte(4) ..write(obj.tax); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is OptionAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/customer.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'customer.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class CustomerAdapter extends TypeAdapter<Customer> { @override final int typeId = 18; @override Customer read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return Customer( id: fields[0] as String, name: fields[1] as String, email: fields[2] as String, phone: fields[3] as String, isSynced: fields[4] as bool, modifiedDateTime: fields[5] as DateTime, ); } @override void write(BinaryWriter writer, Customer obj) { writer ..writeByte(6) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.email) ..writeByte(3) ..write(obj.phone) ..writeByte(4) ..write(obj.isSynced) ..writeByte(5) ..write(obj.modifiedDateTime); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is CustomerAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/sale_order.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:hive_flutter/hive_flutter.dart'; import '../db_utils/db_constants.dart'; import 'customer.dart'; import 'hub_manager.dart'; import 'order_item.dart'; part 'sale_order.g.dart'; @HiveType(typeId: SaleOrderBoxTypeId) class SaleOrder extends HiveObject { @HiveField(0) String id; @HiveField(1) String date; @HiveField(2) String time; @HiveField(3) Customer customer; @HiveField(4) HubManager manager; @HiveField(5) List<OrderItem> items; @HiveField(6) double orderAmount; @HiveField(7) String transactionId; @HiveField(8) bool transactionSynced; @HiveField(9) DateTime tracsactionDateTime; @HiveField(10, defaultValue: "") String paymentMethod; @HiveField(11, defaultValue: "Unpaid") String paymentStatus; String? parkOrderId; SaleOrder({ required this.id, required this.date, required this.time, required this.customer, required this.manager, required this.items, required this.orderAmount, required this.transactionId, required this.transactionSynced, required this.tracsactionDateTime, required this.paymentMethod, required this.paymentStatus, this.parkOrderId = '', }); SaleOrder copyWith( {String? id, String? date, String? time, Customer? customer, HubManager? manager, List<OrderItem>? items, double? orderAmount, String? transactionId, String? paymentMethod, String? paymentStatus, bool? transactionSynced, DateTime? tracsactionDateTime}) { return SaleOrder( id: id ?? this.id, date: date ?? this.date, time: time ?? this.time, customer: customer ?? this.customer, manager: manager ?? this.manager, items: items ?? this.items, orderAmount: orderAmount ?? this.orderAmount, transactionId: transactionId ?? this.transactionId, paymentMethod: paymentMethod ?? this.paymentMethod, paymentStatus: paymentStatus ?? this.paymentStatus, transactionSynced: transactionSynced ?? this.transactionSynced, tracsactionDateTime: tracsactionDateTime ?? this.tracsactionDateTime); } Map<String, dynamic> toMap() { return { 'id': id, 'date': date, 'time': time, 'customer': customer.toMap(), 'manager': manager.toMap(), 'items': items.map((x) => x.toMap()).toList(), 'orderAmount': orderAmount, 'transactionId': transactionId, 'paymentMethod': paymentMethod, 'paymentStatus': paymentStatus, 'transactionSynced': transactionSynced, 'tracsactionDateTime': tracsactionDateTime.toIso8601String(), }; } factory SaleOrder.fromMap(Map<String, dynamic> map) { return SaleOrder( id: map['id'], date: map['date'], time: map['time'], customer: Customer.fromMap(map['customer']), manager: HubManager.fromMap(map['manager']), items: List<OrderItem>.from( map['items']?.map((x) => OrderItem.fromMap(x))), orderAmount: map['orderAmount'], transactionId: map['transactionId'], paymentMethod: map['paymentMethod'], paymentStatus: map['paymentStatus'], transactionSynced: map['transactionSynced'], tracsactionDateTime: map['tracsactionDateTime']); } String toJson() => json.encode(toMap()); factory SaleOrder.fromJson(String source) => SaleOrder.fromMap(json.decode(source)); @override String toString() { return 'SaleOrder(id: $id, date: $date, time: $time, customer: $customer, manager: $manager, items: $items, orderAmount: $orderAmount, transactionId: $transactionId, transactionSynced: $transactionSynced. tracsactionDateTime: $tracsactionDateTime)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is SaleOrder && other.id == id && other.date == date && other.time == time && other.customer == customer && other.manager == manager && listEquals(other.items, items) && other.orderAmount == orderAmount && other.transactionId == transactionId && other.paymentMethod == paymentMethod && other.paymentStatus == paymentStatus && other.transactionSynced == transactionSynced && other.tracsactionDateTime.isAtSameMomentAs(tracsactionDateTime); } @override int get hashCode { return id.hashCode ^ date.hashCode ^ time.hashCode ^ customer.hashCode ^ manager.hashCode ^ items.hashCode ^ orderAmount.hashCode ^ transactionId.hashCode ^ paymentMethod.hashCode ^ paymentStatus.hashCode ^ transactionSynced.hashCode ^ tracsactionDateTime.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/category.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'category.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class CategoryAdapter extends TypeAdapter<Category> { @override final int typeId = 14; @override Category read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return Category( id: fields[0] as String, name: fields[1] as String, image: fields[2] as Uint8List, items: (fields[3] as List).cast<Product>(), ); } @override void write(BinaryWriter writer, Category obj) { writer ..writeByte(4) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.image) ..writeByte(3) ..write(obj.items); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is CategoryAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/hub_manager.dart
import 'dart:convert'; import 'dart:typed_data'; import 'package:hive/hive.dart'; import '../db_utils/db_constants.dart'; part 'hub_manager.g.dart'; @HiveType(typeId: HubManagerBoxTypeId) class HubManager extends HiveObject { @HiveField(0) String id; @HiveField(1) String name; @HiveField(2) String emailId; @HiveField(3) String phone; @HiveField(4) double cashBalance; @HiveField(5) Uint8List profileImage; HubManager( {required this.id, required this.name, required this.emailId, required this.phone, this.cashBalance = 0, required this.profileImage}); HubManager copyWith({ String? id, String? name, String? emailId, String? phone, double? cashBalance, Uint8List? profileImage, }) { return HubManager( id: id ?? this.id, name: name ?? this.name, emailId: emailId ?? this.emailId, phone: phone ?? this.phone, cashBalance: cashBalance ?? this.cashBalance, profileImage: profileImage ?? this.profileImage, ); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'emailId': emailId, 'phone': phone, 'cashBalance': cashBalance, 'profileImage': profileImage, }; } factory HubManager.fromMap(Map<String, dynamic> map) { return HubManager( id: map['id'], name: map['name'], emailId: map['emailId'], phone: map['phone'], cashBalance: map['cashBalance'], profileImage: map['profileImage'], ); } String toJson() => json.encode(toMap()); factory HubManager.fromJson(String source) => HubManager.fromMap(json.decode(source)); @override String toString() { return 'HubManager(id: $id, name: $name, emailId: $emailId, phone: $phone, cashBalance: $cashBalance)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is HubManager && other.id == id && other.name == name && other.emailId == emailId && other.phone == phone && other.profileImage == profileImage && other.cashBalance == cashBalance; } @override int get hashCode { return id.hashCode ^ name.hashCode ^ emailId.hashCode ^ phone.hashCode ^ profileImage.hashCode ^ cashBalance.hashCode; } }
0
mirrored_repositories/GETPOS-Flutter-App/lib/database
mirrored_repositories/GETPOS-Flutter-App/lib/database/models/order_item.dart
import 'dart:convert'; import 'dart:typed_data'; import 'package:hive/hive.dart'; import '../db_utils/db_constants.dart'; import 'attribute.dart'; part 'order_item.g.dart'; @HiveType(typeId: OrderItemBoxTypeId) class OrderItem extends HiveObject { @HiveField(0) String id; @HiveField(1) String name; @HiveField(2) double price; @HiveField(3) String group; @HiveField(4) String description; @HiveField(5) double stock; @HiveField(6) List<Attribute> attributes; @HiveField(7) double orderedQuantity; @HiveField(8) Uint8List productImage; @HiveField(9) DateTime productUpdatedTime; @HiveField(10) double orderedPrice; @HiveField(11, defaultValue: '') String? productImageUrl; @HiveField(12, defaultValue: 0.0) double tax; OrderItem( {required this.id, required this.name, required this.group, required this.description, required this.stock, required this.price, required this.attributes, this.orderedQuantity = 0, this.orderedPrice = 0, required this.productImage, required this.productUpdatedTime, required this.productImageUrl, this.tax = 0}); OrderItem copyWith( {String? id, String? code, String? name, String? group, String? description, double? stock, double? price, List<Attribute>? attributes, double? orderedQuantity, double? orderedPrice, Uint8List? productImage, DateTime? productUpdatedTime, String? productImageUrl, double? tax}) { return OrderItem( id: id ?? this.id, name: name ?? this.name, group: group ?? this.group, description: description ?? this.description, stock: stock ?? this.stock, price: price ?? this.price, attributes: attributes ?? this.attributes, orderedQuantity: orderedQuantity ?? this.orderedQuantity, orderedPrice: orderedPrice ?? this.orderedPrice, productImage: productImage ?? this.productImage, productUpdatedTime: productUpdatedTime ?? this.productUpdatedTime, productImageUrl: productImageUrl ?? this.productImageUrl, tax: tax ?? this.tax, ); } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'group': group, 'description': description, 'stock': stock, 'price': price, 'attributes': attributes, 'orderedQuantity': orderedQuantity, 'orderedPrice': orderedPrice, 'productImage': productImage, 'productUpdatedTime': productUpdatedTime.toIso8601String(), }; } factory OrderItem.fromMap(Map<String, dynamic> map) { // List<int> data = map['productImage'].codeUnits; List<int>? data = (map["productImage"] as List).map((e) => e as int).toList(); return OrderItem( id: map['id'], name: map['name'], group: map['group'], description: map['description'], stock: map['stock'], price: map['price'], // List<OrderItem>.from( // map['items']?.map((x) => OrderItem.fromMap(x))) attributes: List<Attribute>.from( map['attributes']?.map((x) => Attribute.fromMap(x))), orderedQuantity: map['orderedQuantity'] ?? 0, orderedPrice: map['orderedPrice'] ?? map['price'], productImage: Uint8List.fromList(data), //map['productImage'], productUpdatedTime: DateTime.parse(map['productUpdatedTime']), productImageUrl: map['productImageUrl'], tax: map['tax']); } String toJson() => json.encode(toMap()); factory OrderItem.fromJson(String source) => OrderItem.fromMap(json.decode(source)); @override String toString() { return 'OrderItem(id: $id, name: $name, group: $group, description: $description, stock: $stock, price: $price, attributes: $attributes, orderedQuantity: $orderedQuantity, orderedPrice: $orderedPrice, productImage: $productImage, productUpdatedTime: $productUpdatedTime)'; } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is OrderItem && other.id == id && other.name == name && other.group == group && other.description == description && other.stock == stock && other.price == price && other.attributes == attributes && other.orderedQuantity == orderedQuantity && other.orderedPrice == orderedPrice && other.productImage == productImage && other.productUpdatedTime == productUpdatedTime; } @override int get hashCode { return id.hashCode ^ name.hashCode ^ group.hashCode ^ description.hashCode ^ stock.hashCode ^ price.hashCode ^ attributes.hashCode ^ orderedQuantity.hashCode ^ orderedPrice.hashCode ^ productImage.hashCode ^ productUpdatedTime.hashCode; } }
0