repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/app_settings_model.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:relay/core/app_settings_keys.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/models/group_sort.dart'; import 'package:relay/services/app_settings_service.dart'; import 'package:relay/services/image_service.dart'; class AppSettingsModel extends ChangeNotifier { final AppSettingsService _appSettings; final ImageService _imageService; String _name = ""; String _imagePath = ""; GroupSort _defaultGroupSort = GroupSort.lastSentFirst; String _signature = ""; bool _autoIncludeSignature = false; AppSettingsModel._(this._appSettings, this._imageService) { _loadData(); } factory AppSettingsModel([AppSettingsService appSettings, ImageService imageService]) => AppSettingsModel._( appSettings ?? dependencyLocator<AppSettingsService>(), imageService ?? dependencyLocator<ImageService>()); String get name => _name; set name(String value) { if(_name != value) { _name = value; _appSettings.setSettingString(AppSettingsConstants.profile_name_settings_key, value); notifyListeners(); } } String get imagePath => _imagePath; Future updateImagePath(File image) async { var path = await _imageService.importFile(image); _imagePath = await _imageService.getImagePath(path); _appSettings.setSettingString(AppSettingsConstants.profile_image_path_settings_key, path); notifyListeners(); } GroupSort get defaultGroupSort => _defaultGroupSort; set defaultGroupSort(GroupSort value) { if(_defaultGroupSort != value) { _defaultGroupSort = value; _appSettings.setSettingInt(AppSettingsConstants.group_sorting_settings_key, value.toInt()); notifyListeners(); } } String get signature => _signature; set signature(String value) { if(_signature != value) { _signature = value; _appSettings.setSettingString(AppSettingsConstants.signature_settings_key, value); notifyListeners(); } } bool get autoIncludeSignature => _autoIncludeSignature; set autoIncludeSignature(bool value) { if(_autoIncludeSignature != value) { _autoIncludeSignature = value; _appSettings.setSettingsBool(AppSettingsConstants.auto_include_signature_settings_key, value); notifyListeners(); } } void _loadData() async { _name = await _appSettings.getSettingString(AppSettingsConstants.profile_name_settings_key); var path = await _appSettings.getSettingString(AppSettingsConstants.profile_image_path_settings_key); _imagePath = await _imageService.getImagePath(path); _defaultGroupSort = GroupSort.parseInt( await _appSettings.getSettingInt( AppSettingsConstants.group_sorting_settings_key, GroupSort.alphabetical.toInt() ) ); _signature = await _appSettings.getSettingString(AppSettingsConstants.signature_settings_key); _autoIncludeSignature = await _appSettings.getSettingBool(AppSettingsConstants.auto_include_signature_settings_key); notifyListeners(); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/package_info_model.dart
import 'dart:async'; import 'package:app_review/app_review.dart'; import 'package:flutter/material.dart'; import 'package:package_info/package_info.dart'; class PackageInfoModel extends ChangeNotifier { String _appName = ""; String _packageName = ""; String _version = ""; String _buildNumber = ""; String _appID = ""; Future init() async { var packageInfo = await PackageInfo.fromPlatform(); _appName = packageInfo.appName; _packageName = packageInfo.packageName; _version = packageInfo.version; _buildNumber = packageInfo.buildNumber; var appId = await AppReview.getAppID; _appID = appId; notifyListeners(); } String get appName => _appName; String get packageName => _packageName; String get version => _version + "+" + _buildNumber; String get appID => _appID; }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/compose_message_model.dart
import 'dart:collection'; import 'package:flutter/foundation.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/models/message_recipient.dart'; import 'package:relay/models/message_item.dart'; import 'package:relay/models/contact_item.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/services/message_service.dart'; class ComposeMessageModel extends ChangeNotifier { final MessageService _messageService; final GroupItemModel _group; final List<ContactItemModel> recipients; List<MessageItemModel> _messages = []; ComposeMessageModel._(this._messageService, this._group, this.recipients) { _loadData(); } factory ComposeMessageModel({ @required GroupItemModel group, @required List<ContactItemModel> recipients, MessageService messageService}) { return ComposeMessageModel._( messageService ?? dependencyLocator<MessageService>(), group, recipients ); } String get groupName => _group.name; UnmodifiableListView<MessageItemModel> get messages => UnmodifiableListView(_messages.reversed); Future _loadData() async { _messages = await _messageService.getAllMessages(_group); notifyListeners(); } Future<bool> sendMessageToGroup({@required String message}) async { assert(message != null); var messageRecipients = recipients.map((r) => MessageRecipient.fromContact(r)).toList(); if (await _sendMessage(message, messageRecipients) == MessageSendingResult.Success) { await _logAndUpdateMessages(messageRecipients, message); return true; } return false; } Future<bool> sendMessageToIndividuals({@required String message, @required Future<SendMessageNextStep> Function(double progress, int index, MessageRecipient recipient) onSent}) async { assert(onSent != null); assert(message != null); assert(message.isNotEmpty); var messageRecipients = recipients.map((r) => MessageRecipient.fromContact(r)).toList(); List<MessageRecipient> sentRecipients = []; for(int index in List.generate(recipients.length, (i) => (i - 1) + 1)) { var recipient = messageRecipients[index]; double percent = (index + 1) / recipients.length; var nextStep = await onSent(percent, index + 1, recipient); if(nextStep == SendMessageNextStep.Cancel) { if(index == 0 || sentRecipients.isEmpty) return false; var sublist = messageRecipients.sublist(0, index + 1); await _logAndUpdateMessages(sublist, message); return true; } else if (nextStep == SendMessageNextStep.Skip) { continue; } else { if(await _sendMessage(message, [recipient]) == MessageSendingResult.Success) { sentRecipients.add(recipient); } } } if(sentRecipients.isNotEmpty) { await _logAndUpdateMessages(sentRecipients, message); } return sentRecipients.isNotEmpty; } Future _logAndUpdateMessages(List<MessageRecipient> messageRecipients, String message) async { var sentMessage = await _messageService.logMessage( recipients: messageRecipients, group: _group, message: message); _messages.add(sentMessage); notifyListeners(); } Future<MessageSendingResult> _sendMessage(String message, List<MessageRecipient> recipients) async { return await _messageService.sendMessage( message: message, recipients: recipients); } } enum SendMessageNextStep { Send, Skip, Cancel }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/collection_base_model.dart
import 'dart:collection'; import 'package:flutter/material.dart'; abstract class CollectionBaseModel<TModel> extends ChangeNotifier { /// the items to display. UnmodifiableListView<TModel> get items; /// load the children items. Future loadChildren(); }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/add_new_group_model.dart
import 'dart:async'; import 'package:commons/commons.dart'; import 'package:flutter/material.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/services/contacts_service.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/services/image_service.dart'; import 'package:relay/services/group_service.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/ui/models/contact_search_result_model.dart'; class AddNewGroupModel extends ChangeNotifier { GroupService _groupService; ImageService _imageService; ContactsService _contactsService; bool _isLoading = false; bool _filterToOnlyMobileNumbers = false; String _groupName = ""; List<ContactSearchResultModel> _contactsList = []; List<ContactSearchResultModel> _selectedContactsList = []; AddNewGroupModel([GroupService groupService, ImageService imageService, ContactsService contactsService]) { _groupService = groupService ?? dependencyLocator<GroupService>(); _imageService = imageService ?? dependencyLocator<ImageService>(); _contactsService = contactsService ?? dependencyLocator<ContactsService>(); load(); } bool get isLoading => _isLoading; String get groupName => _groupName; set groupName(String value) { if(_groupName != value) { _groupName = value; notifyListeners(); } } List<ContactSearchResultModel> get filteredAllContactsList => _filterToOnlyMobileNumbers ? _contactsList.where((c) => c.hasMobileNumbers).toList() : _contactsList; List<ContactSearchResultModel> get selectedContactsList => _selectedContactsList.reversed.toList(); bool get filterToOnlyMobileNumbers => _filterToOnlyMobileNumbers; set filterToOnlyMobileNumbers(bool value) { if(value != _filterToOnlyMobileNumbers) { _filterToOnlyMobileNumbers = value; notifyListeners(); } } @override void dispose() { super.dispose(); } Future load() async { _isLoading = true; var contacts = await _contactsService.getAllContacts(); _contactsList = contacts .where((c) => c.phones.isNotEmpty) .map((c) => ContactSearchResultModel(c)) .toList(); _isLoading = false; notifyListeners(); } void selectContact({@required BuildContext context, ContactSearchResultModel contact, bool onlyShowMobileNumbers = false}) { var index = _contactsList.indexOf(contact); if(index < 0) { return; } if(contact.selected) { contact.unselect(); _selectedContactsList.remove(contact); notifyListeners(); return; } if(contact.phoneNumbers.length == 1) { _contactsList[index].selectedPhoneNumber = contact.phoneNumbers.first.value; _selectedContactsList.add(contact); notifyListeners(); } else { optionsDialog( context, "Choose Number".i18n, contact.phoneNumbers .map((p) => Option( Text(p.value, style: AppStyles.heading2Bold), p.label == "mobile" ? Icon(Icons.phone_iphone) : Icon(Icons.home), () { _contactsList[index].selectedPhoneNumber = p.value; _selectedContactsList.add(contact); notifyListeners(); })).toList(), ); } } Future<List<ContactSearchResultModel>> search(String query) { if(query == null || query.isEmpty) return Future.value(_contactsList); var q = query.toLowerCase(); return Future.value( _contactsList .where((c) => c.searchString.contains(q)) .toList()); } Future save() async { if(validate()) { var group = await _groupService.addGroup(name: _groupName); for(var contact in selectedContactsList) { String imagePath; if(contact.image != null && contact.image.isNotEmpty) { var stopwatch = Stopwatch(); stopwatch.start(); imagePath = await _imageService.saveToFile(path: "contact_images", bytes: contact.image, width: 100, height: 100); stopwatch.stop(); print("writing image duration: " + stopwatch.elapsed.toString()); } group = await _groupService.addContact( group, firstName: contact.firstName, lastName: contact.lastName, company: contact.company, phone: contact.selectedPhoneNumber, birthday: contact.birthday, imagePath: imagePath); } } } bool validate() { return groupName.isNotEmpty; } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/groups_collection_model.dart
import 'dart:async'; import 'dart:collection'; import 'package:relay/core/app_settings_keys.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/models/group_sort.dart'; import 'package:relay/services/app_settings_service.dart'; import 'package:relay/services/image_service.dart'; import 'package:relay/services/purchases_service.dart'; import 'package:relay/models/toggleable_group_item.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/services/group_service.dart'; import 'package:relay/ui/models/collection_base_model.dart'; class GroupsCollectionModel extends CollectionBaseModel<ToggleableGroupItemModel> { final GroupService _groupService; final PurchasesService _purchasesService; final AppSettingsService _appSettings; List<ToggleableGroupItemModel> _items = []; StreamSubscription _updatesSubscription; StreamSubscription _purchasesSubscription; bool _hasUnlimitedGroups = false; bool _isLoaded = false; GroupsCollectionModel._(this._groupService, this._purchasesService, this._appSettings) { _updatesSubscription = _groupService.updatesReceived .listen((_) => loadChildren()); _purchasesSubscription = _purchasesService.unlimitedGroupsPurchasesStream .listen((_) async { _hasUnlimitedGroups = await _purchasesService.hasUnlimitedGroupsEntitlement(); notifyListeners(); }); loadChildren(); } factory GroupsCollectionModel([ GroupService groupService, PurchasesService purchasesServices, AppSettingsService appSettingsService, ImageService imageService]) => GroupsCollectionModel._( groupService ?? dependencyLocator<GroupService>(), purchasesServices ?? dependencyLocator<PurchasesService>(), appSettingsService ?? dependencyLocator<AppSettingsService>() ); @override UnmodifiableListView<ToggleableGroupItemModel> get items => UnmodifiableListView(_hasUnlimitedGroups ? _items : _items.take(1)); bool get shouldShowPaywall => _shouldShowPaywall(); @override void dispose() { _items.forEach((f) => f.dispose()); _updatesSubscription.cancel(); _purchasesSubscription.cancel(); super.dispose(); } @override Future loadChildren() async { _isLoaded = false; var groups = await _groupService.getAllGroups(); _hasUnlimitedGroups = await _purchasesService.hasUnlimitedGroupsEntitlement(); var groupSort = GroupSort.parseInt(await _appSettings.getSettingInt(AppSettingsConstants.group_sorting_settings_key, GroupSort.alphabetical.toInt())); if(groupSort == GroupSort.alphabetical) { groups.sort((a, b) => a.name.compareTo(b.name)); } else { var noCreationDate = <GroupItemModel>[]; var noLastSentDate = <GroupItemModel>[]; var hasLastSentDate = <GroupItemModel>[]; for(var group in groups) { if(group.lastMessageSentDate != null) { hasLastSentDate.add(group); } else if(group.creationDate != null) { noLastSentDate.add(group); } else { noCreationDate.add(group); } } if(hasLastSentDate.isNotEmpty) hasLastSentDate.sort((a,b) => a.lastMessageSentDate.compareTo(b.lastMessageSentDate)); if(noLastSentDate.isNotEmpty) noLastSentDate.sort((a, b) => a.creationDate.compareTo(b.creationDate)); if(noCreationDate.isNotEmpty) noCreationDate.sort((a,b) => a.name.compareTo(b.name)); groups = null; groups = hasLastSentDate + noLastSentDate + noCreationDate; } _items = groups .map((g) => ToggleableGroupItemModel(g)) .toList(); _isLoaded = true; notifyListeners(); } Future deleteGroup(ToggleableGroupItemModel group) async { await _groupService.deleteGroup(group); await loadChildren(); } Future<List<ToggleableGroupItemModel>> search(String query) { if(query == null || query.isEmpty) { return Future.value(<ToggleableGroupItemModel>[]); } var q = query.toLowerCase(); return Future .value( items .where((group) => group.name.toLowerCase().contains(q)) .toList()); } void toggleSelected(ToggleableGroupItemModel group) { if(group.selected) { _items.firstWhere((g) => g.id == group.id).selected = false; } else { _items.forEach((g) => g.selected = false); _items.firstWhere((g) => g.id == group.id).selected = true; } notifyListeners(); } Future duplicateGroup(GroupItemModel oldGroup) async { await _groupService.duplicateGroup(oldGroup); } bool _shouldShowPaywall() { if(!_isLoaded) { return _hasUnlimitedGroups; } else { return _items.isNotEmpty && !_hasUnlimitedGroups; } } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/show_group_model.dart
import 'dart:async'; import 'package:commons/commons.dart'; import 'package:contacts_service/contacts_service.dart'; import 'package:flutter/material.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/models/toggleable_contact_model.dart'; import 'package:relay/services/group_service.dart'; class ShowGroupModel extends ChangeNotifier { GroupItemModel _group; List<ToggleableContactItemModel> _contacts; Completer<Set<SimpleItem>> _allContactsCompleter = Completer(); GroupService _groupService; List<Contact> _allContacts; ShowGroupModel(this._group, [GroupService groupService]) { _groupService = groupService ?? dependencyLocator<GroupService>(); _updateContactList(); _fetchAllContacts(); } String get name => _group.name; bool get allSelected => !_contacts.any((c) => !c.selected); int get selectedContactsCount => selectedContacts.length; List<ToggleableContactItemModel> get selectedContacts => _contacts.where((c) => c.selected).toList(); set name(String value) { _group.name = value; save(); notifyListeners(); } List<ToggleableContactItemModel> get contacts => _contacts; Future<Set<SimpleItem>> get allContactsOnDevice => _allContactsCompleter.future; Future save() async { await _groupService.updateGroup(_group); } void selectAll() { _contacts.forEach((c) => c.selected = true); notifyListeners(); } void unselectAll() { _contacts.forEach((c) => c.selected = false); notifyListeners(); } void selectContact(ToggleableContactItemModel contact, bool selected) { contact.selected = selected; notifyListeners(); } Future addContact(int index, String phone) async { var contact = _allContacts[index]; if(contact != null) { _group = await _groupService.addContact( _group, firstName: contact.givenName, lastName: contact.familyName, phone: phone, company: contact.company, birthday: contact.birthday); _updateContactList(); } } Future delete() async { await _groupService.deleteGroup(_group); } Future deleteContact(ToggleableContactItemModel contact) async { _group = await _groupService.deleteContact(_group, contact); _updateContactList(); } void _updateContactList() { _contacts = _group.contacts.map((c) => ToggleableContactItemModel(c)..selected = true).toList(); notifyListeners(); } Future _fetchAllContacts() async { _allContacts = (await ContactsService.getContacts(withThumbnails: false)).toList(); List<SimpleItem> _searchableItems = []; for(var index in List.generate(_allContacts.length, (i) => (i - 1) + 1)) { var contact = _allContacts[index]; if(contact.phones.length > 0) { for(var phone in contact.phones) { _searchableItems.add( SimpleItem( index, "${contact.displayName}\n${phone.value} (${phone.label})", remarks: phone.value) ); } } } _allContactsCompleter.complete(_searchableItems.toSet()); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/models/contact_search_result_model.dart
import 'dart:typed_data'; import 'dart:core'; import 'package:contacts_service/contacts_service.dart'; import 'package:relay/translation/translations.dart'; class ContactSearchResultModel { final Contact _contact; String _selectedPhoneNumber = ""; String _searchString = ""; ContactSearchResultModel(this._contact) { _searchString = _contact.displayName.toLowerCase() + (_contact.company == null ? "" : _contact.company.toLowerCase()) + " " + _contact.phones.map((x) => x.value.replaceAll(RegExp(r'[^\d]',), "")).join() + " " + _contact.postalAddresses.map((a) => a.toString().replaceAll(RegExp(r'[^\d\w]'), " ")).join() + " " + _contact.emails.map((e) => e.value).join(); } String get firstName => _contact.givenName; String get lastName => _contact.familyName; String get name => _contact.displayName; String get initials => (_contact.givenName == null || _contact.givenName.isEmpty) && (_contact.familyName == null || _contact.familyName.isEmpty) ? _contact.displayName.substring(0,1) : "${_contact.givenName.isNotEmpty ? _contact.givenName.substring(0,1) : ""}" + "${_contact.familyName.isNotEmpty ? _contact.familyName.substring(0,1) : ""}"; String get company => _contact.company; DateTime get birthday => _contact.birthday; Uint8List get image => _contact.avatar ?? Uint8List.fromList([]); List<Item> get phoneNumbers => _contact.phones.toList(); bool get hasMobileNumbers => _contact.phones.any((p) => p.label == "mobile"); String get phoneNumberSubtitle => _getPhoneSubtitles(); bool get selected => _selectedPhoneNumber.isNotEmpty; void unselect() { selectedPhoneNumber = ""; } String get selectedPhoneNumber => _selectedPhoneNumber; set selectedPhoneNumber(String selectedPhoneNumber) { if(selectedPhoneNumber != _selectedPhoneNumber) { _selectedPhoneNumber = selectedPhoneNumber; } } String get searchString => _searchString; String _getPhoneSubtitles() { if(_contact == null ||_contact.phones == null ||_contact.phones.isEmpty) return ""; if(_contact.phones.length <= 2) { return _contact.phones.map((i) => i.value).join(", "); } else { var firstTwo = _contact.phones.take(2).map((i) => i.value).join(", "); return firstTwo + " and %d more".i18n.fill([_contact.phones.length - 2]); } } }
0
mirrored_repositories/RelayApp/lib/ui/models
mirrored_repositories/RelayApp/lib/ui/models/onboarding/onboarding_model.dart
import 'package:flutter/material.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/services/analytics_service.dart'; import 'package:relay/services/app_settings_service.dart'; import 'package:relay/ui/models/onboarding/onboarding_item_model.dart'; import 'package:relay/ui/app_styles.dart'; class OnboardingModel extends ChangeNotifier { static const int currentOnboardingVersion = 1; final String lastOnboardingVersionSettingString = "last_onboarding_version"; final String onboardingCompleteEvent = "onboarding_complete"; final List<OnboardingItemModel> items = [ OnboardingItemModel( title: "Mass texting made simple!", text: "Relay is designed to make texting large groups without massive REPLY ALL threads simple and easy.", imageAssetPath: "assets/images/onboarding0.png"), OnboardingItemModel( title: "Do you have group messaging turned on?", text: "That's ok! Just remember to use the 'send " + "individually' button when composing messages.", imageAssetPath: "assets/images/onboarding2.png", child: Container( height: 45.00, width: 58.00, decoration: BoxDecoration( gradient: LinearGradient( colors: [AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight), boxShadow: [ BoxShadow( offset: Offset(0.00,3.00), color: Color(0xff000000).withOpacity(0.16), blurRadius: 6), ], borderRadius: BorderRadius.circular(25.00)), child: Center( child: IconButton( onPressed: () { }, icon: Icon( Icons.person_outline, color: Colors.white))))) ]; final AppSettingsService _appSettings; final AnalyticsService _analyticsService; OnboardingModel._(this._appSettings, this._analyticsService); factory OnboardingModel([AppSettingsService settingsService, AnalyticsService analyticsService]) { return OnboardingModel._( settingsService ?? dependencyLocator<AppSettingsService>(), analyticsService ?? dependencyLocator<AnalyticsService>()); } Future skip(int onboardingPage) async { _appSettings.setSettingInt(lastOnboardingVersionSettingString, currentOnboardingVersion); await _analyticsService.trackEvent( onboardingCompleteEvent, properties: { 'result': 'skipped', 'lastPageSeen': onboardingPage, 'version': currentOnboardingVersion }); } Future complete() async { _appSettings.setSettingInt(lastOnboardingVersionSettingString, currentOnboardingVersion); await _analyticsService.trackEvent( onboardingCompleteEvent, properties: { 'result': 'completed', 'version': currentOnboardingVersion }); } }
0
mirrored_repositories/RelayApp/lib/ui/models
mirrored_repositories/RelayApp/lib/ui/models/onboarding/onboarding_input_item_model.dart
import 'package:flutter/material.dart'; import 'package:relay/ui/models/onboarding/onboarding_item_model.dart'; class OnboardingInputItemModel extends OnboardingItemModel { final TextEditingController controller; final String submitString; final Function(String) onSave; OnboardingInputItemModel({ @required String title, @required String text, String imageAssetPath, @required this.controller, @required this.submitString, @required this.onSave}) : super(title: title, text: text, imageAssetPath: imageAssetPath); bool canSave() { return controller.text.isNotEmpty; } void save() { onSave(controller.text); } }
0
mirrored_repositories/RelayApp/lib/ui/models
mirrored_repositories/RelayApp/lib/ui/models/onboarding/onboarding_item_model.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; class OnboardingItemModel { final String title; final String text; final String imageAssetPath; final Widget child; const OnboardingItemModel({@required this.title, @required this.text, this.imageAssetPath, this.child}); }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/onboarding_screen.dart
import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:relay/ui/models/onboarding/onboarding_model.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/ui/transitions/fade_route.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/ui/screens/home_screen.dart'; class OnboardingScreen extends StatefulWidget { OnboardingScreen({Key key}) : super(key: key); @override _OnboardingScreenState createState() => _OnboardingScreenState(); } class _OnboardingScreenState extends State<OnboardingScreen> with RouteAwareAnalytics { final double topHeaderPaddingHeight = 100.0; final double indicatorBoxHeight = 50.0; final double nextOrCompleteBoxHeight = 100.0; final PageController pageController = PageController(initialPage: 0); int currentPage = 0; @override String get screenClass => "OnboardingScreen"; @override String get screenName => "/Onboarding"; @override void dispose() { pageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: ChangeNotifierProvider<OnboardingModel>( create: (_) => OnboardingModel(), child: AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle.light, child: Container( height: double.infinity, width: double.infinity, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd ])), child: Stack( children: <Widget>[ Positioned( top: 0.0, height: topHeaderPaddingHeight, left: 0.0, right: 0.0, child: Container( alignment: Alignment.bottomRight, child: Consumer<OnboardingModel>( builder: (_, model, __) => FlatButton( onPressed: () async { await model.skip(currentPage); Navigator .of(context) .pushReplacement( FadeRoute(page: HomeScreen())); }, child: Text( "Skip".i18n, style: AppStyles.heading2Bold.copyWith(color: Colors.white))), ))), Positioned.fill( top: topHeaderPaddingHeight, left: MediaQuery.of(context).size.width * 0.1, right: MediaQuery.of(context).size.width * 0.1, bottom: indicatorBoxHeight + nextOrCompleteBoxHeight + MediaQuery.of(context).padding.bottom, child: Consumer<OnboardingModel>( builder: (_, model, __) => PageView( physics: ClampingScrollPhysics(), controller: pageController, children: buildOnboardingPages(model), onPageChanged: (index) => setState(() => currentPage = index)) ) ), Positioned( bottom: 0.0, left: 0.0, right: 0.0, height: indicatorBoxHeight + nextOrCompleteBoxHeight + MediaQuery.of(context).padding.bottom, child: Consumer<OnboardingModel>( builder: (context, model, __) => Column(children: <Widget>[ Box( height: indicatorBoxHeight, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: buildPageIndicator(model.items.length))), currentPage < model.items.length - 1 ? Box( height: MediaQuery.of(context).padding.bottom + nextOrCompleteBoxHeight, width: double.infinity, alignment: Alignment.topRight, child: FlatButton( onPressed: () { pageController.nextPage( duration: Duration(milliseconds: 500), curve: Curves.ease, ); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( "Next".i18n, style: AppStyles.heading1.copyWith(fontSize: 22.0), ), SizedBox(width: 10.0), Icon( Icons.arrow_forward, color: Colors.white, size: 30.0, ), ], ), ), ) : Box( height: MediaQuery.of(context).padding.bottom + nextOrCompleteBoxHeight, width: double.infinity, color: Colors.white, child: GestureDetector( onTap: () async { await model.complete(); Navigator .of(context) .pushReplacement( FadeRoute(page: HomeScreen())); }, child: Center( child: Padding( padding: EdgeInsets.only(bottom: 30.0), child: Text( "Get started".i18n, style: TextStyle( color: Color(0xFF5B16D0), fontSize: 20.0, fontWeight: FontWeight.bold, ), ), ), ), ) ) ] ), ) ) ], ), ), ), ), ); } List<Widget> buildOnboardingPages(OnboardingModel model) { return model.items.map((item) => Column( mainAxisSize: MainAxisSize.max, children: <Widget>[ Flexible( flex: 1, child: Center( child: Image( fit: BoxFit.fill, image: AssetImage(item.imageAssetPath) ) ) ), Box(height: 30.0,), Flexible( flex: 1, child: Box( height: double.infinity, width: double.infinity, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( item.title, style: AppStyles.heading1, ), SizedBox(height: 15.0), Text( item.text, style: AppStyles.paragraph, ), if(item.child != null) Center(child: item.child,) ] ) ) ) ), ], )).toList(); } List<Widget> buildPageIndicator(int length) { List<Widget> list = []; for (int i = 0; i < length; i++) { list.add(i == currentPage ? indicator(true) : indicator(false)); } return list; } Widget indicator(bool isActive) { return AnimatedContainer( duration: Duration(milliseconds: 150), margin: EdgeInsets.symmetric(horizontal: 8.0), height: 8.0, width: isActive ? 24.0 : 16.0, decoration: BoxDecoration( color: isActive ? Colors.white : Colors.grey, borderRadius: BorderRadius.all(Radius.circular(12)), ), ); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/home_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:hidden_drawer_menu/hidden_drawer/hidden_drawer_menu.dart'; import 'package:hidden_drawer_menu/simple_hidden_drawer/simple_hidden_drawer.dart'; import 'package:provider/provider.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:relay/services/app_reviews_service.dart'; import 'package:relay/ui/screens/group_collection_screen.dart'; import 'package:relay/ui/screens/menu_screen.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({Key key}) : super(key: key); @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> with RouteAwareAnalytics { @override String get screenClass => "HomeScreen"; @override String get screenName => "/"; @override void initState() { super.initState(); SchedulerBinding.instance.addPostFrameCallback((_) => shouldShowReviews(context)); } @override Widget build(BuildContext context) { return SimpleHiddenDrawer( disableCurrentScreenOnMenuOpened: true, contentCornerRadius: 40.0, menu: MenuScreen(), screenSelectedBuilder: (_, __) => GroupCollectionScreen(), ); } void shouldShowReviews(BuildContext context) async { var reviews = Provider.of<AppReviewsService>(context, listen: false); if(await reviews.shouldRequestReviews()) { await reviews.requestReviews(context); } } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/paywall_screen.dart
import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:purchases_flutter/purchases_flutter.dart'; import 'package:commons/commons.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:waiting_dialog/waiting_dialog.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/services/purchases_service.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/ui/transitions/fade_route.dart'; class PaywallScreen extends StatefulWidget { final Widget Function() onSuccessBuilder; const PaywallScreen({Key key, this.onSuccessBuilder}) : super(key: key); @override _PaywallScreenState createState() => _PaywallScreenState(); } class _PaywallScreenState extends State<PaywallScreen> with RouteAwareAnalytics { @override String get screenClass => "PaywallScreen"; @override String get screenName => "/Paywall"; @override Widget build(BuildContext context) { final double topSpace = MediaQuery.of(context).size.height * 0.20; return Consumer<PurchasesService>( builder: (context, purchases, _) => Scaffold( body: FutureBuilder<Offering>( future: purchases.getUnlimitedGroupsOfferings(), initialData: null, builder: (context, snapshot) { var offering = snapshot.data; if(offering == null) { return Center( child: Container( width: 100.0, height: 100.0, child: FlareActor( "assets/animations/loading.flr", animation: "active", ), ), ); } return Container( height: double.infinity, width: double.infinity, color: AppStyles.primaryGradientStart, child: Stack( children: <Widget>[ Positioned.fill( top: MediaQuery.of(context).padding.top + topSpace, child: new Container( width: double.infinity, decoration: BoxDecoration( color: AppStyles.primaryGradientEnd, borderRadius: BorderRadius.only( topRight: Radius.circular(MediaQuery.of(context).size.width * 0.75), ), ), ) ), Positioned( height: MediaQuery.of(context).padding.top + topSpace + 80.0, left: 80.0, right: 80.0, child: Align( alignment: Alignment.bottomCenter, child: Image.asset( "assets/images/onboarding_messaging.png", fit: BoxFit.contain, ), ), ), Positioned.fill( top: MediaQuery.of(context).padding.top + topSpace + 100.0, child: SingleChildScrollView( child: Column( children: <Widget>[ Text( "Unlimited Groups".i18n, style: AppStyles.heading1), Box(height: 37.0), Padding( padding: EdgeInsets.symmetric(horizontal: AppStyles.horizontalMargin), child: Text( "product_description".i18n, style: AppStyles.paragraph), ), Box(height: 37.0) ] + offering.availablePackages.map<Widget>( (package) => Padding( padding: package == offering.availablePackages.last ? EdgeInsets.symmetric(horizontal: AppStyles.horizontalMargin) : EdgeInsets.only(left: AppStyles.horizontalMargin, right: AppStyles.horizontalMargin, bottom: 24.0), child: Container( height: 50.0, width: double.infinity, decoration: BoxDecoration( color: package.packageType == PackageType.lifetime ? AppStyles.brightGreenBlue : Colors.white, borderRadius: BorderRadius.circular(25.0) ), child: FlatButton( onPressed: () => _makePurchase(purchases, package, context), child: Center( child: Text( _getPackagePricing(package), style: AppStyles.heading2Bold,), ) ) ), ) ).toList() + [ Box(height: 15.0,), FlatButton( onPressed: () async => await _restorePurchases(context, purchases), child: Text( "Restore Purchases".i18n, style: AppStyles.heading2.copyWith(color: Colors.white), ), ), Box(height: 15.0,), Padding( padding: EdgeInsets.symmetric(horizontal: AppStyles.horizontalMargin), child: Text( "subscription_tos".i18n, style: AppStyles.smallText.copyWith(color: Colors.white), ), ) ], ), ) ), Positioned( top: MediaQuery.of(context).padding.top + 5.0, left: 15.0, child: GestureDetector( onTap: () => Navigator.of(context).pop(), child: Container( height: 25.0, width: 25.0, padding: EdgeInsets.all(2.0), decoration: BoxDecoration( color: Colors.white12, shape: BoxShape.circle, ), child: Icon(Icons.close, size: 16.0,), ), ) ) ], )); })), ); } Future _restorePurchases(BuildContext context, PurchasesService purchases) async { showWaitingDialog( context: context, onWaiting:() => purchases.restorePurchases(), onDone: () async { if(await purchases.hasUnlimitedGroupsEntitlement()) { await Navigator.of(context).pushReplacement(FadeRoute(page: widget.onSuccessBuilder())); } else { infoDialog(context, "Unlimited groups have not been purchased using this account.".i18n); } }); } Future _makePurchase(PurchasesService purchases, Package package, BuildContext context) async { if(await purchases.purchaseUnlimitedGroupsPackage(package)) { await Navigator.of(context).pushReplacement(FadeRoute(page: widget.onSuccessBuilder())); } else { warningDialog( context, "Purchase failed.".i18n, showNeutralButton: false, positiveText: "Okay".i18n, positiveAction: () => Navigator.of(context).pop() ); } } String _getPackagePricing(Package package) { switch(package.packageType) { case PackageType.lifetime: return "product_pricing: %s / %s".fill([package.product.priceString, "lifetime".i18n]); break; case PackageType.annual: return "product_pricing: %s / %s".fill([package.product.priceString, "year*".i18n]); break; case PackageType.sixMonth: return "product_pricing: %s / %s".fill([package.product.priceString, "six months*".i18n]); break; case PackageType.threeMonth: return "product_pricing: %s / %s".fill([package.product.priceString, "three months*".i18n]); break; case PackageType.twoMonth: return "product_pricing: %s / %s".fill([package.product.priceString, "two months*".i18n]); break; case PackageType.monthly: return "product_pricing: %s / %s".fill([package.product.priceString, "monthly*".i18n]); break; case PackageType.weekly: return "product_pricing: %s / %s".fill([package.product.priceString, "weekly*".i18n]); break; case PackageType.unknown: case PackageType.custom: default: return package.product.priceString; break; } } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/group_collection_screen.dart
import 'dart:async'; import 'dart:io'; import 'package:commons/commons.dart'; import 'package:flappy_search_bar/flappy_search_bar.dart'; import 'package:flappy_search_bar/search_bar_style.dart'; import 'package:flutter/material.dart'; import 'package:flutter_focus_watcher/flutter_focus_watcher.dart'; import 'package:hidden_drawer_menu/hidden_drawer/hidden_drawer_menu.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; import 'package:relay/services/purchases_service.dart'; import 'package:relay/ui/screens/paywall_screen.dart'; import 'package:relay/ui/transitions/scale_route.dart'; import 'package:relay/ui/models/groups_collection_model.dart'; import 'package:relay/models/toggleable_group_item.dart'; import 'package:relay/ui/widgets/group_item_card.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/ui/widgets/hamburger.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/ui/screens/group_create_new_screen.dart'; class GroupCollectionScreen extends StatefulWidget { const GroupCollectionScreen({Key key}) : super(key: key); @override _GroupCollectionScreenState createState() => _GroupCollectionScreenState(); } class _GroupCollectionScreenState extends State<GroupCollectionScreen> { bool isMenuOpen = false; StreamSubscription<MenuState> _menuOpenedSubscription; @override void didChangeDependencies() { if(_menuOpenedSubscription == null) { _menuOpenedSubscription = SimpleHiddenDrawerProvider .of(context) .getMenuStateListener() .listen((state) { var isOpen = state == MenuState.open; if(isMenuOpen != isOpen) { setState(() => isMenuOpen = isOpen); } }); } super.didChangeDependencies(); } @override void dispose() { _menuOpenedSubscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => GroupsCollectionModel(), child: FocusWatcher( child: Scaffold( floatingActionButton: Padding( padding: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom), child: Consumer<GroupsCollectionModel>( builder: (context, model, _) => FloatingActionButton( onPressed: () async { if (model.shouldShowPaywall) { Navigator.push(context, ScaleRoute(page:PaywallScreen(onSuccessBuilder: () => GroupCreateNewScreen()))); } else if (await Permission.contacts.isDenied) { warningDialog( context, "no-contacts-permission-text".i18n, positiveText: "Open Settings".i18n, positiveAction: () => openAppSettings(), neutralText: "Exit".i18n, ); } else { Navigator.push(context, MaterialPageRoute(builder: (_) => GroupCreateNewScreen())); } }, backgroundColor: AppStyles.brightGreenBlue, child: Icon(Icons.add, color: Colors.white,), ), ), ), body: IgnorePointer( ignoring: isMenuOpen, child: Container( width: MediaQuery.of(context).size.width, decoration: BoxDecoration( gradient: LinearGradient( colors: [AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight)), child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top + 30.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(left: AppStyles.horizontalMargin), child: Hamburger( onTap: () => SimpleHiddenDrawerProvider.of(context).toggle()), ), Padding( padding: EdgeInsets.only(top: 20.0, bottom: 6.0, left: AppStyles.horizontalMargin), child: Text("Groups".i18n, style: AppStyles.heading1,),), _buildSearchBar(context), ],), ), ), ), ), ), ); } Widget _buildSearchBar(BuildContext context) { return Expanded( child: Consumer<GroupsCollectionModel>( builder: (context, model, _) { if(model.items == null || model.items.length == 0) return _buildEmptyState(); return SearchBar<ToggleableGroupItemModel>( searchBarPadding: EdgeInsets.symmetric(horizontal: AppStyles.horizontalMargin), onSearch: (query) => model.search(query), onItemFound: (group, _) => _buildContactGroup(group), hintText: "Search...".i18n, hintStyle: AppStyles.paragraph, textStyle: AppStyles.paragraph, icon: Icon(Icons.search, color: Colors.white38), suggestions: model.items, cancellationWidget: Text("Cancel".i18n, style: AppStyles.paragraph), emptyWidget: _buildNoResultsState(), searchBarStyle: SearchBarStyle( backgroundColor: Colors.white12, padding: EdgeInsets.only(left: 15.0), borderRadius: BorderRadius.all(Radius.circular(25.0)), ), ); }, ), ); } Widget _buildContactGroup(ToggleableGroupItemModel item) { return Padding( padding: EdgeInsets.symmetric(horizontal: AppStyles.horizontalMargin), child: GroupItemCard(group: item,), ); } Widget _buildEmptyState() { return _buildFilledText("Let's add your first group.".i18n); } Center _buildFilledText(String text) { return Center( child: Text( text, style: AppStyles.paragraph.copyWith(color: Colors.white))); } Widget _buildNoResultsState() { return _buildFilledText("No results.".i18n); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/group_create_new_screen.dart
import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; import 'package:commons/commons.dart'; import 'package:flappy_search_bar/flappy_search_bar.dart'; import 'package:flappy_search_bar/search_bar_style.dart'; import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:flutter_focus_watcher/flutter_focus_watcher.dart'; import 'package:provider/provider.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:waiting_dialog/waiting_dialog.dart'; import 'package:relay/ui/models/add_new_group_model.dart'; import 'package:relay/ui/models/contact_search_result_model.dart'; import 'package:relay/ui/widgets/contact_list_item.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/translation/translations.dart'; class GroupCreateNewScreen extends StatefulWidget { @override _GroupCreateNewScreenState createState() => _GroupCreateNewScreenState(); } class _GroupCreateNewScreenState extends State<GroupCreateNewScreen> with RouteAwareAnalytics { final double _topOfContentHeight = 100.0; final double _selectedContactsWidgetHeight = 80.0; final TextEditingController groupTextEditingController = TextEditingController(); @override String get screenClass => "GroupCreateNewScreen"; @override String get screenName => "/GroupCreateNew"; @override void dispose() { groupTextEditingController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var bottom = MediaQuery.of(context).padding.bottom; var top = MediaQuery.of(context).padding.top; return FocusWatcher( child: Scaffold( resizeToAvoidBottomInset: false, body: ChangeNotifierProvider<AddNewGroupModel>( create: (_) => AddNewGroupModel(), child: Stack( children: <Widget>[ // header Positioned( top: 0.0, left: 0.0, right: 0.0, height: top + 130.0, child: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight)), child: Padding( padding: EdgeInsets.only( left: 15.0, right: AppStyles.horizontalMargin), child: Row(children: <Widget>[ BackButton(onPressed: () { return Navigator.pop(context); }, color: Colors.white,), Expanded( child: Padding( padding: EdgeInsets.only(top: top), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Consumer<AddNewGroupModel>( builder: (context, model, _) => TextField( controller: groupTextEditingController, style: AppStyles.heading1.copyWith(color: Colors.white), decoration: InputDecoration( hintText: "New Group".i18n, hintStyle: AppStyles.heading1.copyWith(color: Colors.white), border: InputBorder.none)), ), Container( height: 0.50, color: Colors.white)])))])))), Positioned( bottom: 0.0, left: 0.0, right: 0.0, height: bottom + 100.0, child: Container( color: AppStyles.brightGreenBlue, child: Padding( padding: EdgeInsets.only(top:30), child: null))), // body Positioned.fill( top: top + 90.0, bottom: bottom + 60.0, child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(40.00)), child: Consumer<AddNewGroupModel>( builder: (context, model, _) { if(model.isLoading) return _buildLoadingWidget(); if(model.filteredAllContactsList.isEmpty) return _buildEmptyState(); return Padding( padding: EdgeInsets.only( top: 0.0, left: AppStyles.horizontalMargin, right: AppStyles.horizontalMargin), child: LayoutBuilder( builder: (context, constraints) => Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ SizedBox( height: _topOfContentHeight, width: MediaQuery.of(context).size.width, child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ model.selectedContactsList.isEmpty ? Expanded(child: Center(child: Text("Please select some contacts.".i18n),)) : ConstrainedBox( constraints: BoxConstraints( minHeight: 0.0, maxHeight: _selectedContactsWidgetHeight), child: SingleChildScrollView( child: Wrap( spacing: 10.0, children: model.selectedContactsList.map((contact) => ChoiceChip( onSelected: (selected) => model.selectContact(context: context, contact: contact), selected: false, backgroundColor: AppStyles.primaryGradientEnd, labelStyle: AppStyles.paragraph, label: TextOneLine(contact.name.length < 15 ? contact.name : contact.name.substring(0, 14) + "...",), avatar: CircleAvatar( backgroundColor: AppStyles.lightGrey, child: Icon(Icons.close, color: Colors.black)))).toList())))])), SizedBox( height: constraints.maxHeight - _topOfContentHeight, child: Stack( children: <Widget>[ Positioned.fill( top: 0.0, child: SearchBar<ContactSearchResultModel>( shrinkWrap: true, searchBarPadding: EdgeInsets.only(right: 100.0), textStyle: AppStyles.paragraph.copyWith(color: Colors.black), searchBarStyle: SearchBarStyle( padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 0.0), borderRadius: BorderRadius.circular(10.0)), onSearch: (query) => model.search(query), onItemFound: (contact, _) => ContactListItem(contact: contact,), suggestions: model.filteredAllContactsList, buildSuggestion: (contact, _) => ContactListItem(contact: contact,),), ), Positioned( right: 0.0, width: 100.0, height: 75.0, child: GestureDetector( onTap: () => model.filterToOnlyMobileNumbers = !model.filterToOnlyMobileNumbers, child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Checkbox( value: model.filterToOnlyMobileNumbers, onChanged: (newValue) => model.filterToOnlyMobileNumbers = newValue), Text("Mobile #".i18n, style: AppStyles.smallText, overflow: TextOverflow.ellipsis,)]), ))]))]))); } ))), // this is to fix a very annoying bug with flappy_search_bar // Reported here: https://github.com/smartnsoft/flappy_search_bar/issues/21 Positioned( bottom: 0, width: MediaQuery.of(context).size.width, height: 100.0 + MediaQuery.of(context).padding.bottom, child: Stack( children: <Widget>[ Positioned.fill( top:40.0, child: LayoutBuilder( builder: (context, constraints) => Container( width: constraints.maxWidth, height: constraints.maxHeight, color: AppStyles.brightGreenBlue, child: Consumer<AddNewGroupModel>( builder: (_, model, __) => FlatButton( onPressed: () { if(groupTextEditingController.value.text == null || groupTextEditingController.value.text.isEmpty) { infoDialog( context, "Please give your group a name.".i18n, neutralText: "Okay".i18n); return; } model.groupName = groupTextEditingController.value.text; showWaitingDialog( context: context, onWaiting: () => model.save(), onDone: () => Navigator.pop(context)); }, child: Text("save".i18n, style: AppStyles.heading1)), )))) ], ) ) ], ), ), ), ); } Widget _buildEmptyState([String emptyLabel = "Add some contacts first."]) { return Center(child: Text(emptyLabel.i18n, style: AppStyles.heading2)); } Widget _buildLoadingWidget() { return Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 75, width: 75, child: FlareActor( "assets/animations/loading.flr", animation: "active",), ), Padding( padding: const EdgeInsets.only(left: 20.0), child: FadeAnimatedTextKit( textAlign: TextAlign.left, text: [ "loading your contacts. ".i18n, "loading your contacts.. ".i18n, "loading your contacts...".i18n], pause: Duration(milliseconds: 150), textStyle: AppStyles.heading2), ) ], )); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/splash_screen.dart
import 'dart:async'; import 'package:flare_flutter/flare_actor.dart'; import 'package:flutter/material.dart'; import 'package:relay/ui/models/app_bootstraper_model.dart'; import 'package:relay/ui/screens/onboarding_screen.dart'; import 'package:relay/ui/transitions/fade_route.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/ui/screens/home_screen.dart'; class SplashScreen extends StatefulWidget { SplashScreen({Key key}) : super(key: key); @override _SplashScreenState createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { AppBootstrapperModel bootstrapper; Completer _completer; @override void initState() { bootstrapper = AppBootstrapperModel(); _completer = Completer(); _completer.complete(bootstrapper.init(context)); super.initState(); } @override Widget build(BuildContext context) { return FutureBuilder<dynamic>( future: _completer.future, initialData: BootstrapStatus.Initializing, builder: (context, snapshot) { String animation = bootstrapper.status == BootstrapStatus.Initializing ? "Splash_Loop" : "Splash_Ends"; return Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight)), height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, child: FlareActor( "assets/animations/splash_screen.flr", fit: BoxFit.fitHeight, callback: (s) { if(bootstrapper.status == BootstrapStatus.ReadyToLaunch) { Navigator .of(context) .pushReplacement( FadeRoute(page: HomeScreen())); } else if(bootstrapper.status == BootstrapStatus.RequiresOnboarding) { Navigator .of(context) .pushReplacement( FadeRoute(page: OnboardingScreen())); } }, animation: animation, ) ); }, ); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/compose_message_screen.dart
import 'dart:async'; import 'package:commons/commons.dart'; import 'package:flutter/material.dart'; import 'package:flutter_focus_watcher/flutter_focus_watcher.dart'; import 'package:lottie/lottie.dart'; import 'package:percent_indicator/percent_indicator.dart'; import 'package:provider/provider.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:relay/models/contact_item.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/models/message_recipient.dart'; import 'package:relay/ui/models/compose_message_model.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/mixins/color_mixin.dart' as RelayApp; import 'package:relay/ui/widgets/message_container.dart'; import 'package:relay/translation/translations.dart'; class ComposeMessageScreen extends StatefulWidget { final GroupItemModel group; final List<ContactItemModel> recipients; const ComposeMessageScreen({Key key, @required this.group, @required this.recipients}) : super(key: key); @override _ComposeMessageScreenState createState() => _ComposeMessageScreenState(); } class _ComposeMessageScreenState extends State<ComposeMessageScreen> with RouteAwareAnalytics { final TextEditingController textMessagingController = TextEditingController(); @override String get screenClass => "ComposeMessageScreen"; @override String get screenName => "/ComposeMessage"; @override void dispose() { textMessagingController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return FocusWatcher( child: ChangeNotifierProvider<ComposeMessageModel>( create: (_) => ComposeMessageModel(group: widget.group, recipients: widget.recipients), child: Scaffold( resizeToAvoidBottomInset: false, backgroundColor: AppStyles.lightGrey, body: Stack( children: <Widget>[ // Header Positioned( top: 0.0, left: 0.0, right: 0.0, height: MediaQuery.of(context).padding.top + 90.0, child: Padding( padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top), child: Stack(children: <Widget>[ Align( alignment: Alignment.centerLeft, child: BackButton( color: AppStyles.darkGrey, onPressed: () => Navigator.of(context).pop())), Positioned.fill( child: Center( child: Consumer<ComposeMessageModel>( builder: (_,model,__) => Text(model.groupName, style: AppStyles.heading1.copyWith(color: AppStyles.darkGrey),)),)) ]))), // Body Positioned.fill( top: MediaQuery.of(context).padding.top + 90.0, left: 0.0, right: 0.0, child: ClipRRect( borderRadius: BorderRadius.only(topLeft: Radius.circular(40.00), topRight: Radius.circular(40.00)), child: Container( color: Colors.white, child: Padding( padding: EdgeInsets.only(left: 23.0, right: 23.0, bottom: 23.0), child: Stack( children: <Widget>[ // Message list Positioned.fill( bottom: 115.0, left: 40.0, right: 0.0, top: 0.0, child: Consumer<ComposeMessageModel>( builder: (_, model, __) => ListView.builder( reverse: true, itemCount: model.messages.length, itemBuilder: (_, index) { var message = model.messages[index]; return MessageContainer( message: message.message, sendDateTime: message.sendDateTime, recipients: message.recipients, onDetailsPressed: () {}, ); }))), // New Message Box Positioned( bottom: 0, left: 0, right: 0, height: 140.0, child: Container( decoration: BoxDecoration( color: AppStyles.lightGrey, borderRadius: BorderRadius.circular(30.00)), child: Padding( padding: const EdgeInsets.all(15.0), child: Row(children: <Widget>[ Expanded( child: TextField( textCapitalization: TextCapitalization.sentences, keyboardType: TextInputType.multiline, controller: textMessagingController, decoration: InputDecoration( border: InputBorder.none ), maxLines: 6,), ), Consumer<ComposeMessageModel>( builder: (_, model, __) => Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( height: 45.00, width: 58.00, decoration: BoxDecoration( gradient: LinearGradient( colors: [AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight), boxShadow: [ BoxShadow( offset: Offset(0.00,3.00), color: Color(0xff000000).withOpacity(0.16), blurRadius: 6), ], borderRadius: BorderRadius.circular(25.00)), child: Center( child: IconButton( onPressed: () { if(textMessagingController.text.isEmpty) { toast("Please enter a message first.".i18n); return; } showDialog( context: context, barrierDismissible: false, builder: (c) => AlertDialog( backgroundColor: Colors.transparent, contentPadding: EdgeInsets.all(0), content: _SendIndividuallyDialog( context: context, model: model, messageController: textMessagingController) ) ); }, icon: Icon( Icons.person_outline, color: Colors.white)))), Icon( Icons.arrow_forward_ios, size: 10.0, color: RelayApp.HexColor.fromHex("#D9D9D9")), Container( height: 45.00, width: 58.00, decoration: BoxDecoration( color: AppStyles.brightGreenBlue, boxShadow: [ BoxShadow( offset: Offset(0.00,3.00), color: Color(0xff000000).withOpacity(0.16), blurRadius: 6), ], borderRadius: BorderRadius.circular(25.00)), child: Center( child: IconButton( onPressed: () async { if(textMessagingController.text.isEmpty) { toast("Please enter a message first.".i18n); return; } else if(await model.sendMessageToGroup(message: textMessagingController.text)) { textMessagingController.clear(); } }, icon: Icon( Icons.people_outline, color: Colors.white)))) ], ), ) ],), ))) ],))), )), Positioned( top: MediaQuery.of(context).padding.top + 70.0, left: 0.0, right: 0.0, child: Center( child: Container( height: 35.00, decoration: BoxDecoration( color: Color(0xfff3f3f3), borderRadius: BorderRadius.circular(20.00)), child: Padding( padding: const EdgeInsets.only(left: 16.0, right:16.0, top: 10.0), child: Consumer<ComposeMessageModel>( builder: (_, model, __) => Text("%d People".plural(model.recipients.length), style: AppStyles.paragraph.copyWith( color: AppStyles.darkGrey, fontWeight: FontWeight.bold)), ), )), ), ) ], ) ), ), ); } } class _SendIndividuallyDialog extends StatefulWidget { final BuildContext context; final ComposeMessageModel model; final TextEditingController messageController; const _SendIndividuallyDialog({ Key key, @required this.model, @required this.context, @required this.messageController }) : super(key: key); @override _SendIndividuallyDialogState createState() => _SendIndividuallyDialogState(); } class _SendIndividuallyDialogState extends State<_SendIndividuallyDialog> { double percent; String nextName; String nextNumber; String index; String total; Completer<SendMessageNextStep> messageSendCompleter = Completer(); @override void dispose() { if(!messageSendCompleter.isCompleted) { messageSendCompleter.complete(SendMessageNextStep.Cancel); } super.dispose(); } @override void initState() { percent = 0.0; nextName = ""; nextNumber = ""; index = "1"; total = widget.model.recipients.length.toString(); widget.model .sendMessageToIndividuals(message: widget.messageController.text, onSent: onSent) .then((didSendMessages) { if(didSendMessages) { widget.messageController.clear(); } return Navigator.pop(widget.context, true); }); super.initState(); } Future<SendMessageNextStep> onSent(double percent, int idx, MessageRecipient recipient) { setState(() { this.percent = percent; index = idx.toString(); nextName = recipient.name; nextNumber = recipient.number; }); messageSendCompleter = Completer(); return messageSendCompleter.future; } @override Widget build(BuildContext context) { return Stack( children: <Widget>[ Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(25.0)) ), width: MediaQuery.of(context).size.width, height: 400.0, child: Column( children: <Widget>[ Expanded( child: Center( child: SizedBox( height: 250.0, width: 250.0, child: Lottie.asset( "assets/animations/paper-flying-animation.json", repeat: true) ), ), ), Row(children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 22.0), child: Container( height: 60.0, child: Stack( children: <Widget>[ Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Align( alignment: Alignment.topLeft, child: Text(index, style: AppStyles.heading1.copyWith(color: AppStyles.primaryGradientEnd),)), Transform.rotate( angle: -45.0, child: Container( color: AppStyles.primaryGradientEnd, height: 4.0, width: 60.0,),), Align( alignment: Alignment.bottomRight, child: Text(total, style: AppStyles.heading1.copyWith(color: AppStyles.primaryGradientEnd),)), ],), ] ), ), ), Padding( padding: const EdgeInsets.only(left: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("Name", style: AppStyles.heading2Bold.copyWith(color: AppStyles.primaryGradientStart),), Text(nextName, style: AppStyles.heading2Bold.copyWith(color: AppStyles.primaryGradientStart),), Text(nextNumber, style: AppStyles.heading2.copyWith(color: AppStyles.primaryGradientStart),) ],), ) ],), Padding( padding: const EdgeInsets.symmetric( vertical: 24.0, horizontal: 28.0), child: LinearPercentIndicator( lineHeight: 18.0, percent: percent, animateFromLastPercent: true, progressColor: AppStyles.primaryGradientEnd, ), ), Container( width: 212.0, child: FlatButton( onPressed: () => messageSendCompleter.complete(SendMessageNextStep.Send), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0) ), color: AppStyles.primaryGradientEnd, child: Text("send".i18n, style: AppStyles.paragraph) ), ), Padding( padding: const EdgeInsets.only(bottom: 20.0), child: FlatButton( onPressed: () => messageSendCompleter.complete(SendMessageNextStep.Skip), child: Text("skip".i18n, style: AppStyles.paragraph.copyWith(color: AppStyles.primaryGradientEnd)),), ) ], ), ), Positioned( right:0, top:0, child: IconButton( onPressed: () => messageSendCompleter.complete(SendMessageNextStep.Cancel), icon: Icon(Icons.close, color: AppStyles.primaryGradientEnd))) ], ); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/settings_screen.dart
import 'dart:io'; import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; import 'package:commons/commons.dart'; import 'package:flutter/material.dart'; import 'package:flutter_focus_watcher/flutter_focus_watcher.dart'; import 'package:image_picker/image_picker.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:relay/models/group_sort.dart'; import 'package:relay/services/app_reviews_service.dart'; import 'package:relay/translation/eula.dart'; import 'package:relay/translation/privacy_policy.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/ui/app_styles.dart'; import 'package:relay/mixins/color_mixin.dart'; import 'package:relay/ui/models/app_settings_model.dart'; import 'package:relay/ui/models/package_info_model.dart'; class SettingsScreen extends StatefulWidget { final AppSettingsModel model; const SettingsScreen({Key key, @required this.model}) : super(key: key); @override _SettingsScreenState createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> with RouteAwareAnalytics { final TextEditingController signatureTextController = TextEditingController(); final FocusNode signatureFocusNode = FocusNode(); @override String get screenClass => "SettingsScreen"; @override String get screenName => "/Settings"; @override void dispose() { signatureTextController.dispose(); signatureFocusNode.dispose(); super.dispose(); } @override void initState() { signatureTextController.text = widget.model.signature; super.initState(); } @override Widget build(BuildContext context) { final double headerHeight = MediaQuery.of(context).padding.top + 230.0; return Consumer<AppSettingsModel>( builder: (context, model, __) { return FocusWatcher( child: Scaffold( body: Container( width: double.maxFinite, height: double.maxFinite, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [HexColor.fromHex("#626672"), HexColor.fromHex("#6B7899")] ) ), child: Stack( children: <Widget>[ Positioned( top: 0.0, left: 0.0, right: 0.0, height: headerHeight, child: Container( height: 230.00, decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( offset: Offset(0.00, 15.00), color: Color(0xff000000).withOpacity(0.16), blurRadius: 30, ), ], borderRadius: BorderRadius.only(bottomLeft: Radius.circular(40.00), bottomRight: Radius.circular(40.00), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only( left: 15.0, top: MediaQuery.of(context).padding.top), child: Row( children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back_ios, color: AppStyles.darkGrey), onPressed: () { model.signature = signatureTextController.text; return Navigator.of(context).pop(); }, ), Text("Your Profile".i18n, style: AppStyles.heading1.copyWith(color: AppStyles.darkGrey)), Expanded( child: Container()), FlatButton( onPressed: () => _changeName(context, model), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Container( width: 5.0, height: 5.0, decoration: BoxDecoration( shape: BoxShape.circle, color: AppStyles.darkGrey ), ), Box(height: 45.0, width: 6.0,), Container( width: 5.0, height: 5.0, decoration: BoxDecoration( shape: BoxShape.circle, color: AppStyles.darkGrey ), ), Box(width: AppStyles.horizontalMargin,) ],), ), ],), ), Box(height: 60.0,), Padding( padding: EdgeInsets.only(left: AppStyles.horizontalMargin), child: Row( children: <Widget>[ GestureDetector( onTap: () async { if(await Permission.photos.isGranted == false) { var status = await Permission.photos.request(); if(status == PermissionStatus.denied) { showToast("Can't access photos. Please grant photos access in settings.".i18n); } } var image = await ImagePicker.pickImage(source: ImageSource.gallery); await model.updateImagePath(image); }, child: Column(children: <Widget>[ Container( width: 60.0, height: 60.0, decoration: BoxDecoration( shape: BoxShape.circle, image: model.imagePath != null && model.imagePath.isNotEmpty ? DecorationImage( fit: BoxFit.cover, image: FileImage(File(model.imagePath))) : null, color: AppStyles.darkGrey ), child: model.imagePath == null || model.imagePath.isEmpty ? Center( child: Icon(Icons.person, color: Colors.white, size: 30.0,),) : null, ), SizedBox(height: 10.0,), Text( "change".i18n, style: AppStyles.smallText.copyWith(color: AppStyles.primaryGradientStart)) ],), ), Box(width: 20.0,), Expanded( child: Padding( padding: EdgeInsets.only(bottom: 24.0, right: AppStyles.horizontalMargin), child: GestureDetector( onTap: () => _changeName(context, model), child: TextOneLine( model.name == null || model.name.isEmpty ? "Enter Name".i18n : model.name, style: AppStyles.heading1.copyWith(fontWeight: FontWeight.w100, color: Colors.black) ), ), ), ) ],), ), ], ) ) ), Positioned.fill( top: headerHeight + 40.0, bottom: MediaQuery.of(context).padding.bottom + 14.0, child: SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric(horizontal: AppStyles.horizontalMargin), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("Group Sorting".i18n, style: AppStyles.heading2.copyWith(color: AppStyles.lightGrey),), Box(height: 6.0,), Container( decoration: BoxDecoration( border: Border.all(color: Colors.white, width: 1.0), borderRadius: BorderRadius.all(Radius.circular(10.0)), color: AppStyles.lightGrey.withAlpha(20) ), child: DropdownButton<GroupSort>( isExpanded: true, value: model.defaultGroupSort, underline: Container(height: 0.0, color: Colors.transparent,), icon: Icon(Icons.keyboard_arrow_down, color: Colors.white, size: 30.0,), selectedItemBuilder: (_) => GroupSort.valueStrings.map<Widget>((s) => Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.only(left: 15.0), child: Text( s.toString(), style: AppStyles.heading2.copyWith(color: Colors.white) ), ) ) ).toList(), onChanged: (sort) => model.defaultGroupSort = sort, items: GroupSort.values .map((v) => DropdownMenuItem<GroupSort>( value: v, child: Text(v.toString(), style: AppStyles.heading2 ) ) ).toList()), ), Box(height: 30.0,), Text("Signature".i18n, style: AppStyles.heading2.copyWith(color: AppStyles.lightGrey),), Box(height: 6.0,), Container( padding: EdgeInsets.symmetric(horizontal:15.0, vertical: 5.0), decoration: BoxDecoration( border: Border.all(color: Colors.white, width: 1.0), borderRadius: BorderRadius.all(Radius.circular(10.0)), color: AppStyles.lightGrey.withAlpha(20) ), child: TextFormField( autocorrect: true, focusNode: signatureFocusNode, controller: signatureTextController, textCapitalization: TextCapitalization.sentences, maxLines: 6, style: AppStyles.paragraph, decoration: InputDecoration( border: InputBorder.none ), ), ), Box(height: 15.0,), Row(children: <Widget>[ Theme( data: ThemeData(unselectedWidgetColor: Colors.white), child: Checkbox( value: model.autoIncludeSignature, activeColor: Colors.white, checkColor: AppStyles.darkGrey, onChanged: (value) => model.autoIncludeSignature = value,), ), GestureDetector( onTap: () => model.autoIncludeSignature = !model.autoIncludeSignature, child: Text( "Include signature on every message.".i18n, style: AppStyles.paragraph)) ],), Row(children: <Widget>[ FlatButton( child: Text( "Terms of Use".i18n, style: AppStyles.paragraph), onPressed: () => _showEula(context), ), FlatButton( child: Text( "Privacy Policy".i18n, style: AppStyles.paragraph), onPressed: () => _showPrivacyPolicy(context), ), ],), FlatButton( color: AppStyles.brightGreenBlue, child: Text( "Review Relay".i18n, style: AppStyles.paragraph), onPressed: () => _showReviews(context), ) ],), ), ) ), Positioned( bottom: 40.0, left: AppStyles.horizontalMargin, right: 0.0, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("Copyright 2020 - Hinterland Supply Co.", style: AppStyles.smallText.copyWith(color: Colors.white)), Text("Version: %s".fill([ Provider.of<PackageInfoModel>(context).version ]), style: AppStyles.smallText.copyWith(color: Colors.white)), ], ), ) ], ), ), ), ); }, ); } void _changeName(BuildContext context, AppSettingsModel model) { singleInputDialog( context, label: "", title: "Enter Name".i18n, maxLines: 1, validator: (s) => s != null && s.isNotEmpty ? null : "Name can't be empty!", value: model.name, positiveText: "Save".i18n, positiveAction: (name) => model.name = name, negativeText: "Cancel".i18n ); } void _showEula(BuildContext context) { errorDialog( context, Eula.text, textAlign: TextAlign.left, neutralText: "I Agree".i18n, icon: AlertDialogIcon.INFO_ICON, title: "EULA - Terms Of Use"); } void _showPrivacyPolicy(BuildContext context) { errorDialog( context, PrivacyPolicy.text, textAlign: TextAlign.left, neutralText: "I Agree".i18n, icon: AlertDialogIcon.INFO_ICON, title: "Privacy Policy"); } void _showReviews(BuildContext context) { Provider.of<AppReviewsService>(context, listen: false).requestReviews(context); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/menu_screen.dart
import 'dart:io'; import 'dart:ui'; import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:hidden_drawer_menu/hidden_drawer/hidden_drawer_menu.dart'; import 'package:provider/provider.dart'; import 'package:relay/ui/models/app_settings_model.dart'; import 'package:relay/ui/screens/settings_screen.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/ui/widgets/long_arrow_button.dart'; import 'package:relay/mixins/color_mixin.dart'; import 'package:relay/ui/app_styles.dart'; class MenuScreen extends StatefulWidget { const MenuScreen({ Key key, }) : super(key: key); @override _MenuScreenState createState() => _MenuScreenState(); } class _MenuScreenState extends State<MenuScreen> { @override Widget build(BuildContext context) { return Scaffold( body: Container( width: double.maxFinite, height: double.maxFinite, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [HexColor.fromHex("#626672"), HexColor.fromHex("#6B7899")] ) ), child: Consumer<AppSettingsModel>( builder: (context, model, __) => Stack(children: <Widget>[ if(model.name != null && model.name.isNotEmpty) Positioned( top: 0.0, left: 0.0, child: Container( height: 165.00 + MediaQuery.of(context).padding.top, width: 209.00, decoration: BoxDecoration( color: Color(0xff6f7a9a), borderRadius: BorderRadius.only(bottomRight: Radius.circular(40.00)) ), child: Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top, left: AppStyles.horizontalMargin), child: GestureDetector( onTap: () { Navigator.of(context).push(MaterialPageRoute(builder: (_) => SettingsScreen(model: model))); SimpleHiddenDrawerProvider.of(context).toggle(); }, child: Row( children: <Widget>[ if(model.imagePath != null && model.imagePath.isNotEmpty) Container( width: 40.0, height: 40.0, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( fit: BoxFit.cover, image: FileImage(File(model.imagePath))), color: AppStyles.darkGrey ), ), Box(width: 10.0,), Expanded( child: Padding( padding: const EdgeInsets.only(right: 8.0), child: TextOneLine( model.name, style: AppStyles.heading2.copyWith(color: Colors.white, fontWeight: FontWeight.w100) ), ), ), ], ), ) ) ) ) ), Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom + 25.0), child: LongArrowButton( onTap: () { SimpleHiddenDrawerProvider.of(context).toggle(); }, ), ) ), Positioned( bottom: MediaQuery.of(context).padding.top + 90.0, left: AppStyles.horizontalMargin, child: GestureDetector( onTap: () { Navigator.of(context).push(MaterialPageRoute(builder: (_) => SettingsScreen(model: model,))); SimpleHiddenDrawerProvider.of(context).toggle(); }, child: Row(children: <Widget>[ Icon(Icons.settings, color: Colors.white,), Box(width: 10.0), Text( "Settings".i18n, style: AppStyles.heading2.copyWith(color: Colors.white, fontWeight: FontWeight.w100) ) ],), ) ) ],), ), ), ); } }
0
mirrored_repositories/RelayApp/lib/ui
mirrored_repositories/RelayApp/lib/ui/screens/group_view_screen.dart
import 'package:assorted_layout_widgets/assorted_layout_widgets.dart'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:commons/commons.dart'; import 'package:flutter/material.dart'; import 'package:flutter_focus_watcher/flutter_focus_watcher.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:provider/provider.dart'; import 'package:relay/mixins/route_aware_analytics_mixin.dart'; import 'package:relay/ui/screens/compose_message_screen.dart'; import 'package:relay/models/toggleable_contact_model.dart'; import 'package:relay/translation/translations.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/ui/models/show_group_model.dart'; import 'package:relay/ui/app_styles.dart'; class GroupViewScreen extends StatefulWidget { final GroupItemModel _groupModel; const GroupViewScreen(this._groupModel, {Key key}) : super(key: key); @override _GroupViewScreenState createState() => _GroupViewScreenState(); } class _GroupViewScreenState extends State<GroupViewScreen> with RouteAwareAnalytics { @override String get screenClass => "GroupViewScreen"; @override String get screenName => "/GroupView"; @override Widget build(BuildContext context) { var bottom = MediaQuery.of(context).padding.bottom; var top = MediaQuery.of(context).padding.top; return ChangeNotifierProvider<ShowGroupModel>( create: (_) => ShowGroupModel(widget._groupModel), child: Consumer<ShowGroupModel>( builder: (context, model, _) => FocusWatcher( child: Scaffold( floatingActionButton: Padding( padding: EdgeInsets.only(bottom: 80.0 + MediaQuery.of(context).padding.bottom), child: FloatingActionButton( onPressed: () async { var contacts = await model.allContactsOnDevice; singleSelectDialog( context, "Add Contact".i18n, contacts, (SimpleItem item) { model.addContact(item.id, item.remarks); } ); }, backgroundColor: AppStyles.brightGreenBlue, child: Icon(Icons.add, color: Colors.white,)), ), resizeToAvoidBottomInset: false, body: Stack( children: <Widget>[ // header Positioned( top: 0.0, left: 0.0, right: 0.0, height: top + 130.0, child: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight)), child: Consumer<ShowGroupModel>( builder: (context, model, _) => Row(children: <Widget>[ Flexible( flex: 0, child: BackButton( onPressed: () => Navigator.pop(context), color: Colors.white),), Expanded( child: GestureDetector( onTap: () => _changeGroupName(context, model), child: TextOneLine( model.name, overflow: TextOverflow.ellipsis, style: AppStyles.heading1))), Flexible( flex: 0, child: IconButton( onPressed: () => _changeGroupName(context, model), icon: Icon(Icons.mode_edit, color: Colors.white,)), ), Flexible( flex: 0, child: Align( alignment: Alignment.centerRight, child: IconButton( icon: Icon(Icons.delete, color: Colors.white,), onPressed: () { confirmationDialog( context, "Are you sure you want to delete the group '%s'?".fill([model.name]), confirmationText: "Check this box to confirm delete!".i18n, title: "Confirm delete?".i18n, icon: AlertDialogIcon.WARNING_ICON, negativeText: "No".i18n, positiveText: "Yes".i18n, positiveAction: () async { await model.delete(); Navigator.pop(context); }); }))) ]) ))), // footer Positioned( bottom: 0.0, left: 0.0, right: 0.0, height: bottom + 100.0, child: Container( color: AppStyles.brightGreenBlue, child: FlatButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (_) => ComposeMessageScreen( group: widget._groupModel, recipients: model.selectedContacts,))); }, child: Padding( padding: EdgeInsets.only(top:30), child: Center( child: Text("compose".i18n, style: AppStyles.heading1) )), ))), // body Positioned.fill( top: top + 90.0, bottom: bottom + 60.0, child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(40.00)), child: Padding( padding: EdgeInsets.symmetric( vertical: 15.0, horizontal: AppStyles.horizontalMargin), child: LayoutBuilder( builder: (context, constraints) { var headerHeight = 22.0; var listViewHeight = constraints.maxHeight - headerHeight; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( height: headerHeight, child: Row( children: <Widget>[ Text("Contacts".i18n, style: AppStyles.heading2Bold), Text( " (%d people selected)".plural(model.selectedContactsCount), style: AppStyles.heading2), Expanded( child: Align( alignment: Alignment.centerRight, child: Checkbox( value: model.allSelected, onChanged: (s) => s ? model.selectAll() : model.unselectAll()))) ])), if(model.contacts.length > 0) Container( height: listViewHeight, child: ListView.builder( shrinkWrap: true, itemCount: model.contacts.length, itemBuilder: (context, index) { var contact = model.contacts[index]; return _buildContactWidget(context, contact); })) ]); })))), ]))))); } void _changeGroupName(BuildContext context, ShowGroupModel model) { singleInputDialog( context, label: "", title: "Group Name".i18n, maxLines: 1, validator: (s) => s != null && s.isNotEmpty ? null : "Name can't be empty!", value: model.name, positiveText: "Save".i18n, positiveAction: (name) => model.name = name, negativeText: "Cancel".i18n ); } Widget _buildContactWidget(BuildContext context, ToggleableContactItemModel contact) { var model = Provider.of<ShowGroupModel>(context); var lastContact = model.contacts.last; return Slidable( actionPane: SlidableDrawerActionPane(), actions: <Widget>[ IconSlideAction( icon: Icons.delete, color: Colors.red, caption: "delete".i18n, onTap: () => model.deleteContact(contact), ) ], child: GestureDetector( onTap: () => model.selectContact(contact, !contact.selected), child: Container( height: 80.0, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( children: <Widget>[ contact.imagePath != null && contact.imagePath.isNotEmpty ? Container( decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( image: FileImage(contact.imageFile), fit: BoxFit.fill,) ), width: 50, height: 50, ) : Container( width: 50, height: 50, decoration: BoxDecoration( gradient: LinearGradient( colors: [ AppStyles.primaryGradientStart, AppStyles.primaryGradientEnd], begin: Alignment.bottomLeft, end: Alignment.topRight), shape: BoxShape.circle), child: Center( child:Padding( padding: const EdgeInsets.all(8.0), child: AutoSizeText(contact.initials, style: AppStyles.heading1.copyWith(color: Colors.white),), ),),), Padding( padding: EdgeInsets.only(left: 14.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(contact.fullName, style: AppStyles.heading2Bold,), Text(contact.phone, style: AppStyles.smallText) ], ), ), Expanded( child: Align( alignment: Alignment.centerRight, child: Checkbox( onChanged: (s) => model.selectContact(contact, s), value: contact.selected,) ), ) ],), if(contact != lastContact) Center(child: Container(width: MediaQuery.of(context).size.width * 0.75, height: 1.00, color: Color(0xffdbdbdb),)) ],), ), ), ); } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/database_service.dart
import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/data/db/app_database.dart'; import 'package:relay/data/db/database_provider.dart'; class DatabaseService { final String _mainStorageDatabaseName = "appstore.db"; DatabaseProvider _provider; DatabaseService([DatabaseProvider provider]) { _provider = provider ?? dependencyLocator<DatabaseProvider>(); } /// Gets the main storage database for the app. Future<AppDatabase> getMainStorage() async { return await _provider.getLocalDatabase(_mainStorageDatabaseName); } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/message_service.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter_sms/flutter_sms.dart'; import 'package:relay/core/app_settings_keys.dart'; import 'package:relay/services/analytics_service.dart'; import 'package:relay/services/app_settings_service.dart'; import 'package:relay/data/db/query_package.dart'; import 'package:relay/data/db/dto/message_dto.dart'; import 'package:relay/data/db/db_collection.dart'; import 'package:relay/models/message_recipient.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/models/message_item.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/services/database_service.dart'; import 'package:relay/services/group_service.dart'; class MessageService { static const String _messageDbName = "messages"; static const String _messageSentEvent = "messaging_message_sent"; final DatabaseService _dbService; final GroupService _groupService; final AppSettingsService _appSettingsService; final AnalyticsService _analyticsService; Completer<DbCollection> _messageDb = Completer(); MessageService._(this._dbService, this._groupService, this._appSettingsService, this._analyticsService) { _dbService.getMainStorage().then((db) { _messageDb.complete(db.collections(_messageDbName)); }); } factory MessageService([DatabaseService databaseService, GroupService groupService, AppSettingsService appSettings, AnalyticsService analyticsService]) { return MessageService._( databaseService ?? dependencyLocator<DatabaseService>(), groupService ?? dependencyLocator<GroupService>(), appSettings ?? dependencyLocator<AppSettingsService>(), analyticsService ?? dependencyLocator<AnalyticsService>()); } Future<List<MessageItemModel>> getAllMessages(GroupItemModel group) async { assert(group != null); assert(group.id > 0); var db = await _messageDb.future; var messages = await db.query([QueryPackage( key: "groupId", value: group.id, filter: FilterType.EqualTo )], (map) => MessageDto.fromMap(map)); return messages .map((m) => MessageItemModel.fromDto(m, group)) .toList(); } Future<MessageSendingResult> sendMessage({ @required List<MessageRecipient> recipients, @required String message}) async { assert(recipients != null); assert(recipients.isNotEmpty); assert(message != null); assert(message.isNotEmpty); if(await _appSettingsService.getSettingBool(AppSettingsConstants.auto_include_signature_settings_key)) { String signature = await _appSettingsService.getSettingString(AppSettingsConstants.signature_settings_key); message = message + signature; } var result = await sendSMS(message: message, recipients: recipients.map((r) => r.number).toList()); if(result == "cancelled") { return MessageSendingResult.Cancelled; } else if (result == "failed") { return MessageSendingResult.Failed; } else if (result == "sent" || result == "SMS Sent!") { return MessageSendingResult.Success; } print("Unknown Result Message: $result"); return MessageSendingResult.Failed; } Future<MessageItemModel> logMessage({ @required List<MessageRecipient> recipients, @required GroupItemModel group, @required String message}) async { assert(group != null); assert(group.id > 0); assert(recipients != null); assert(recipients.isNotEmpty); assert(message != null); assert(message.isNotEmpty); var dto = MessageDto( message: message, sendDateTime: DateTime.now(), recipients: Map.fromIterables( recipients.map((r) => r.name), recipients.map((r) => r.number)), groupId: group.id); var db = await _messageDb.future; var id = await db.add(dto); dto = dto.copyWith(id: id); group.lastMessageSentDate = dto.sendDateTime; group = await _groupService.updateGroup(group); var messageCount = await _appSettingsService.getSettingInt(AppSettingsConstants.analytics_message_count); messageCount++; _appSettingsService.setSettingInt(AppSettingsConstants.analytics_message_count, messageCount); print("recording message count: $messageCount"); await _analyticsService.trackEvent( _messageSentEvent, properties: { 'recipients': recipients.length, }); return MessageItemModel.fromDto(dto, group); } } enum MessageSendingResult { Success, Cancelled, Failed }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/image_service.dart
import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/foundation.dart'; import 'package:image/image.dart' as I; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; import 'package:uuid/uuid.dart'; I.Image _resizeImage(_CopyResizeParams i) { return I.copyResize(i.image, width: i.width, height: i.height); } class _CopyResizeParams { final I.Image image; final int height; final int width; _CopyResizeParams(this.image, this.height, this.width); } class ImageService { Completer<Directory> _applicationDocumentsDirectory = Completer(); ImageService() { _applicationDocumentsDirectory.complete(getApplicationDocumentsDirectory()); } Future<String> importFile(File image, {String path, bool useRandomFileName = true, bool deleteOldFile = true}) async { var directory = await _applicationDocumentsDirectory.future; var destination = directory; String destinationPath = ""; String fileName = useRandomFileName ? Uuid().v1() + "." + p.extension(image.path) : p.basename(image.path); if(path != null && path.isNotEmpty) { destination = Directory(p.join(directory.path, path)); await destination.create(recursive: true); destinationPath = p.join(path, fileName); } else { destinationPath = fileName; } var pathToFile = p.join(destination.path, fileName); await image.copy(pathToFile); if(deleteOldFile) { await image.delete(); } return destinationPath; } /// Encodes the image stored in [bytes] as a jpeg and resizes it to [height] and [width]. /// /// Supply a [path] relative to the application documents directory. /// Set either [useRandomFileName] to generate a random filename or supply a [filename]. /// /// Returns the `path to the file` relative to the apps documents directory. Future<String> saveToFile({String path, Uint8List bytes, bool useRandomFileName = true, String filename, int height, int width}) async { I.Image image; bool isJpeg = false; try { image = await compute(I.decodeJpg, bytes); isJpeg = true; } catch (_) { image = await compute(I.decodeImage, bytes); } var start = DateTime.now(); if(width != null && height != null) { image = await compute(_resizeImage, _CopyResizeParams(image, height, width)); } var end = DateTime.now(); print(start.difference(end)); if(useRandomFileName) { var fileName = Uuid().v1() + ".jpg"; return await _writeImageToFile(path, fileName, image, isJpeg); } else if(filename != null && filename.isNotEmpty) { return await _writeImageToFile(path, filename, image, isJpeg); } throw ArgumentError.notNull("filename"); } /// Supply a relative [pathToFile] and a `File` will be returned with the absolute path to the file. Future<File> getImageFile(String pathToFile) async { return File(await getImagePath(pathToFile)); } /// Supply a relative [pathTofile] and a `String` will be returned with the absolute path to the file. Future<String> getImagePath(String pathToFile) async { assert(pathToFile != null); assert(pathToFile.isNotEmpty); if(pathToFile[0] == p.separator) { pathToFile = pathToFile.replaceRange(0, 1, ""); } var directory = await _applicationDocumentsDirectory.future; if(pathToFile.startsWith(directory.path)) { return pathToFile; } var pp = p.join(directory.path, pathToFile); return pp; } Future<String> _writeImageToFile(String path, String fileName, I.Image image, bool isJpeg) async { var directory = await _applicationDocumentsDirectory.future; var destination = directory; String destinationPath = ""; if(path != null && path.isNotEmpty) { destination = Directory(p.join(directory.path, path)); await destination.create(recursive: true); destinationPath = p.join(path, fileName); } else { destinationPath = fileName; } var pathToFile = p.join(destination.path, fileName); List<int> bytes = await compute(I.encodeJpg, image); await File(pathToFile).writeAsBytes(bytes); return destinationPath; } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/app_settings_service.dart
import 'dart:async'; import 'package:commons/commons.dart'; class AppSettingsService { static const String last_report_sent = "last_report_sent"; Completer<SharedPreferences> _prefs = Completer(); AppSettingsService([SharedPreferences prefs]) { _prefs.complete(prefs ?? SharedPreferences.getInstance()); } Future<String> getSettingString(String key, [String defaultValue = ""]) async { var prefs = await _prefs.future; return await _getSetting( prefs, key, defaultValue, prefs.getString, prefs.setString); } void setSettingString(String key, String value) { _prefs.future.then((prefs) => prefs.setString(key, value)); } Future<List<String>> getSettingListString(String key, [List<String> defaultValue]) async { defaultValue = defaultValue ?? []; var prefs = await _prefs.future; return await _getSetting( prefs, key, defaultValue, prefs.getStringList, prefs.setStringList); } void setSettingsStringList(String key, List<String> value) { _prefs.future.then((prefs) => prefs.setStringList(key, value)); } Future<int> getSettingInt(String key, [int defaultValue = 0]) async { var prefs = await _prefs.future; return await _getSetting( prefs, key, defaultValue, prefs.getInt, prefs.setInt); } void setSettingInt(String key, int value) { _prefs.future.then((prefs) => prefs.setInt(key, value)); } Future<bool> getSettingBool(String key, [bool defaultValue = false]) async { var prefs = await _prefs.future; return await _getSetting( prefs, key, defaultValue, prefs.getBool, prefs.setBool); } void setSettingsBool(String key, bool value) { _prefs.future.then((prefs) => prefs.setBool(key, value)); } Future<T> _getSetting<T>( SharedPreferences prefs, String key, T defaultValue, T Function(String) getValue, Future<bool> Function(String, T) setValue) async { if(!prefs.containsKey(key)) { await setValue(key, defaultValue); return defaultValue; } else { return getValue(key); } } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/group_service.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:relay/data/db/query_package.dart'; import 'package:relay/models/contact_item.dart'; import 'package:relay/data/db/db_collection.dart'; import 'package:relay/data/db/dto/contact_dto.dart'; import 'package:relay/data/db/dto/group_dto.dart'; import 'package:relay/data/db/dto/preferred_send_type.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/models/group_item.dart'; import 'package:relay/services/database_service.dart'; import 'package:relay/services/image_service.dart'; import 'package:relay/translation/translations.dart'; class GroupService { final DatabaseService _dbService; final ImageService _imageService; static const String _contactsDbName = "contacts"; static const String _groupsDbName = "groups"; StreamController<void> _groupOrContactsUpdated = StreamController.broadcast(); Completer<DbCollection> _groupsDb = Completer(); Completer<DbCollection> _contactsDb = Completer(); GroupService._(this._dbService, this._imageService) { _dbService.getMainStorage().then((db) { _groupsDb.complete(db.collections(_groupsDbName)); _contactsDb.complete(db.collections(_contactsDbName)); }); } factory GroupService([DatabaseService databaseService, ImageService imageService]) { return GroupService._( databaseService ?? dependencyLocator<DatabaseService>(), imageService ?? dependencyLocator<ImageService>() ); } Stream get updatesReceived => _groupOrContactsUpdated.stream; void dispose() { _groupOrContactsUpdated.close(); } /// Gets all the groups from the database. Future<List<GroupItemModel>> getAllGroups() async { var groupsDb = await _groupsDb.future; var contactsDb = await _contactsDb.future; var groups = await groupsDb.getAll((map) => GroupDto.fromMap(map)); List<GroupItemModel> groupModels = []; for(var group in groups) { List<ContactDto> contacts = await contactsDb.getMany(group.contacts, itemCreator: (map) => ContactDto.fromMap(map)); groupModels.add(GroupItemModel.fromDTO(group, contacts)); for(var group in groupModels) { for(var contact in group.contacts) { if(contact.imagePath != null && contact.imagePath.isNotEmpty) { contact.imageFile = await _imageService.getImageFile(contact.imagePath); } } } } return groupModels; } /// Add a new group with the specified [name] and [preferredSendType]. After creating the group /// you can add contacts to it using the [addContact] method. Future<GroupItemModel> addGroup({@required String name, PreferredSendType preferredSendType = PreferredSendType.Unset}) async { assert(name != null); assert(name.isNotEmpty); var groupDb = await _groupsDb.future; var dto = GroupDto( name: name, preferredSendType: preferredSendType, creationDate: DateTime.now()); dto = await _addGroup(groupDb, dto); if (dto.id == null || dto.id < 0) { return null; } else { _groupOrContactsUpdated.sink.add(null); return GroupItemModel( id: dto.id, name: dto.name, preferredSendType: dto.preferredSendType, creationDate: dto.creationDate); } } Future<GroupItemModel> addContact(GroupItemModel group, {String firstName, String lastName, String phone, String company, DateTime birthday, String imagePath}) async { assert(group != null); assert(group.id >= 0); var contactDb = await _contactsDb.future; var contact = await _addContact(firstName, lastName, phone, company, birthday, imagePath, contactDb); group.addContact(ContactItemModel.fromDto(contact)); _groupOrContactsUpdated.sink.add(null); return await updateGroup(group); } Future<ContactItemModel> updateContact(ContactItemModel contact) async { assert(contact != null); assert(contact.id != null); assert(contact.id >= 0); var dto = ContactDto( id: contact.id, firstName: contact.firstName, lastName: contact.lastName, phone: contact.phone, company: contact.company, birthday: contact.birthday, imagePath: contact.imagePath ); var db = await _contactsDb.future; await db.update(dto); _groupOrContactsUpdated.sink.add(null); return ContactItemModel.fromDto(dto); } Future<GroupItemModel> updateGroup(GroupItemModel group) async { assert(group != null); assert(group.id != null); assert(group.id >= 0); var groupDb = await _groupsDb.future; var contactDb = await _groupsDb.future; for(var c in group.contacts.where((c) => c.id != null && c.id >= 0)) { c = await updateContact(c); } if(group.contacts.any((c) => c.id == null || c.id <= 0)) { for(var c in group.contacts.where((c) => c.id == null || c.id < 0)) { var dto = await _addContact(c.firstName, c.lastName, c.phone, c.company, c.birthday, c.imagePath, contactDb); c = ContactItemModel.fromDto(dto); } } var groupDto = GroupDto( id: group.id, name: group.name, preferredSendType: group.preferredSendType, contacts: group.contacts.map((c) => c.id).toList(), creationDate: group.creationDate, lastMessageSentDate: group.lastMessageSentDate ); await groupDb.update(groupDto); _groupOrContactsUpdated.sink.add(null); return group; } Future deleteGroup(GroupItemModel group) async { assert(group != null); assert(group.id > 0); var groupDb = await _groupsDb.future; var contactDb = await _contactsDb.future; for(var c in group.contacts) { var otherGroupsWithSameId = await groupDb.query( [QueryPackage( key: "contacts", value: c.id, filter: FilterType.Contains )], (map) => GroupDto.fromMap(map), findFirst: true ); if(otherGroupsWithSameId == null) { await contactDb.deleteFromId(c.id); } } await groupDb.deleteFromId(group.id); _groupOrContactsUpdated.sink.add(null); } Future<GroupItemModel> deleteContact(GroupItemModel group, ContactItemModel contact) async { assert(group != null); assert(group.id > 0); assert(contact != null); assert(contact.id > 0); var contactDb = await _contactsDb.future; if(group.contacts.any((c) => c.id == contact.id)) { await contactDb.deleteFromId(contact.id); group.removeContact(contact); group = await updateGroup(group); if(group != null) { _groupOrContactsUpdated.sink.add(null); return group; } } return group; } Future<GroupDto> _addGroup(DbCollection groupDb, GroupDto dto) async { var id = await groupDb.add(dto); return dto.copyWith(id: id); } Future<ContactDto> _addContact(String firstName, String lastName, String phone, String company, DateTime birthday, String imagePath, DbCollection contactDb) async { var contact = ContactDto( firstName: firstName, lastName: lastName, phone: phone, company: company, birthday: birthday, imagePath: imagePath ); var id = await contactDb.add(contact); contact = ContactDto( id: id, firstName: firstName, lastName: lastName, phone: phone, company: company, birthday: birthday, imagePath: imagePath ); return contact; } Future<GroupItemModel> duplicateGroup(GroupItemModel oldGroup) async { assert(oldGroup != null); assert(oldGroup.id != null); assert(oldGroup.id > 0); var groupDb = await _groupsDb.future; var contactDb = await _contactsDb.future; var missingContacts = oldGroup.contacts.where((c) => c.id <= 0).toList(); var missingContactIds = <int>[]; if(missingContacts.isNotEmpty) { for(var c in missingContacts) { var dto = await _addContact(c.firstName, c.lastName, c.phone, c.company, c.birthday, c.imagePath, contactDb); missingContactIds.add(dto.id); } } var dto = GroupDto( name: "%s (copy)".fill([oldGroup.name]), contacts: oldGroup.contacts.where((c) => c.id != null && c.id > 0).map((c) => c.id).toList() + missingContactIds, preferredSendType: oldGroup.preferredSendType, lastMessageSentDate: oldGroup.lastMessageSentDate, creationDate: DateTime.now() ); dto = await _addGroup(groupDb, dto); var contacts = await contactDb.getMany(dto.contacts, itemCreator: (map) => ContactDto.fromMap(map)); _groupOrContactsUpdated.sink.add(null); return GroupItemModel.fromDTO(dto, contacts); } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/contacts_service.dart
import 'dart:async'; import 'package:contacts_service/contacts_service.dart' as cs; import 'package:flutter/material.dart'; class ContactsService { Completer<Iterable<cs.Contact>> _allContacts = Completer(); ContactsService() { _invalidateCachedContacts(); WidgetsBinding.instance.addObserver( _OnNextResumeLifecyleEventObserver( () async => _invalidateCachedContacts() )); } Future<List<cs.Contact>> getAllContacts() async { var list = await _allContacts.future; return list.toList(); } Future _invalidateCachedContacts() async { if(_allContacts.isCompleted) { _allContacts = Completer(); } var contactList = await cs.ContactsService.getContacts(); _allContacts.complete(contactList); } } class _OnNextResumeLifecyleEventObserver extends WidgetsBindingObserver { final Future Function() onResume; _OnNextResumeLifecyleEventObserver(this.onResume); @override Future<void> didChangeAppLifecycleState(AppLifecycleState state) async { if(state == AppLifecycleState.resumed) { await onResume(); } } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/purchases_service.dart
import 'dart:async'; import 'package:flutter/services.dart'; import 'package:purchases_flutter/purchases_flutter.dart'; import 'package:uuid/uuid.dart'; import 'package:relay/core/app_settings_keys.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/secrets/api_constants.dart'; import 'package:relay/services/analytics_service.dart'; import 'package:relay/services/app_settings_service.dart'; class PurchasesService { final AppSettingsService _appSettings; final AnalyticsService _analyticsService; final String unlimitedGroupsEntitlement = "unlimited groups"; final String unlimitedGroupOffering = "default"; String _userId = ""; Completer _init = Completer(); StreamController<void> _unlimitedGroupsPurchases = StreamController.broadcast(); void dispose() { _unlimitedGroupsPurchases.close(); } PurchasesService._(this._appSettings, this._analyticsService) { _init.complete(_initialize()); } factory PurchasesService([AppSettingsService appSettings, AnalyticsService analyticsService]) => PurchasesService._( appSettings ?? dependencyLocator<AppSettingsService>(), analyticsService ?? dependencyLocator<AnalyticsService>()); Stream<void> get unlimitedGroupsPurchasesStream => _unlimitedGroupsPurchases.stream; Future<bool> hasUnlimitedGroupsEntitlement() async { await _init.future; try { PurchaserInfo purchaserInfo = await Purchases.getPurchaserInfo(); return purchaserInfo.entitlements.all.isNotEmpty && purchaserInfo.entitlements.all.containsKey(unlimitedGroupsEntitlement) && purchaserInfo.entitlements.all[unlimitedGroupsEntitlement].isActive; } on PlatformException catch (e) { _logError(e); return false; } } Future<Offering> getUnlimitedGroupsOfferings() async { await _init.future; try { var offerings = await Purchases.getOfferings(); return offerings.getOffering(unlimitedGroupOffering); } on PlatformException catch (e) { _logError(e); return null; } } Future<bool> purchaseUnlimitedGroupsPackage(Package package) async { await _init.future; try { PurchaserInfo purchaserInfo = await Purchases.purchasePackage(package); if(purchaserInfo.entitlements.all[unlimitedGroupsEntitlement].isActive) { _unlimitedGroupsPurchases.sink.add(null); return true; } } on PlatformException catch (e) { var errorCode = PurchasesErrorHelper.getErrorCode(e); if (errorCode != PurchasesErrorCode.purchaseCancelledError) { _logError(e); } } return false; } void _logError(PlatformException e) { _analyticsService.logException(e); } Future _initialize() async { _userId = await _appSettings.getSettingString(AppSettingsConstants.profile_user_id, Uuid().v1()); Purchases.setDebugLogsEnabled(true); await Purchases.setup(ApiConstants.revenueCatPublicKey, appUserId: _userId); print("purchases init completed"); } Future<bool> restorePurchases() async { await _init.future; try { await Purchases.restoreTransactions(); if(await hasUnlimitedGroupsEntitlement()) { _unlimitedGroupsPurchases.sink.add(null); } return true; } on PlatformException catch (e) { _logError(e); return false; } } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/app_reviews_service.dart
import 'dart:async'; import 'package:app_review/app_review.dart'; import 'package:commons/commons.dart'; import 'package:flutter/widgets.dart'; import 'package:relay/core/app_settings_keys.dart'; import 'package:relay/ioc/dependency_registrar.dart'; import 'package:relay/services/analytics_service.dart'; import 'package:relay/services/app_settings_service.dart'; import 'package:relay/translation/translations.dart'; class AppReviewsService { final String _reviewsShownEvent = "reviews_shown"; final AppSettingsService _appSettings; final AnalyticsService _analyticsService; AppReviewsService._(this._appSettings, this._analyticsService); factory AppReviewsService([AppSettingsService appSettingsService, AnalyticsService analyticsService]) { return AppReviewsService._( appSettingsService ?? dependencyLocator<AppSettingsService>(), analyticsService ?? dependencyLocator<AnalyticsService>() ); } Future<bool> shouldRequestReviews() async { var appOpens = await _appSettings.getSettingInt(AppSettingsConstants.analytics_app_open_count); var messagesSent = await _appSettings.getSettingInt(AppSettingsConstants.analytics_message_count); var didShowReviews = await _appSettings.getSettingBool(AppSettingsConstants.reviews_have_been_shown); if(didShowReviews) { return false; } print("reviews have not been shown."); if(appOpens > 5 && messagesSent > 3) { print ("reviews should show"); return true; } else { return false; } } Future requestReviews(BuildContext context) async { if(await AppReview.isRequestReviewAvailable == false) { Completer<bool> completer = Completer(); infoDialog( context, "Do you want to rate or review Relay on the app store?".i18n, title: "Enjoying Relay?".i18n, showNeutralButton: false, positiveAction: () => completer.complete(true), positiveText: "Review Relay".i18n, negativeAction: () => completer.complete(false), negativeText: "Not Right Now".i18n ); await completer.future; await AppReview.storeListing; } else { await AppReview.requestReview; } _appSettings.setSettingsBool(AppSettingsConstants.reviews_have_been_shown, true); _analyticsService.trackEvent(_reviewsShownEvent); } }
0
mirrored_repositories/RelayApp/lib
mirrored_repositories/RelayApp/lib/services/analytics_service.dart
import 'dart:async'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_analytics/observer.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:purchases_flutter/package_wrapper.dart'; class AnalyticsService { final FirebaseAnalytics _analytics; const AnalyticsService._(this._analytics); factory AnalyticsService() { var analytics = FirebaseAnalytics(); return AnalyticsService._(analytics); } // Track an event with the given [name] and the optional [propeties] Future trackEvent(String name, {Map<String, dynamic> properties}) async { // This is not an assert because we don't want to crash over analytics. if(name == null || name.isEmpty) return; await _analytics.logEvent(name: name,parameters: properties); } RouteObserver getObserver() { return FirebaseAnalyticsObserver(analytics: _analytics); } Future logException(PlatformException e) async { Crashlytics.instance.recordError(e, StackTrace.current); } }
0
mirrored_repositories/DeliasMails
mirrored_repositories/DeliasMails/lib/main.dart
import 'package:flutter/material.dart'; import 'data/dummy_data.dart'; import 'models/meal.dart'; import 'models/settings.dart'; import 'screens/categories_meals_screen.dart'; import 'screens/meal_detail_screen.dart'; import 'screens/settings_screen.dart'; import 'screens/tabs_screen.dart'; import 'utils/app_routes.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { Settings settings = Settings(); List<Meal> _availableMeals = dummyMeals; final List<Meal> _favoriteMeals = []; void _filterMeals(Settings settings) { setState(() { this.settings = settings; _availableMeals = dummyMeals.where((meal) { final filterGluten = settings.isGlutenFree && !meal.isGlutenFree; final filterLactose = settings.isLactoseFree && !meal.isLactoseFree; final filterVegan = settings.isVegan && !meal.isVegan; final filterVegetarian = settings.isVegetarian && !meal.isVegetarian; return !filterGluten && !filterLactose && !filterVegan && !filterVegetarian; }).toList(); }); } void _toggleFavorite(Meal meal) { setState(() { _favoriteMeals.contains(meal) ? _favoriteMeals.remove(meal) : _favoriteMeals.add(meal); }); } bool _isFavorite(Meal meal) { return _favoriteMeals.contains(meal); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Vamos Cozinhar?', theme: ThemeData( colorScheme: ColorScheme.fromSwatch().copyWith( primary: Colors.pink, secondary: Colors.amber, ), canvasColor: const Color.fromRGBO(255, 254, 229, 1), fontFamily: 'Raleway', textTheme: ThemeData.light().textTheme.copyWith( titleLarge: const TextStyle( fontSize: 20, fontFamily: 'RobotoCondensed', ), ), ), routes: { AppRoutes.home: (ctx) => TabsScreen(_favoriteMeals), AppRoutes.categoriesMeals: (ctx) => CategoriesMealsScreen(_availableMeals), AppRoutes.mealDetail: (ctx) => MealDetailScreen(_toggleFavorite, _isFavorite), AppRoutes.settings: (ctx) => SettingsScreen(settings, _filterMeals), }, debugShowCheckedModeBanner: false, ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/components/meal_item.dart
import 'package:flutter/material.dart'; import '../models/meal.dart'; import '../utils/app_routes.dart'; class MealItem extends StatelessWidget { final Meal meal; const MealItem(this.meal, {Key? key}) : super(key: key); void _selectMeal(BuildContext context) { Navigator.of(context) .pushNamed( AppRoutes.mealDetail, arguments: meal, ) .then((result) { if (result == null) { print('Sem resultado!'); } else { print('O nome da refeição é $result.'); } }); } @override Widget build(BuildContext context) { return InkWell( onTap: () => _selectMeal(context), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), elevation: 4, margin: const EdgeInsets.all(10), child: Column( children: [ Stack( children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(15), topRight: Radius.circular(15), ), child: Image.network( meal.imageUrl, height: 250, width: double.infinity, fit: BoxFit.cover, ), ), Positioned( bottom: 20, right: 10, child: Container( width: 300, color: Colors.black54, padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 20, ), child: Text( meal.title, style: const TextStyle( fontSize: 26, color: Colors.white, ), softWrap: true, overflow: TextOverflow.fade, ), ), ), ], ), Padding( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Row( children: [ const Icon(Icons.schedule), const SizedBox(width: 6), Text('${meal.duration} min'), ], ), Row( children: [ const Icon(Icons.work), const SizedBox(width: 6), Text(meal.complexityText), ], ), Row( children: [ const Icon(Icons.attach_money), const SizedBox(width: 6), Text(meal.costText), ], ), ], ), ), ], ), ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/components/main_drawer.dart
import 'package:flutter/material.dart'; import '../utils/app_routes.dart'; class MainDrawer extends StatelessWidget { const MainDrawer({Key? key}) : super(key: key); Widget _createItem(IconData icon, String label, Function() onTap) { return ListTile( leading: Icon( icon, size: 26, ), title: Text( label, style: const TextStyle( fontFamily: 'RobotoCondensed', fontSize: 24, fontWeight: FontWeight.bold, ), ), onTap: onTap, ); } @override Widget build(BuildContext context) { return Drawer( child: Column( children: [ Container( height: 120, width: double.infinity, padding: const EdgeInsets.all(20), color: Theme.of(context).colorScheme.secondary, alignment: Alignment.bottomRight, child: Text( 'Vamos Cozinhar?', style: TextStyle( fontWeight: FontWeight.w900, fontSize: 30, color: Theme.of(context).colorScheme.primary, ), ), ), const SizedBox(height: 20), _createItem( Icons.restaurant, 'Refeições', () => Navigator.of(context).pushReplacementNamed(AppRoutes.home), ), _createItem( Icons.settings, 'Configurações', () => Navigator.of(context).pushReplacementNamed(AppRoutes.settings), ), ], ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/components/category_item.dart
import 'package:flutter/material.dart'; import '../models/category.dart'; import '../utils/app_routes.dart'; class CategoryItem extends StatelessWidget { final Category category; const CategoryItem(this.category, {Key? key}) : super(key: key); void _selectCategory(BuildContext context) { Navigator.of(context).pushNamed( AppRoutes.categoriesMeals, arguments: category, ); } @override Widget build(BuildContext context) { return InkWell( onTap: () => _selectCategory(context), splashColor: Theme.of(context).colorScheme.primary, borderRadius: BorderRadius.circular(15), child: Container( padding: const EdgeInsets.all(15), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), gradient: LinearGradient( colors: [ category.color.withOpacity(0.5), category.color, ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: Text( category.title, style: Theme.of(context).textTheme.headline6, ), ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/models/meal.dart
enum Complexity { simple, medium, difficult, } enum Cost { cheap, fair, expensive, } class Meal { final String id; final List<String> categories; final String title; final String imageUrl; final List<String> ingredients; final List<String> steps; final int duration; final bool isGlutenFree; final bool isLactoseFree; final bool isVegan; final bool isVegetarian; final Complexity complexity; final Cost cost; const Meal({ required this.id, required this.categories, required this.title, required this.imageUrl, required this.ingredients, required this.steps, required this.duration, required this.isGlutenFree, required this.isLactoseFree, required this.isVegan, required this.isVegetarian, required this.complexity, required this.cost, }); String get complexityText { switch (complexity) { case Complexity.simple: return 'Simples'; case Complexity.medium: return 'Normal'; case Complexity.difficult: return 'Difícil'; default: return 'Desconhecida'; } } String get costText { switch (cost) { case Cost.cheap: return 'Barato'; case Cost.fair: return 'Justo'; case Cost.expensive: return 'Caro'; default: return 'Desconhecido'; } } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/models/category.dart
import 'package:flutter/material.dart'; class Category { final String id; final String title; final Color color; const Category({ required this.id, required this.title, this.color = Colors.orange, }); }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/models/settings.dart
class Settings { bool isGlutenFree; bool isLactoseFree; bool isVegan; bool isVegetarian; Settings({ this.isGlutenFree = false, this.isLactoseFree = false, this.isVegan = false, this.isVegetarian = false, }); }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/data/dummy_data.dart
import 'package:flutter/material.dart'; import '../models/category.dart'; import '../models/meal.dart'; const dummyCategories = [ Category( id: 'c1', title: 'Italiano', color: Colors.purple, ), Category( id: 'c2', title: 'Rápido & Fácil', color: Colors.red, ), Category( id: 'c3', title: 'Hamburgers', color: Colors.orange, ), Category( id: 'c4', title: 'Alemã', color: Colors.amber, ), Category( id: 'c5', title: 'Leve & Saudável', color: Colors.indigo, ), Category( id: 'c6', title: 'Exótica', color: Colors.green, ), Category( id: 'c7', title: 'Café da Manhã', color: Colors.lightBlue, ), Category( id: 'c8', title: 'Asiática', color: Colors.lightGreen, ), Category( id: 'c9', title: 'Francesa', color: Colors.pink, ), Category( id: 'c10', title: 'Verão', color: Colors.teal, ), ]; const dummyMeals = [ Meal( id: 'm1', categories: ['c1', 'c2'], title: 'Spaghetti with Tomato Sauce', cost: Cost.cheap, complexity: Complexity.simple, imageUrl: 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg', duration: 20, ingredients: [ '4 Tomatoes', '1 Tablespoon of Olive Oil', '1 Onion', '250g Spaghetti', 'Spices', 'Cheese (optional)' ], steps: [ 'Cut the tomatoes and the onion into small pieces.', 'Boil some water - add salt to it once it boils.', 'Put the spaghetti into the boiling water - they should be done in about 10 to 12 minutes.', 'In the meantime, heaten up some olive oil and add the cut onion.', 'After 2 minutes, add the tomato pieces, salt, pepper and your other spices.', 'The sauce will be done once the spaghetti are.', 'Feel free to add some cheese on top of the finished dish.' ], isGlutenFree: false, isVegan: true, isVegetarian: true, isLactoseFree: true, ), Meal( id: 'm2', categories: ['c2'], title: 'Toast Hawaii', cost: Cost.cheap, complexity: Complexity.simple, imageUrl: 'https://cdn.pixabay.com/photo/2018/07/11/21/51/toast-3532016_1280.jpg', duration: 10, ingredients: [ '1 Slice White Bread', '1 Slice Ham', '1 Slice Pineapple', '1-2 Slices of Cheese', 'Butter' ], steps: [ 'Butter one side of the white bread', 'Layer ham, the pineapple and cheese on the white bread', 'Bake the toast for round about 10 minutes in the oven at 200°C' ], isGlutenFree: false, isVegan: false, isVegetarian: false, isLactoseFree: false, ), Meal( id: 'm3', categories: ['c2', 'c3'], title: 'Classic Hamburger', cost: Cost.fair, complexity: Complexity.simple, imageUrl: 'https://cdn.pixabay.com/photo/2014/10/23/18/05/burger-500054_1280.jpg', duration: 45, ingredients: [ '300g Cattle Hack', '1 Tomato', '1 Cucumber', '1 Onion', 'Ketchup', '2 Burger Buns' ], steps: [ 'Form 2 patties', 'Fry the patties for c. 4 minutes on each side', 'Quickly fry the buns for c. 1 minute on each side', 'Bruch buns with ketchup', 'Serve burger with tomato, cucumber and onion' ], isGlutenFree: false, isVegan: false, isVegetarian: false, isLactoseFree: true, ), Meal( id: 'm4', categories: ['c4'], title: 'Wiener Schnitzel', cost: Cost.expensive, complexity: Complexity.medium, imageUrl: 'https://cdn.pixabay.com/photo/2018/03/31/19/29/schnitzel-3279045_1280.jpg', duration: 60, ingredients: [ '8 Veal Cutlets', '4 Eggs', '200g Bread Crumbs', '100g Flour', '300ml Butter', '100g Vegetable Oil', 'Salt', 'Lemon Slices' ], steps: [ 'Tenderize the veal to about 2–4mm, and salt on both sides.', 'On a flat plate, stir the eggs briefly with a fork.', 'Lightly coat the cutlets in flour then dip into the egg, and finally, coat in breadcrumbs.', 'Heat the butter and oil in a large pan (allow the fat to get very hot) and fry the schnitzels until golden brown on both sides.', 'Make sure to toss the pan regularly so that the schnitzels are surrounded by oil and the crumbing becomes ‘fluffy’.', 'Remove, and drain on kitchen paper. Fry the parsley in the remaining oil and drain.', 'Place the schnitzels on awarmed plate and serve garnishedwith parsley and slices of lemon.' ], isGlutenFree: false, isVegan: false, isVegetarian: false, isLactoseFree: false, ), Meal( id: 'm5', categories: ['c2', 'c5', 'c10'], title: 'Salad with Smoked Salmon', cost: Cost.expensive, complexity: Complexity.simple, imageUrl: 'https://cdn.pixabay.com/photo/2016/10/25/13/29/smoked-salmon-salad-1768890_1280.jpg', duration: 15, ingredients: [ 'Arugula', 'Lamb\'s Lettuce', 'Parsley', 'Fennel', '200g Smoked Salmon', 'Mustard', 'Balsamic Vinegar', 'Olive Oil', 'Salt and Pepper' ], steps: [ 'Wash and cut salad and herbs', 'Dice the salmon', 'Process mustard, vinegar and olive oil into a dessing', 'Prepare the salad', 'Add salmon cubes and dressing' ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: true, ), Meal( id: 'm6', categories: ['c6', 'c10'], title: 'Delicious Orange Mousse', cost: Cost.cheap, complexity: Complexity.difficult, imageUrl: 'https://cdn.pixabay.com/photo/2017/05/01/05/18/pastry-2274750_1280.jpg', duration: 240, ingredients: [ '4 Sheets of Gelatine', '150ml Orange Juice', '80g Sugar', '300g Yoghurt', '200g Cream', 'Orange Peel', ], steps: [ 'Dissolve gelatine in pot', 'Add orange juice and sugar', 'Take pot off the stove', 'Add 2 tablespoons of yoghurt', 'Stir gelatin under remaining yoghurt', 'Cool everything down in the refrigerator', 'Whip the cream and lift it under die orange mass', 'Cool down again for at least 4 hours', 'Serve with orange peel', ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: false, ), Meal( id: 'm7', categories: ['c7'], title: 'Pancakes', cost: Cost.cheap, complexity: Complexity.simple, imageUrl: 'https://cdn.pixabay.com/photo/2018/07/10/21/23/pancake-3529653_1280.jpg', duration: 20, ingredients: [ '1 1/2 Cups all-purpose Flour', '3 1/2 Teaspoons Baking Powder', '1 Teaspoon Salt', '1 Tablespoon White Sugar', '1 1/4 cups Milk', '1 Egg', '3 Tablespoons Butter, melted', ], steps: [ 'In a large bowl, sift together the flour, baking powder, salt and sugar.', 'Make a well in the center and pour in the milk, egg and melted butter; mix until smooth.', 'Heat a lightly oiled griddle or frying pan over medium high heat.', 'Pour or scoop the batter onto the griddle, using approximately 1/4 cup for each pancake. Brown on both sides and serve hot.' ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: false, ), Meal( id: 'm8', categories: ['c8'], title: 'Creamy Indian Chicken Curry', cost: Cost.fair, complexity: Complexity.medium, imageUrl: 'https://cdn.pixabay.com/photo/2018/06/18/16/05/indian-food-3482749_1280.jpg', duration: 35, ingredients: [ '4 Chicken Breasts', '1 Onion', '2 Cloves of Garlic', '1 Piece of Ginger', '4 Tablespoons Almonds', '1 Teaspoon Cayenne Pepper', '500ml Coconut Milk', ], steps: [ 'Slice and fry the chicken breast', 'Process onion, garlic and ginger into paste and sauté everything', 'Add spices and stir fry', 'Add chicken breast + 250ml of water and cook everything for 10 minutes', 'Add coconut milk', 'Serve with rice' ], isGlutenFree: true, isVegan: false, isVegetarian: false, isLactoseFree: true, ), Meal( id: 'm9', categories: ['c9'], title: 'Chocolate Souffle', cost: Cost.cheap, complexity: Complexity.difficult, imageUrl: 'https://cdn.pixabay.com/photo/2014/08/07/21/07/souffle-412785_1280.jpg', duration: 45, ingredients: [ '1 Teaspoon melted Butter', '2 Tablespoons white Sugar', '2 Ounces 70% dark Chocolate, broken into pieces', '1 Tablespoon Butter', '1 Tablespoon all-purpose Flour', '4 1/3 tablespoons cold Milk', '1 Pinch Salt', '1 Pinch Cayenne Pepper', '1 Large Egg Yolk', '2 Large Egg Whites', '1 Pinch Cream of Tartar', '1 Tablespoon white Sugar', ], steps: [ 'Preheat oven to 190°C. Line a rimmed baking sheet with parchment paper.', 'Brush bottom and sides of 2 ramekins lightly with 1 teaspoon melted butter; cover bottom and sides right up to the rim.', 'Add 1 tablespoon white sugar to ramekins. Rotate ramekins until sugar coats all surfaces.', 'Place chocolate pieces in a metal mixing bowl.', 'Place bowl over a pan of about 3 cups hot water over low heat.', 'Melt 1 tablespoon butter in a skillet over medium heat. Sprinkle in flour. Whisk until flour is incorporated into butter and mixture thickens.', 'Whisk in cold milk until mixture becomes smooth and thickens. Transfer mixture to bowl with melted chocolate.', 'Add salt and cayenne pepper. Mix together thoroughly. Add egg yolk and mix to combine.', 'Leave bowl above the hot (not simmering) water to keep chocolate warm while you whip the egg whites.', 'Place 2 egg whites in a mixing bowl; add cream of tartar. Whisk until mixture begins to thicken and a drizzle from the whisk stays on the surface about 1 second before disappearing into the mix.', 'Add 1/3 of sugar and whisk in. Whisk in a bit more sugar about 15 seconds.', 'whisk in the rest of the sugar. Continue whisking until mixture is about as thick as shaving cream and holds soft peaks, 3 to 5 minutes.', 'Transfer a little less than half of egg whites to chocolate.', 'Mix until egg whites are thoroughly incorporated into the chocolate.', 'Add the rest of the egg whites; gently fold into the chocolate with a spatula, lifting from the bottom and folding over.', 'Stop mixing after the egg white disappears. Divide mixture between 2 prepared ramekins. Place ramekins on prepared baking sheet.', 'Bake in preheated oven until scuffles are puffed and have risen above the top of the rims, 12 to 15 minutes.', ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: false, ), Meal( id: 'm10', categories: ['c2', 'c5', 'c10'], title: 'Asparagus Salad with Cherry Tomatoes', cost: Cost.expensive, complexity: Complexity.simple, imageUrl: 'https://cdn.pixabay.com/photo/2018/04/09/18/26/asparagus-3304997_1280.jpg', duration: 30, ingredients: [ 'White and Green Asparagus', '30g Pine Nuts', '300g Cherry Tomatoes', 'Salad', 'Salt, Pepper and Olive Oil' ], steps: [ 'Wash, peel and cut the asparagus', 'Cook in salted water', 'Salt and pepper the asparagus', 'Roast the pine nuts', 'Halve the tomatoes', 'Mix with asparagus, salad and dressing', 'Serve with Baguette' ], isGlutenFree: true, isVegan: true, isVegetarian: true, isLactoseFree: true, ), ];
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screen/categories_meals_screen.dart
// ignore_for_file: use_key_in_widget_constructors, unused_local_variable import 'package:flutter/material.dart'; import 'package:food/components/meal_item.dart'; import 'package:food/models/category.dart'; import 'package:food/models/meal.dart'; class CategoriesMealsScreen extends StatelessWidget { final List<Meal> meals; const CategoriesMealsScreen(this.meals); @override Widget build(BuildContext context) { final category = ModalRoute.of(context)!.settings.arguments as Category; final categoryMeals = meals.where((meal) { return meal.categories.contains(category.id); }).toList(); return Scaffold( appBar: AppBar( title: Center(child: Text(category.title)), ), body: Center( child: ListView.builder( itemCount: categoryMeals.length, itemBuilder: (ctx, index) { return MealItem(categoryMeals[index]); }, ), ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screen/tabs_screen.dart
import 'package:flutter/material.dart'; import 'package:food/components/main_drawer.dart'; import 'package:food/screen/categories_screen.dart'; import 'package:food/screen/favorite_screen.dart'; import '../models/meal.dart'; class TabScreen extends StatefulWidget { List<Meal> favoriteMeals; TabScreen({super.key, required this.favoriteMeals}); @override State<TabScreen> createState() => _TabScreenState(); } class _TabScreenState extends State<TabScreen> { int _selectedScreenIndex = 0; final List<Map<String, Object>> _screens = [ { 'title': 'Lista de Categorias', 'screen': const CategoriesScreen(), }, { 'title': 'Meus Favoritos', 'screen': const FavoriteScreen( favoriteMeals: [], ), }, ]; _selectScreen(int index) { setState(() { _selectedScreenIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Vamos cozinhar?'), ), body: Center( child: _screens[_selectedScreenIndex]['screen'] as Widget, ), drawer: const MainDrawer(), bottomNavigationBar: BottomNavigationBar( onTap: _selectScreen, backgroundColor: Theme.of(context).primaryColor, unselectedItemColor: Colors.white, selectedItemColor: Theme.of(context).colorScheme.secondary, currentIndex: _selectedScreenIndex, items: const [ BottomNavigationBarItem( icon: Icon(Icons.category), label: 'Categorias', ), BottomNavigationBarItem( icon: Icon(Icons.star), label: 'Favoritos', ), ], )); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screen/meal_detail_screen.dart
import 'package:flutter/material.dart'; import '../models/meal.dart'; class MealDetailScreen extends StatelessWidget { const MealDetailScreen({super.key}); @override Widget build(BuildContext context) { final meal = ModalRoute.of(context)?.settings.arguments as Meal; return Scaffold( appBar: AppBar( title: const Text('Detalhes da Refeição'), ), body: ListView( children: <Widget>[ Image.network( meal.imageUrl, width: double.infinity, height: 300, fit: BoxFit.cover, ), const SizedBox(height: 10), Container( margin: const EdgeInsets.symmetric(vertical: 10), child: const Text( 'Ingredientes', style: TextStyle( fontSize: 26, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), ), Container( width: double.infinity, padding: const EdgeInsets.all(10), margin: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10), ), height: 200, child: ListView.builder( itemCount: meal.ingredients.length, itemBuilder: (ctx, index) => Card( color: Theme.of(context).badgeTheme.backgroundColor, child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 10, ), child: Text( meal.ingredients[index], ), ), ), ), ), Container( margin: const EdgeInsets.symmetric(vertical: 10), child: const Text( 'Passos', style: TextStyle( fontSize: 26, fontWeight: FontWeight.bold, ), textAlign: TextAlign.center, ), ), Container( width: double.infinity, padding: const EdgeInsets.all(10), margin: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10), ), height: 200, child: ListView.builder( itemCount: meal.steps.length, itemBuilder: (ctx, index) => Column( children: <Widget>[ ListTile( leading: CircleAvatar( child: Text('${index + 1}'), ), title: Text(meal.steps[index]), ), const Divider(), ], ), ), ), ], ), floatingActionButton: FloatingActionButton( child: const Icon(Icons.star), onPressed: () { Navigator.of(context).pop(meal.title); }, ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screen/categories_screen.dart
import 'package:flutter/material.dart'; import 'package:food/components/category_item.dart'; import 'package:food/data/dummy_data.dart'; class CategoriesScreen extends StatelessWidget { const CategoriesScreen({super.key}); @override Widget build(BuildContext context) { return GridView( gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200, childAspectRatio: 3 / 2, crossAxisSpacing: 20, mainAxisSpacing: 20, ), children: dummyCategories.map((cat) { return CategoryItem(cat); }).toList(), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screen/settings_screen.dart
import 'package:flutter/material.dart'; import '../components/main_drawer.dart'; import '../models/settings.dart'; class SettingsScreen extends StatefulWidget { final Function(Settings) onSettingsChanged; const SettingsScreen(this.onSettingsChanged); @override State<SettingsScreen> createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { // const SettingsScreen({super.key}); late Settings settings; @override void initState() { super.initState(); settings = widget.onSettingsChanged as Settings; } Widget _createSwitch( String title, String subtitle, bool value, void Function(bool) onChanged, ) { return SwitchListTile.adaptive( title: Text(title), subtitle: Text(subtitle), value: value, onChanged: (value) { onChanged(value); widget.onSettingsChanged(settings); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Configurações'), ), drawer: const MainDrawer(), body: Column( children: [ Container( padding: const EdgeInsets.all(20), child: Text( 'Configurações', style: Theme.of(context).textTheme.displayLarge, ), ), Expanded( child: ListView( children: [ _createSwitch( 'Sem Glutén', 'Só exibe refeições sem glutén!', settings.isGlutenFree, (value) => setState(() => settings.isGlutenFree = value), ), _createSwitch( 'Sem Lactose', 'Só exibe refeições sem lactose!', settings.isLactoseFree, (value) => setState(() => settings.isLactoseFree = value), ), _createSwitch( 'Vegana', 'Só exibe refeições veganas!', settings.isVegan, (value) => setState(() => settings.isVegan = value), ), _createSwitch( 'Vegetariana', 'Só exibe refeições vegetarianas!', settings.isVegetarian, (value) => setState(() => settings.isVegetarian = value), ), ], ), ), ], ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screen/favorite_screen.dart
import 'package:flutter/material.dart'; import '../models/meal.dart'; class FavoriteScreen extends StatelessWidget { final List<Meal> favoriteMeals; const FavoriteScreen({super.key, required this.favoriteMeals}); @override Widget build(BuildContext context) { if (favoriteMeals.isEmpty) { return const Center( child: Text('Nenhuma refeição foi marcada como favorita!'), ); } else { return ListView.builder( itemCount: favoriteMeals.length, itemBuilder: (ctx, index) { return Text(favoriteMeals[index].title); }, ); } } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/utils/app_routes.dart
class AppRoutes { static const home = '/'; static const categoriesMeals = '/categories-meals'; static const mealDetail = '/meal-detail'; static const settings = '/settings'; }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screens/categories_meals_screen.dart
import 'package:flutter/material.dart'; import '../components/meal_item.dart'; import '../models/category.dart'; import '../models/meal.dart'; class CategoriesMealsScreen extends StatelessWidget { final List<Meal> meals; const CategoriesMealsScreen(this.meals, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { final category = ModalRoute.of(context)!.settings.arguments as Category; final categoryMeals = meals.where((meal) { return meal.categories.contains(category.id); }).toList(); return Scaffold( appBar: AppBar( title: Text(category.title), ), body: ListView.builder( itemCount: categoryMeals.length, itemBuilder: (ctx, index) { return MealItem(categoryMeals[index]); }, ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screens/tabs_screen.dart
import 'package:flutter/material.dart'; import 'categories_screen.dart'; import 'favorite_screen.dart'; import '../components/main_drawer.dart'; import '../models/meal.dart'; class TabsScreen extends StatefulWidget { final List<Meal> favoriteMeals; const TabsScreen(this.favoriteMeals, {Key? key}) : super(key: key); @override State<TabsScreen> createState() => _TabsScreenState(); } class _TabsScreenState extends State<TabsScreen> { int _selectedScreenIndex = 0; List<Map<String, Object>>? _screens; @override void initState() { super.initState(); _screens = [ { 'title': 'Lista de Categorias', 'screen': const CategoriesScreen(), }, { 'title': 'Meus Favoritos', 'screen': FavoriteScreen(widget.favoriteMeals), }, ]; } _selectScreen(int index) { setState(() { _selectedScreenIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( _screens![_selectedScreenIndex]['title'] as String, ), ), drawer: const MainDrawer(), body: _screens![_selectedScreenIndex]['screen'] as Widget, bottomNavigationBar: BottomNavigationBar( onTap: _selectScreen, backgroundColor: Theme.of(context).colorScheme.primary, unselectedItemColor: Colors.white, selectedItemColor: Theme.of(context).colorScheme.secondary, currentIndex: _selectedScreenIndex, items: const [ BottomNavigationBarItem( icon: Icon(Icons.category), label: 'Categorias', ), BottomNavigationBarItem( icon: Icon(Icons.star), label: 'Favoritos', ), ], ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screens/meal_detail_screen.dart
import 'package:flutter/material.dart'; import '../models/meal.dart'; class MealDetailScreen extends StatelessWidget { final Function(Meal) onToggleFavorite; final bool Function(Meal) isFavorite; const MealDetailScreen(this.onToggleFavorite, this.isFavorite, {Key? key}) : super(key: key); Widget _createSectionTitle(BuildContext context, String title) { return Container( margin: const EdgeInsets.symmetric(vertical: 10), child: Text( title, style: Theme.of(context).textTheme.headline6, ), ); } Widget _createSectionContainer(Widget child) { return Container( width: 330, height: 200, padding: const EdgeInsets.all(10), margin: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10), ), child: child, ); } @override Widget build(BuildContext context) { final meal = ModalRoute.of(context)!.settings.arguments as Meal; return Scaffold( appBar: AppBar( title: Text(meal.title), ), body: SingleChildScrollView( child: Column( children: [ SizedBox( height: 300, width: double.infinity, child: Image.network( meal.imageUrl, fit: BoxFit.cover, ), ), _createSectionTitle(context, 'Ingredientes'), _createSectionContainer( ListView.builder( itemCount: meal.ingredients.length, itemBuilder: (ctx, index) { return Card( color: Theme.of(context).colorScheme.secondary, child: Padding( padding: const EdgeInsets.symmetric( vertical: 5, horizontal: 10, ), child: Text(meal.ingredients[index]), ), ); }, ), ), _createSectionTitle(context, 'Passos'), _createSectionContainer(ListView.builder( itemCount: meal.steps.length, itemBuilder: (ctx, index) { return Column( children: [ ListTile( leading: CircleAvatar( backgroundColor: Theme.of(context).colorScheme.primary, child: Text( '${index + 1}', style: const TextStyle(color: Colors.white), ), ), title: Text(meal.steps[index]), ), const Divider(), ], ); }, )), ], ), ), floatingActionButton: FloatingActionButton( child: Icon(isFavorite(meal) ? Icons.star : Icons.star_border), onPressed: () { onToggleFavorite(meal); }, ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screens/categories_screen.dart
import 'package:flutter/material.dart'; import '../components/category_item.dart'; import '../data/dummy_data.dart'; class CategoriesScreen extends StatelessWidget { const CategoriesScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return GridView( padding: const EdgeInsets.all(25), gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200, childAspectRatio: 3 / 2, crossAxisSpacing: 20, mainAxisSpacing: 20, ), children: dummyCategories.map((cat) { return CategoryItem(cat); }).toList(), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screens/settings_screen.dart
import 'package:flutter/material.dart'; import '../components/main_drawer.dart'; import '../models/settings.dart'; class SettingsScreen extends StatefulWidget { final Settings settings; final Function(Settings) onSettingsChanged; const SettingsScreen(this.settings, this.onSettingsChanged, {Key? key}) : super(key: key); @override State<SettingsScreen> createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { Settings? settings; @override void initState() { super.initState(); settings = widget.settings; } Widget _createSwitch( String title, String subtitle, bool value, Function(bool) onChanged, ) { return SwitchListTile.adaptive( title: Text(title), subtitle: Text(subtitle), value: value, onChanged: (value) { onChanged(value); widget.onSettingsChanged(settings!); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Configurações'), ), drawer: const MainDrawer(), body: Column( children: [ Container( padding: const EdgeInsets.all(20), child: Text( 'Configurações', style: Theme.of(context).textTheme.headline6, ), ), Expanded( child: ListView( children: [ _createSwitch( 'Sem Glutén', 'Só exibe refeições sem glúten!', settings!.isGlutenFree, (value) => setState(() => settings!.isGlutenFree = value), ), _createSwitch( 'Sem Lactose', 'Só exibe refeições sem lactose!', settings!.isLactoseFree, (value) => setState(() => settings!.isLactoseFree = value), ), _createSwitch( 'Vegana', 'Só exibe refeições veganas!', settings!.isVegan, (value) => setState(() => settings!.isVegan = value), ), _createSwitch( 'Vegetariana', 'Só exibe refeições vegetarianas!', settings!.isVegetarian, (value) => setState(() => settings!.isVegetarian = value), ), ], ), ) ], ), ); } }
0
mirrored_repositories/DeliasMails/lib
mirrored_repositories/DeliasMails/lib/screens/favorite_screen.dart
import 'package:flutter/material.dart'; import '../components/meal_item.dart'; import '../models/meal.dart'; class FavoriteScreen extends StatelessWidget { final List<Meal> favoriteMeals; const FavoriteScreen(this.favoriteMeals, {Key? key}) : super(key: key); @override Widget build(BuildContext context) { if (favoriteMeals.isEmpty) { return const Center( child: Text('Nenhuma refeição foi marcada como favoritas'), ); } else { return ListView.builder( itemCount: favoriteMeals.length, itemBuilder: (ctx, index) { return MealItem(favoriteMeals[index]); }, ); } } }
0
mirrored_repositories/Blockconnect
mirrored_repositories/Blockconnect/lib/metamask_home.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:metamask_connect/utils.dart'; import 'package:metamask_connect/utils/utils.dart'; import 'package:metamask_connect/w3m_service.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import 'package:web3modal_flutter/web3modal_flutter.dart'; import 'models/coindata.dart'; import 'utils/custom_double_extension.dart'; class MetamaskHomeScreen extends StatefulWidget { const MetamaskHomeScreen({super.key}); @override State<MetamaskHomeScreen> createState() => _MetamaskHomeScreenState(); } class _MetamaskHomeScreenState extends State<MetamaskHomeScreen> { late W3mConnector w3mCtrl = W3mConnector(waletBalanceFetch); String signHash = ""; String txnHash = ""; CoinData? coinData; final RefreshController _refreshController = RefreshController(initialRefresh: false); void waletBalanceFetch(CoinData val) { print("updating "); setState(() { coinData = val; }); } @override void initState() { super.initState(); w3mCtrl.init(); w3mCtrl.initService(connectListener); } @override void dispose() { super.dispose(); w3mCtrl.closeService(connectListener); } void connectListener() { setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: const Text("Blockconnect"), ), body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 12), child: SmartRefresher( controller: _refreshController, onRefresh: () async { w3mCtrl.getWalletBalance(); await Future.delayed(const Duration(seconds: 1)); _refreshController.refreshCompleted(); }, child: Column( children: <Widget>[ const SizedBox(height: 8), ...[ W3MConnectWalletButton(service: w3mCtrl.service), const SizedBox(height: 10), Visibility( visible: coinData?.remainingAmount != null && w3mCtrl.service.isConnected, child: Text( "Wallet balance - ${coinData?.remainingAmount} ", style: const TextStyle(fontSize: 18), ), ), ], const Spacer(), if (w3mCtrl.service.isConnected) ...[ ElevatedButton( onPressed: () { getMessageDialog(); }, child: const Text("Sign Message"), ), const SizedBox(height: 8), Visibility( visible: signHash.isNotEmpty, child: Text("Sign hash is $signHash")), const SizedBox(height: 8), ElevatedButton( // onPressed: genTxnHash, onPressed: () async { if (coinData == null) { await w3mCtrl.getWalletBalance(); } showTransactionDialog(); }, child: const Text("Transact"), ), const SizedBox(height: 8), Visibility( visible: txnHash.isNotEmpty, child: Text("transaction hash is $txnHash")), ], ], ), ), ), ), ); } void showTransactionDialog() { print("gas fee ${coinData?.gasFee?.toStringAsFixed(18)}"); TextEditingController amountCtrl = TextEditingController(); TextEditingController addressCtrl = TextEditingController( text: "0x8491C4546977f98F01e7629Dd234882c17d1C86E"); showDialog( context: context, builder: (ctx) => AlertDialog( title: const Text("Transaction Details"), content: Column( mainAxisSize: MainAxisSize.min, children: [ Text("Wallet Balance - ${coinData?.remainingAmount}"), const SizedBox(height: 30), SizedBox( height: 50, child: TextField( controller: addressCtrl, decoration: const InputDecoration( labelText: "Address", isDense: true, suffixIcon: Icon(Icons.qr_code), contentPadding: EdgeInsets.zero, ), ), ), const SizedBox(height: 20), SizedBox( height: 30, child: TextField( controller: amountCtrl, inputFormatters: [FilteringTextInputFormatter.digitsOnly], decoration: InputDecoration( isDense: true, suffixIcon: GestureDetector( onTap: () { if (coinData != null) { if (coinData!.remainingAmount != null && coinData!.gasFee != null) { final minAmount = coinData!.gasFee?.toDouble() ?? 0; if (coinData!.remainingAmount! > minAmount) { amountCtrl.text = (coinData!.remainingAmount! - minAmount) .reduceByPercent(percent: 0.5) .toString(); } } } }, child: Text( "Max", style: TextStyle(color: Theme.of(context).primaryColor), ), ), contentPadding: EdgeInsets.zero), ), ), const SizedBox(height: 15), if (coinData != null) if (coinData!.gasFee != null) Text( "Gas Fee - ${(coinData!.gasFee! * pow(10, 18)).toInt()} Wei") ], ), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(ctx).pop(); }, child: const Text("Cancel"), ), TextButton( onPressed: () { createTxn( toAddress: addressCtrl.text, amount: double.parse(amountCtrl.text)); Navigator.of(ctx).pop(); }, child: const Text("Pay"), ), ], ), ); } void getMessageDialog() { TextEditingController signMessageCtrl = TextEditingController(text: ""); showDialog( context: context, builder: (ctx) => AlertDialog( title: const Text("Enter Message"), content: Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 30), SizedBox( height: 50, child: TextField( controller: signMessageCtrl, decoration: const InputDecoration( labelText: "Message", isDense: true, suffixIcon: Icon(Icons.qr_code), contentPadding: EdgeInsets.zero, ), ), ), const SizedBox(height: 20), ], ), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(ctx).pop(); }, child: const Text("Cancel"), ), TextButton( onPressed: () { if(signMessageCtrl.text.isEmpty) { Utils.showToast(message: "Message cannot be empty.") ; } else { genSignedMsg(message: signMessageCtrl.text); } Navigator.of(ctx).pop(); }, child: const Text("Sign"), ), ], ), ); } void createTxn({required String toAddress, required double amount}) async { final val = await w3mCtrl.createTransaction( toAddress: toAddress, tokenAmount: amount); if (val != null) { setState(() { txnHash = val; }); } } void genSignedMsg({required String message}) async { final val = await w3mCtrl.onPersonalSign(message: message); if (val != null) { setState(() { signHash = val; }); } } }
0
mirrored_repositories/Blockconnect
mirrored_repositories/Blockconnect/lib/w3m_service.dart
import 'dart:math'; import 'package:http/http.dart'; //You can also import the browser version import 'package:flutter/cupertino.dart'; import 'package:metamask_connect/utils.dart'; import 'package:web3modal_flutter/web3modal_flutter.dart'; import 'models/coindata.dart'; class W3mConnector { late W3MService _w3mService; void Function(CoinData coinData) onWalletBalanceFetch; W3mConnector(this.onWalletBalanceFetch); W3MService get service => _w3mService; late final W3MChainInfo _sepoliaChain = W3MChainInfo( chainName: 'Sepolia', namespace: 'eip155:${BlockchainUtils.sepoliaChainId}', chainId: BlockchainUtils.sepoliaChainId, tokenName: 'ETH', rpcUrl: 'https://rpc.sepolia.org/', blockExplorer: W3MBlockExplorer( name: 'Sepolia Explorer', url: 'https://sepolia.etherscan.io/', ), ); initService(VoidCallback func) { _w3mService.addListener(func); } closeService(VoidCallback func) { _w3mService.removeListener(func); } Future<String?> createTransaction( {required String toAddress, required double tokenAmount}) async { double val = tokenAmount * pow(10, 18).toDouble(); final finalAmt = val.toInt().toRadixString(16); debugPrint("amount ${val.toInt().toRadixString(16)}"); await _w3mService.launchConnectedWallet(); var hash = await _w3mService.web3App?.request( topic: _w3mService.session!.topic!, chainId: 'eip155:${BlockchainUtils.sepoliaChainId}', request: SessionRequestParams( method: 'eth_sendTransaction', params: [ { "from": _w3mService.session?.address, "to": toAddress, "data": "0x", "value": finalAmt, } ], ), ); getWalletBalance(); return hash; } Future getWalletBalance() async { if (_w3mService.session?.address == null) { return; } var apiUrl = "https://rpc.sepolia.org/"; var httpClient = Client(); var ethClient = Web3Client(apiUrl, httpClient); EtherAmount balance = await ethClient.getBalance(EthereumAddress.fromHex( _w3mService.session!.address!, enforceEip55: true)); print("${balance.getValueInUnit(EtherUnit.ether)}"); final gasFee = (await ethClient.estimateGas()) / BigInt.from(10).pow(18); onWalletBalanceFetch(CoinData( remainingAmount: balance.getValueInUnit(EtherUnit.ether), gasFee: gasFee)); return; } Future<String?> onPersonalSign({required String message}) async { await _w3mService.launchConnectedWallet(); var hash = await _w3mService.web3App?.request( topic: _w3mService.session!.topic!, chainId: 'eip155:${BlockchainUtils.sepoliaChainId}', request: SessionRequestParams( method: 'personal_sign', params: [message, _w3mService.session?.address], ), ); getWalletBalance(); return hash; } void init() async { W3MChainPresets.chains .putIfAbsent(BlockchainUtils.sepoliaChainId, () => _sepoliaChain); _w3mService = W3MService( projectId: '91fea5ea39fc5898af040c6fd6c478c2', metadata: const PairingMetadata( name: 'Blockchain on Flutter', description: 'Blockchain Demo', url: 'https://www.walletconnect.com/', icons: ['https://walletconnect.com/walletconnect-logo.png'], redirect: Redirect( native: 'flutterdapp://', universal: 'https://www.walletconnect.com', ), ), featuredWalletIds: {BlockchainUtils.metamaskId}, ); await _w3mService.init(); getWalletBalance(); } disconnect() { _w3mService.disconnect(); } }
0
mirrored_repositories/Blockconnect
mirrored_repositories/Blockconnect/lib/utils.dart
class BlockchainUtils { static const String sepoliaChainId = "11155111"; static const String metamaskId = "'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96'"; }
0
mirrored_repositories/Blockconnect
mirrored_repositories/Blockconnect/lib/main.dart
import 'package:flutter/material.dart'; import 'metamask_home.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MetamaskHomeScreen(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // TRY THIS: Try changing the color here to a specific color (to // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar // change color while the other colors stay the same. backgroundColor: Theme.of(context).colorScheme.inversePrimary, // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). // // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" // action in the IDE, or press "p" in the console), to see the // wireframe for each widget. mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
0
mirrored_repositories/Blockconnect/lib
mirrored_repositories/Blockconnect/lib/models/coindata.dart
class CoinData { double? remainingAmount; double? gasFee; CoinData({ this.remainingAmount, this.gasFee, }); }
0
mirrored_repositories/Blockconnect/lib
mirrored_repositories/Blockconnect/lib/utils/custom_double_extension.dart
extension DoubleExt on double { double reduceByPercent({double percent = 1}) { final reducedVal = this*(100 - percent)/100; return reducedVal; } }
0
mirrored_repositories/Blockconnect/lib
mirrored_repositories/Blockconnect/lib/utils/utils.dart
import 'package:fluttertoast/fluttertoast.dart'; class Utils { static showToast({required String message}) { Fluttertoast.showToast(msg: message); } }
0
mirrored_repositories/Blockconnect
mirrored_repositories/Blockconnect/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 in the flutter_test package. 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:metamask_connect/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/chat_story_flutter/storyapp
mirrored_repositories/chat_story_flutter/storyapp/lib/main.dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
0
mirrored_repositories/chat_story_flutter/storyapp
mirrored_repositories/chat_story_flutter/storyapp/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:storyapp/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/websocket
mirrored_repositories/websocket/lib/main.dart
import 'package:flutter/material.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter WebSocket Task'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final channel = WebSocketChannel.connect( Uri.parse('wss://echo.websocket.org'), ); @override void dispose() { channel.sink.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ StreamBuilder( stream: channel.stream, builder: (context, snapshot) { return Text(snapshot.hasData ? '${snapshot.data}' : ''); }, ) ], ), ), floatingActionButton: FloatingActionButton( onPressed: _webSocketConnection, tooltip: 'WebSocket Connection', child: Icon(Icons.add), ), ); } void _webSocketConnection() { print('sending...'); channel.sink.add('Hi. This is Muhammad Shoaib'); print('message'); } }
0
mirrored_repositories/websocket
mirrored_repositories/websocket/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:websocket/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/Flutter-navigation-2
mirrored_repositories/Flutter-navigation-2/lib/DUMMY.dart
const List<Map<String, dynamic>> DUMMY = [ {'title': 'Apple', 'caption': 'The biggest green apple ever'}, {'title': 'Orange', 'caption': 'An awesome orange'}, {'title': 'Banana', 'caption': 'Something long and strange'}, {'title': 'Car', 'caption': 'wtf?'}, ];
0
mirrored_repositories/Flutter-navigation-2
mirrored_repositories/Flutter-navigation-2/lib/main.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_navigation_2/routes/router_parser.dart'; import 'package:flutter_navigation_2/routes/router_delegator.dart'; void main() { if (kIsWeb) setUrlStrategy(PathUrlStrategy()); runApp( /// Init Riverpod's providers /// https://riverpod.dev/docs/concepts/providers#creating-a-provider const ProviderScope( child: MyApp(), ), ); } class MyApp extends ConsumerWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { return MaterialApp.router( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), routerDelegate: AppRouteDelegator(ref), routeInformationParser: AppRouterInformationParser(), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/widgets/loading.dart
import 'package:flutter/material.dart'; class AppLoading extends StatelessWidget { final String text; const AppLoading({Key? key, required this.text}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text(text), const CircularProgressIndicator(), ], ), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/routes/router_parser.dart
import 'package:flutter/material.dart'; import 'package:flutter_navigation_2/routes/router_states.dart'; /// Parses the current location after that RouterDelegate changing the app state /// /// If you are going to build only mobile app (without Web app) it's not necessary to build it class AppRouterInformationParser extends RouteInformationParser<AppRouteState> { /// Convert current url to navigation state @override Future<AppRouteState> parseRouteInformation(RouteInformation routeInformation) async { final Uri uri = Uri.parse(routeInformation.location!); if (uri.pathSegments.length == 2 && uri.pathSegments[0] == 'item') { return ItemDetailRouteState(title: uri.pathSegments[1]); } return const HomeAppRouteState(); } /// Convert current navigation state to url @override RouteInformation restoreRouteInformation(AppRouteState state) { return RouteInformation(location: state.location); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/routes/router_delegator.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter_navigation_2/providers/ItemProvider.dart'; import 'package:flutter_navigation_2/routes/pages/InitialPage.dart'; import 'package:flutter_navigation_2/routes/pages/MainPage.dart'; import 'package:flutter_navigation_2/routes/pages/OptionDetailsPage.dart'; import 'package:flutter_navigation_2/routes/router_states.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; /// App router delegator /// Build Navigator according the app state and handling the pop requests class AppRouteDelegator extends RouterDelegate<AppRouteState> with ChangeNotifier, PopNavigatorRouterDelegateMixin<AppRouteState> { final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>(); final WidgetRef ref; @override GlobalKey<NavigatorState> get navigatorKey => _navigatorKey; /// Determinate if the app is ready to use bool _isInit = false; AppRouteDelegator(this.ref) { _initApp(); } String? get selectedItemTitle => ref.watch(itemProvider).selectedItem?.title; /// Emulate getting data from the remote API or local storage /// /// For example, You can use this method to check the authentication status Future<void> _initApp() async { if (_isInit) return; /// Random delay await Future.delayed(const Duration(milliseconds: 300)); _isInit = true; notifyListeners(); } @override Widget build(BuildContext context) { return Navigator( key: navigatorKey, /// pages stack, shows the last page in this stack pages: [ const MainPage(), if (!_isInit) const InitialPage(), if (selectedItemTitle != null) const OptionDetailsPage(), ], onPopPage: (route, result) { if (!route.didPop(result)) return false; return true; }, ); } @override AppRouteState get currentConfiguration { if (selectedItemTitle != null) { return ItemDetailRouteState(title: selectedItemTitle!); } else { return const HomeAppRouteState(); } } /// For example this method can be used to check access to pages (guards) @override Future<void> setNewRoutePath(AppRouteState configuration) async { final _itemProvider = ref.watch(itemProvider); if (configuration is ItemDetailRouteState) { _itemProvider.selectedTitle = configuration.title; } else { _itemProvider.selectedTitle = null; } } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/routes/router_states.dart
/// Represents current app route state abstract class AppRouteState { const AppRouteState(); String get location; } /// State for home page class HomeAppRouteState extends AppRouteState { const HomeAppRouteState(); @override String get location => '/'; } /// State for item's details page class ItemDetailRouteState extends AppRouteState { final String title; const ItemDetailRouteState({ required this.title, }); @override String get location => '/item/${title.toLowerCase()}'; }
0
mirrored_repositories/Flutter-navigation-2/lib/routes
mirrored_repositories/Flutter-navigation-2/lib/routes/pages/MainPage.dart
import 'package:flutter/material.dart'; import 'package:flutter_navigation_2/screens/MainScreen.dart'; class MainPage extends Page { const MainPage(); @override Route createRoute(BuildContext context) { return MaterialPageRoute( settings: this, builder: (BuildContext context) => const MainScreen(), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib/routes
mirrored_repositories/Flutter-navigation-2/lib/routes/pages/OptionDetailsPage.dart
import 'package:flutter/material.dart'; import 'package:flutter_navigation_2/screens/OptionDetailsScreen.dart'; class OptionDetailsPage extends Page { const OptionDetailsPage(); @override Route createRoute(BuildContext context) { return MaterialPageRoute( settings: this, builder: (BuildContext context) => const OptionDetailsScreen(), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib/routes
mirrored_repositories/Flutter-navigation-2/lib/routes/pages/InitialPage.dart
import 'package:flutter/material.dart'; import 'package:flutter_navigation_2/screens/InitialScreen.dart'; /// Sample of initial page, shows initial screen class InitialPage extends Page { const InitialPage(); @override Route createRoute(BuildContext context) { return MaterialPageRoute( settings: this, builder: (BuildContext context) => const InitialScreen(), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/models/ItemModel.dart
import 'package:flutter_navigation_2/models/BaseModel.dart'; class ItemModel extends BaseModel { final String title; final String caption; const ItemModel({required this.title, required this.caption}); ItemModel.fromJson(Map<String, dynamic> json) : title = json['title'], caption = json['caption']; }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/models/BaseModel.dart
class BaseModel { const BaseModel(); @override String toString() { // TODO: print all properties of the class return 'Instance of ${this.runtimeType}'; } }
0
mirrored_repositories/Flutter-navigation-2/lib/repositories
mirrored_repositories/Flutter-navigation-2/lib/repositories/main/ItemRepoFake.dart
import 'package:flutter_navigation_2/models/ItemModel.dart'; import 'package:flutter_navigation_2/repositories/main/ItemRepoContract.dart'; import 'package:flutter_navigation_2/DUMMY.dart'; class ItemRepoFake implements ItemRepoContract { @override Future<List<ItemModel>> loadItems() async { await Future.delayed(const Duration(seconds: 2)); return DUMMY.map((item) => ItemModel.fromJson(item)).toList(); } }
0
mirrored_repositories/Flutter-navigation-2/lib/repositories
mirrored_repositories/Flutter-navigation-2/lib/repositories/main/ItemRepoContract.dart
import 'package:flutter_navigation_2/models/ItemModel.dart'; abstract class ItemRepoContract { /// Load all items Future<List<ItemModel>> loadItems(); }
0
mirrored_repositories/Flutter-navigation-2/lib/utils
mirrored_repositories/Flutter-navigation-2/lib/utils/enums/loading_status.dart
enum LoadingStatus { init, loading, loaded, networkError }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/screens/InitialScreen.dart
import 'package:flutter/material.dart'; class InitialScreen extends StatelessWidget { const InitialScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ CircularProgressIndicator.adaptive(), Text('data preparing...'), ], ), ), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/screens/OptionDetailsScreen.dart
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_navigation_2/models/ItemModel.dart'; import 'package:flutter_navigation_2/providers/ItemProvider.dart'; class OptionDetailsScreen extends StatelessWidget { const OptionDetailsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer( builder: (BuildContext context, WidgetRef ref, _) { final ItemModel _item = ref.read(itemProvider).selectedItem!; return Scaffold( appBar: AppBar( title: Text("Let's talk about ${_item.title}"), ), body: Center( child: Text(_item.caption), ), ); }, ); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/screens/MainScreen.dart
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_navigation_2/models/ItemModel.dart'; import 'package:flutter_navigation_2/providers/ItemProvider.dart'; import 'package:flutter_navigation_2/widgets/loading.dart'; class MainScreen extends StatelessWidget { const MainScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Main screen"), elevation: 0, ), body: Padding( padding: const EdgeInsets.all(4.0), child: Consumer( builder: (BuildContext context, WidgetRef ref, _) { final ItemNotifier _itemProvider = ref.watch(itemProvider); if (_itemProvider.isLoading) return const AppLoading(text: "items loading"); final List<ItemModel> _items = _itemProvider.items; return GridView.count( crossAxisCount: 4, children: [ ..._items .map((option) => _OptionWidget( title: option.title, )) .toList(), ], ); }, ), ), ); } } class _OptionWidget extends StatelessWidget { final String title; const _OptionWidget({ Key? key, required this.title, }) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Container( color: Colors.blue, child: Consumer( builder: (ctx, ref, child) { final _itemProvider = ref.read(itemProvider); return InkWell( onTap: () { _itemProvider.selectedTitle = title; }, child: child, ); }, child: Center( child: Text( title, style: const TextStyle( color: Colors.white, ), ), ), ), ), ); } }
0
mirrored_repositories/Flutter-navigation-2/lib
mirrored_repositories/Flutter-navigation-2/lib/providers/ItemProvider.dart
import 'package:flutter/foundation.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:flutter_navigation_2/repositories/main/ItemRepoContract.dart'; import 'package:flutter_navigation_2/repositories/main/ItemRepoFake.dart'; import 'package:flutter_navigation_2/models/ItemModel.dart'; import 'package:flutter_navigation_2/utils/enums/loading_status.dart'; final itemProvider = ChangeNotifierProvider<ItemNotifier>((ref) => ItemNotifier()); class ItemNotifier with ChangeNotifier { LoadingStatus _loadingStatus = LoadingStatus.init; final ItemRepoContract itemRepo; List<ItemModel> _items = []; String? _selectedTitle; ItemNotifier() : itemRepo = ItemRepoFake() { if (_loadingStatus == LoadingStatus.init) { _loadItems(); } } ItemModel? get selectedItem { if(_selectedTitle == null || _items.isEmpty) return null; final List<ItemModel> _item = _items.where((element) => element.title.toLowerCase() == _selectedTitle!.toLowerCase()).toList(); if(_items.isEmpty) return null; return _item.first; } bool get isLoading => _loadingStatus == LoadingStatus.loading; List<ItemModel> get items => [..._items]; set loadingStatus(LoadingStatus newStatus) { _loadingStatus = newStatus; notifyListeners(); } set selectedTitle(String? title){ _selectedTitle = title; notifyListeners(); } Future<void> _loadItems() async { loadingStatus = LoadingStatus.loading; _items = [...await itemRepo.loadItems()]; loadingStatus = LoadingStatus.loaded; } }
0
mirrored_repositories/Flutter-navigation-2
mirrored_repositories/Flutter-navigation-2/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:flutter_navigation_2/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/world_clock_app
mirrored_repositories/world_clock_app/lib/main.dart
import 'package:flutter/material.dart'; import 'package:world_clock_app/screens/loading.dart'; import 'package:world_clock_app/screens/timezones.dart'; import 'screens/home.dart'; void main() => runApp(MaterialApp( initialRoute: Loading.routeName, routes: { Loading.routeName: (context) => Loading(), TimeZonesSelector.routeName: (context) => TimeZonesSelector(), Home.routeName: (context) => Home(), }, ));
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/views/timezone_List_view.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:world_clock_app/models/timezone.dart'; import '../db/app_db.dart'; import 'cards.dart'; class TimeZonesList extends StatefulWidget { List<TimeZone> selectedTimeZones = []; List<String> allTimeZones = []; final String _base_url = 'http://worldtimeapi.org/api/timezone/'; TimeZonesList({this.selectedTimeZones, this.allTimeZones}); @override _TimeZonesListState createState() => _TimeZonesListState(); } class _TimeZonesListState extends State<TimeZonesList> { AppDatabase database; initDB() async { database = await $FloorAppDatabase.databaseBuilder(AppDatabase.DB_NAME).build(); } @override void initState() { super.initState(); initDB(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(5.0), child: Column( children: <Widget>[ Expanded( child: ListView( children: widget.selectedTimeZones .map((timezone) => ClockCard( timezone: timezone, delete: () { database.timezoneDao .deleteTimeZone(timezone.timezone); // .then((val) { // if (val == 1) setState(() { widget.selectedTimeZones.remove(timezone); }); // }); }, )) .toList(), ), ), FloatingActionButton( child: Icon(Icons.add), backgroundColor: Colors.black, onPressed: () async { final index = await Navigator.pushNamed( context, "/timezone_selector", arguments: {"timezones": widget.allTimeZones}); if (index != null) { Response response = await get( '${widget._base_url}/${widget.allTimeZones[index]}'); Map _json = json.decode(response.body); TimeZone timeZone = TimeZone.fromJson(_json); if (!widget.selectedTimeZones.contains(timeZone)) { setState(() { widget.selectedTimeZones.add(timeZone); }); database.timezoneDao.insertTimeZone(timeZone); print('record inserted'); } } }, ) ], ), ); } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/views/clock_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_analog_clock/flutter_analog_clock.dart'; import 'package:intl/intl.dart'; class ClockView extends StatefulWidget { Function addTimeZone; ClockView({this.addTimeZone}); @override _ClockViewState createState() => _ClockViewState(); } class _ClockViewState extends State<ClockView> { DateTime date; @override Widget build(BuildContext context) { date = DateTime.now(); return Center( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(10.0), child: FlutterAnalogClock( dateTime: DateTime.now(), dialPlateColor: Colors.white, hourHandColor: Colors.black, minuteHandColor: Colors.black, secondHandColor: Colors.black, numberColor: Colors.black, borderColor: Colors.black, tickColor: Colors.black, centerPointColor: Colors.black, showBorder: true, showTicks: true, showMinuteHand: true, showSecondHand: true, showNumber: true, borderWidth: 8.0, hourNumberScale: .10, hourNumbers: [ 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII' ], isLive: true, width: 200.0, height: 200.0, decoration: const BoxDecoration(), ), ), SizedBox( height: 20, ), Text( ' ${DateFormat('EEEE').format(date)}, ${date.day} ${DateFormat('MMM').format(date)}', textAlign: TextAlign.center, style: TextStyle(fontSize: 20), ), SizedBox( height: 50, ), FlatButton.icon( onPressed: () { widget.addTimeZone(); }, icon: Icon(Icons.airplanemode_active), label: Text('Add Time Zone')), ], ), ); } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/views/cards.dart
import 'package:flutter/material.dart'; import 'package:flutter_analog_clock/flutter_analog_clock.dart'; import 'package:intl/intl.dart'; import 'package:world_clock_app/models/timezone.dart'; class ClockCard extends StatefulWidget { TimeZone timezone; Function delete; ClockCard({this.timezone, this.delete}); @override _ClockCardState createState() => _ClockCardState(); } class _ClockCardState extends State<ClockCard> { DateTime date; @override Widget build(BuildContext context) { date = DateTime.parse(widget.timezone.datetime); date = date.add( Duration(hours: int.parse(widget.timezone.utcOffset.substring(1, 3)))); return Card( child: Row( children: <Widget>[ FlutterAnalogClock( dateTime: date, dialPlateColor: Colors.white, hourHandColor: Colors.black, minuteHandColor: Colors.black, secondHandColor: Colors.black, numberColor: Colors.black, borderColor: Colors.black, tickColor: Colors.black, centerPointColor: Colors.black, showBorder: true, showTicks: true, showMinuteHand: true, showSecondHand: true, showNumber: true, borderWidth: 5.0, hourNumberScale: .05, hourNumbers: [ 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X', 'XI', 'XII' ], isLive: true, width: 100.0, height: 100.0, decoration: const BoxDecoration(), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text( '${widget.timezone.timezone}', textAlign: TextAlign.end, style: TextStyle(fontSize: 20), ), SizedBox( height: 10, ), Text( '${DateFormat('EEEE').format(date)}, ${date.day} ${DateFormat('MMM').format(date)}', textAlign: TextAlign.right, ), SizedBox( height: 20, ), FlatButton.icon( onPressed: () => widget.delete(), icon: Icon(Icons.delete), label: Text('')) ], ), ) ], ), elevation: 2, ); } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/db/app_db.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'app_db.dart'; // ************************************************************************** // FloorGenerator // ************************************************************************** class $FloorAppDatabase { /// Creates a database builder for a persistent database. /// Once a database is built, you should keep a reference to it and re-use it. static _$AppDatabaseBuilder databaseBuilder(String name) => _$AppDatabaseBuilder(name); /// Creates a database builder for an in memory database. /// Information stored in an in memory database disappears when the process is killed. /// Once a database is built, you should keep a reference to it and re-use it. static _$AppDatabaseBuilder inMemoryDatabaseBuilder() => _$AppDatabaseBuilder(null); } class _$AppDatabaseBuilder { _$AppDatabaseBuilder(this.name); final String name; final List<Migration> _migrations = []; Callback _callback; /// Adds migrations to the builder. _$AppDatabaseBuilder addMigrations(List<Migration> migrations) { _migrations.addAll(migrations); return this; } /// Adds a database [Callback] to the builder. _$AppDatabaseBuilder addCallback(Callback callback) { _callback = callback; return this; } /// Creates the database and initializes it. Future<AppDatabase> build() async { final database = _$AppDatabase(); database.database = await database.open( name ?? ':memory:', _migrations, _callback, ); return database; } } class _$AppDatabase extends AppDatabase { _$AppDatabase([StreamController<String> listener]) { changeListener = listener ?? StreamController<String>.broadcast(); } TimeZoneDao _timezoneDaoInstance; Future<sqflite.Database> open(String name, List<Migration> migrations, [Callback callback]) async { final path = join(await sqflite.getDatabasesPath(), name); return sqflite.openDatabase( path, version: 1, onConfigure: (database) async { await database.execute('PRAGMA foreign_keys = ON'); }, onOpen: (database) async { await callback?.onOpen?.call(database); }, onUpgrade: (database, startVersion, endVersion) async { MigrationAdapter.runMigrations( database, startVersion, endVersion, migrations); await callback?.onUpgrade?.call(database, startVersion, endVersion); }, onCreate: (database, version) async { await database.execute( 'CREATE TABLE IF NOT EXISTS `TimeZone` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `weekNumber` INTEGER, `utcOffset` TEXT, `utcDatetime` TEXT, `unixtime` INTEGER, `timezone` TEXT, `rawOffset` INTEGER, `dstOffset` INTEGER, `dst` INTEGER, `dayOfYear` INTEGER, `dayOfWeek` INTEGER, `datetime` TEXT, `clientIp` TEXT, `abbreviation` TEXT)'); await callback?.onCreate?.call(database, version); }, ); } @override TimeZoneDao get timezoneDao { return _timezoneDaoInstance ??= _$TimeZoneDao(database, changeListener); } } class _$TimeZoneDao extends TimeZoneDao { _$TimeZoneDao(this.database, this.changeListener) : _queryAdapter = QueryAdapter(database), _timeZoneInsertionAdapter = InsertionAdapter( database, 'TimeZone', (TimeZone item) => <String, dynamic>{ 'id': item.id, 'weekNumber': item.weekNumber, 'utcOffset': item.utcOffset, 'utcDatetime': item.utcDatetime, 'unixtime': item.unixtime, 'timezone': item.timezone, 'rawOffset': item.rawOffset, 'dstOffset': item.dstOffset, 'dst': item.dst ? 1 : 0, 'dayOfYear': item.dayOfYear, 'dayOfWeek': item.dayOfWeek, 'datetime': item.datetime, 'clientIp': item.clientIp, 'abbreviation': item.abbreviation }); final sqflite.DatabaseExecutor database; final StreamController<String> changeListener; final QueryAdapter _queryAdapter; static final _timeZoneMapper = (Map<String, dynamic> row) => TimeZone( id: row['id'] as int, weekNumber: row['weekNumber'] as int, utcOffset: row['utcOffset'] as String, utcDatetime: row['utcDatetime'] as String, unixtime: row['unixtime'] as int, timezone: row['timezone'] as String, rawOffset: row['rawOffset'] as int, dstOffset: row['dstOffset'] as int, dst: (row['dst'] as int) != 0, dayOfYear: row['dayOfYear'] as int, dayOfWeek: row['dayOfWeek'] as int, datetime: row['datetime'] as String, clientIp: row['clientIp'] as String, abbreviation: row['abbreviation'] as String); final InsertionAdapter<TimeZone> _timeZoneInsertionAdapter; @override Future<List<TimeZone>> findAllTimeZones() async { return _queryAdapter.queryList('SELECT * FROM TimeZone', mapper: _timeZoneMapper); } @override Future<void> deleteTimeZone(String timezone) async { await _queryAdapter.queryNoReturn('DELETE FROM TimeZone where timezone = ?', arguments: <dynamic>[timezone]); } @override Future<void> insertTimeZone(TimeZone timeZone) async { await _timeZoneInsertionAdapter.insert( timeZone, sqflite.ConflictAlgorithm.abort); } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/db/app_db.dart
import 'dart:async'; import 'package:floor/floor.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart' as sqflite; import 'package:world_clock_app/db/dao.dart'; import 'package:world_clock_app/models/timezone.dart'; part 'app_db.g.dart'; @Database(version: 1, entities: [TimeZone]) abstract class AppDatabase extends FloorDatabase { static const String DB_NAME = 'app_database.db'; TimeZoneDao get timezoneDao; } /* * static final _timeZoneMapper = (Map<String, dynamic> row) => TimeZone( weekNumber: row['weekNumber'] as int, abbreviation: row['abbreviation'] as String, clientIp: row['clientIp'] as String, datetime: row['datetime'] as String, dayOfWeek: row['dayOfWeek'] as int, dayOfYear: row['dayOfYear'] as int, dst: (row['dst'] as int) != 0, dstOffset: row['dstOffset'] as int, rawOffset: row['rawOffset'] as int, timezone: row['timezone'] as String, unixtime: row['unixtime'] as int, utcOffset: row['utcOffset'] as String, utcDatetime: row['utcDatetime'] as String);*/
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/db/dao.dart
import 'package:floor/floor.dart'; import 'package:world_clock_app/models/timezone.dart'; @dao abstract class TimeZoneDao { @Query('SELECT * FROM TimeZone') Future<List<TimeZone>> findAllTimeZones(); @insert Future<void> insertTimeZone(TimeZone timeZone); @Query('DELETE FROM TimeZone where timezone = :timezone') Future<void> deleteTimeZone(String timezone); }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/models/timezone.dart
import 'package:floor/floor.dart'; @entity class TimeZone { @PrimaryKey(autoGenerate: true) int id; int weekNumber; String utcOffset; String utcDatetime; int unixtime; // @primaryKey String timezone; int rawOffset; // Null dstUntil; int dstOffset; // Null dstFrom; bool dst; int dayOfYear; int dayOfWeek; String datetime; String clientIp; String abbreviation; TimeZone({this.id, this.weekNumber, this.utcOffset, this.utcDatetime, this.unixtime, this.timezone, this.rawOffset, // this.dstUntil, this.dstOffset, // this.dstFrom, this.dst, this.dayOfYear, this.dayOfWeek, this.datetime, this.clientIp, this.abbreviation}); @override bool operator ==(Object other) => identical(this, other) || other is TimeZone && timezone == other.timezone; @override int get hashCode => id.hashCode ^ weekNumber.hashCode ^ utcOffset.hashCode ^ utcDatetime.hashCode ^ unixtime.hashCode ^ timezone.hashCode ^ rawOffset.hashCode ^ dstOffset.hashCode ^ dst.hashCode ^ dayOfYear.hashCode ^ dayOfWeek.hashCode ^ datetime.hashCode ^ clientIp.hashCode ^ abbreviation.hashCode; TimeZone.fromJson(Map<String, dynamic> json) { weekNumber = json['week_number']; utcOffset = json['utc_offset']; utcDatetime = json['utc_datetime']; unixtime = json['unixtime']; timezone = json['timezone']; rawOffset = json['raw_offset']; // dstUntil = json['dst_until']; dstOffset = json['dst_offset']; // dstFrom = json['dst_from']; dst = json['dst']; dayOfYear = json['day_of_year']; dayOfWeek = json['day_of_week']; datetime = json['datetime']; clientIp = json['client_ip']; abbreviation = json['abbreviation']; } @override String toString() { return 'TimeZone{id: $id, weekNumber: $weekNumber, utcOffset: $utcOffset, utcDatetime: $utcDatetime, unixtime: $unixtime, timezone: $timezone, rawOffset: $rawOffset, dstOffset: $dstOffset, dst: $dst, dayOfYear: $dayOfYear, dayOfWeek: $dayOfWeek, datetime: $datetime, clientIp: $clientIp, abbreviation: $abbreviation}'; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['week_number'] = this.weekNumber; data['utc_offset'] = this.utcOffset; data['utc_datetime'] = this.utcDatetime; data['unixtime'] = this.unixtime; data['timezone'] = this.timezone; data['raw_offset'] = this.rawOffset; // data['dst_until'] = this.dstUntil; data['dst_offset'] = this.dstOffset; // data['dst_from'] = this.dstFrom; data['dst'] = this.dst; data['day_of_year'] = this.dayOfYear; data['day_of_week'] = this.dayOfWeek; data['datetime'] = this.datetime; data['client_ip'] = this.clientIp; data['abbreviation'] = this.abbreviation; return data; } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/screens/loading.dart
import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:http/http.dart'; import 'package:world_clock_app/models/timezone.dart'; import '../db/app_db.dart'; import 'home.dart'; class Loading extends StatefulWidget { static const routeName = '/loading'; @override _LoadingState createState() => _LoadingState(); } class _LoadingState extends State<Loading> { List<String> timeZones = []; loadTimeZones() async { Response response = await get('http://worldtimeapi.org/api/timezone.txt'); timeZones = response.body.split('\n'); // load saved timezones final database = await $FloorAppDatabase.databaseBuilder(AppDatabase.DB_NAME).build(); List<TimeZone> _selectedTimeZones = await database.timezoneDao.findAllTimeZones(); _selectedTimeZones.forEach((val) { print(val); }); Navigator.pushReplacementNamed(context, Home.routeName, arguments: { "timezones": timeZones, "selectedTimeZones": _selectedTimeZones }); } @override void initState() { super.initState(); loadTimeZones(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SpinKitRotatingPlain( color: Colors.black, size: 80.0, ), )); } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/screens/home.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:world_clock_app/models/timezone.dart'; import 'package:world_clock_app/views/clock_view.dart'; import 'package:world_clock_app/views/timezone_List_view.dart'; class Home extends StatefulWidget { static const routeName = '/home'; @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { DateTime date; int _currentIndex; List<String> _allTimeZones = []; List<TimeZone> _selectedTimeZones = []; List<Widget> _selectableViews = []; @override void initState() { super.initState(); _currentIndex = 0; } void onTabTapped(int index) { setState(() { _currentIndex = index; }); } @override Widget build(BuildContext context) { date = DateTime.now(); Map arguments = ModalRoute.of(context).settings.arguments; _allTimeZones = arguments['timezones']; _selectedTimeZones = arguments['selectedTimeZones']; _selectableViews.add(ClockView( addTimeZone: () { setState(() { _currentIndex = 1; }); }, )); _selectableViews.add(TimeZonesList( selectedTimeZones: _selectedTimeZones, allTimeZones: _allTimeZones, )); return Scaffold( bottomNavigationBar: BottomNavigationBar( onTap: onTabTapped, // new currentIndex: _currentIndex, items: [ new BottomNavigationBarItem( icon: Icon(Icons.timer), title: Text('Clock'), ), new BottomNavigationBarItem( icon: Icon(Icons.list), title: Text('List'), ), ], ), body: SafeArea( child: _selectableViews[_currentIndex], ), ); } }
0
mirrored_repositories/world_clock_app/lib
mirrored_repositories/world_clock_app/lib/screens/timezones.dart
import 'package:flutter/material.dart'; class TimeZonesSelector extends StatelessWidget { static const routeName = '/timezone_selector'; @override Widget build(BuildContext context) { Map arguments = ModalRoute.of(context).settings.arguments; List<String> timezones = arguments["timezones"]; return Scaffold( body: SafeArea( child: ListView( children: List.generate(timezones.length, (int index) { return ListTile( title: Text(timezones[index]), onTap: () => Navigator.pop(context, index), ); }), ), ), ); } }
0
mirrored_repositories/Flutter-RecipeApplication
mirrored_repositories/Flutter-RecipeApplication/lib/main.dart
import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_firebase_get/auth/login_screen.dart'; import 'package:flutter_firebase_get/auth/registration_screen.dart'; import 'package:flutter_firebase_get/screens/categories_full.dart'; import 'package:flutter_firebase_get/screens/welcome_screen.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, routes: {"mainPage": (context) => CategoriesFull()}, theme: ThemeData( primarySwatch: Colors.orange, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: Anasayfa(), ); } } class Anasayfa extends StatefulWidget { @override _AnasayfaState createState() => _AnasayfaState(); } class _AnasayfaState extends State<Anasayfa> { var refKategoriler = FirebaseDatabase.instance.reference().child("Kategori"); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, initialRoute: WelcomeScreen.id, routes: { WelcomeScreen.id: (context) => WelcomeScreen(), LoginScreen.id: (context) => LoginScreen(), RegistrationScreen.id: (context) => RegistrationScreen(), }, ); } } /* Scaffold( appBar: AppBar( title: Center(child: Text("Kategoriler")), ), body: CategoriesPage(refKategoriler: refKategoriler), );*/
0
mirrored_repositories/Flutter-RecipeApplication/lib
mirrored_repositories/Flutter-RecipeApplication/lib/widgets/background_image.dart
import 'package:flutter/material.dart'; class backgroundimage extends StatelessWidget { const backgroundimage({ Key key, @required this.screenSize, }) : super(key: key); final Size screenSize; @override Widget build(BuildContext context) { return Opacity( opacity: 0.6, child: Container( width: screenSize.width, height: screenSize.height, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('images/arkaplan2.jpeg'), fit: BoxFit.cover, ), ), ), ); } }
0
mirrored_repositories/Flutter-RecipeApplication/lib
mirrored_repositories/Flutter-RecipeApplication/lib/widgets/rounded_button.dart
import 'package:flutter/material.dart'; class RoundedButton extends StatelessWidget { RoundedButton({this.title, this.colour, this.onPressed}); final Color colour; final String title; final Function onPressed; @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(vertical: 16.0), child: Material( elevation: 5.0, color: colour, borderRadius: BorderRadius.circular(30.0), child: MaterialButton( onPressed: onPressed, minWidth: 200.0, height: 42.0, child: Text( title, ), ), ), ); } }
0
mirrored_repositories/Flutter-RecipeApplication/lib
mirrored_repositories/Flutter-RecipeApplication/lib/widgets/categorycardwidget.dart
import 'package:flutter/material.dart'; import 'package:flutter_firebase_get/model/Kategoriler.dart'; class CategoryCard extends StatelessWidget { const CategoryCard({ Key key, @required this.kategori, }) : super(key: key); final Kategori kategori; @override Widget build(BuildContext context) { return Card( // // color: Colors.blueGrey, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(0.0), child: Image.network( // "https://cdn.ntvspor.net/5a28979268064f76a8cef3c21f0d3860.jpg?&mode=crop&w=940&h=626.6666666666666", "https://www.bestepebloggers.com/wp-content/uploads/2021/04/healthy-lifestyle-1024x576-1.jpg", height: 130.0, width: 200.0, ), ), Text( kategori.kategori_ad, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), ], ), ); } }
0
mirrored_repositories/Flutter-RecipeApplication/lib
mirrored_repositories/Flutter-RecipeApplication/lib/widgets/constants.dart
import 'package:flutter/material.dart'; const kTextFieldDecoration = InputDecoration( hintText: 'Enter a value', labelStyle: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), hintStyle: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), contentPadding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 15.0), border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular(32.0), ), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.orange, width: 1.0), borderRadius: BorderRadius.all(Radius.circular(32.0)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.orange, width: 2.0), borderRadius: BorderRadius.all(Radius.circular(32.0)), ), );
0
mirrored_repositories/Flutter-RecipeApplication/lib
mirrored_repositories/Flutter-RecipeApplication/lib/widgets/yemekcardwidget.dart
import 'package:flutter/material.dart'; import 'package:flutter_firebase_get/model/yemek.dart'; class YemekCardWidget extends StatelessWidget { const YemekCardWidget({Key key, @required this.yemek, this.screenSize}) : super(key: key); final Yemekler yemek; final Size screenSize; @override Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(40.0), child: Container( child: Stack( children: [ // Resim Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( yemek.resim, ), fit: BoxFit.cover, ), ), ), // ********************** Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.end, children: [ Container( height: 20, color: Colors.grey.withOpacity(0.3), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.end, children: [ Center( child: Text( yemek.Yemek_adi, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), ), ], ), ), ], ) ], )), ); } } /* Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(0.0), child: Image.network( yemek.resim, height: 120.0, width: 200.0, filterQuality: FilterQuality.high, ), ), SizedBox( height: 1, ), Text( yemek.Yemek_adi, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), ], ), */
0
mirrored_repositories/Flutter-RecipeApplication/lib
mirrored_repositories/Flutter-RecipeApplication/lib/model/google_sign.dart
import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; Future<UserCredential> signInGoogle() async { await Firebase.initializeApp(); final GoogleSignInAccount user = await GoogleSignIn().signIn(); final GoogleSignInAuthentication auth = await user.authentication; final GoogleAuthCredential credential = GoogleAuthProvider.credential( accessToken: auth.accessToken, idToken: auth.idToken, ); return await FirebaseAuth.instance.signInWithCredential(credential); }
0