repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/party_flutter
mirrored_repositories/party_flutter/lib/main.dart
import 'package:firebase_analytics/observer.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter/services.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:screen/screen.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'localizations.dart'; import 'ui/theme.dart'; import 'ui/shared/widgets.dart'; import 'ui/screens/category_detail.dart'; import 'ui/screens/game_play.dart'; import 'ui/screens/game_summary.dart'; import 'ui/screens/game_gallery.dart'; import 'ui/screens/settings.dart'; import 'ui/screens/tutorial.dart'; import 'ui/screens/home.dart'; import 'ui/screens/contributors.dart'; import 'services/analytics.dart'; import 'services/language.dart'; import 'services/ads.dart'; import 'services/crashlytics.dart'; import 'services/notifications.dart'; import 'repository/category.dart'; import 'repository/question.dart'; import 'repository/language.dart'; import 'repository/settings.dart'; import 'repository/tutorial.dart'; import 'repository/contributor.dart'; import 'store/store.dart'; import 'store/category.dart'; import 'store/question.dart'; import 'store/tutorial.dart'; import 'store/settings.dart'; import 'store/language.dart'; import 'store/gallery.dart'; import 'store/contributor.dart'; class App extends StatelessWidget { final Map<Type, StoreModel> stores = {}; @override Widget build(BuildContext context) { Screen.keepOn(true); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); return FutureBuilder<SharedPreferences>( future: SharedPreferences.getInstance(), builder: ( BuildContext context, AsyncSnapshot<SharedPreferences> snapshot, ) { if (snapshot.data == null) { return ScreenLoader(); } return buildStore(context, snapshot.data); }, ); } Widget buildStore(BuildContext context, SharedPreferences storage) { if (stores.isEmpty) { stores.addAll({ CategoryModel: CategoryModel(CategoryRepository(storage: storage)), QuestionModel: QuestionModel(QuestionRepository()), TutorialModel: TutorialModel(TutorialRepository(storage: storage)), SettingsModel: SettingsModel(SettingsRepository(storage: storage)), LanguageModel: LanguageModel(LanguageRepository(storage: storage)), GalleryModel: GalleryModel(), ContributorModel: ContributorModel(ContributorRepository()), }); stores.values.forEach((store) => store.initialize()); } return ScopedModel<CategoryModel>( model: stores[CategoryModel], child: ScopedModel<QuestionModel>( model: stores[QuestionModel], child: ScopedModel<TutorialModel>( model: stores[TutorialModel], child: ScopedModel<SettingsModel>( model: stores[SettingsModel], child: ScopedModel<LanguageModel>( model: stores[LanguageModel], child: ScopedModel<GalleryModel>( model: stores[GalleryModel], child: ScopedModel<ContributorModel>( model: stores[ContributorModel], child: buildApp(context), ), ), ), ), ), ), ); } Widget buildApp(BuildContext context) { return ScopedModelDescendant<LanguageModel>( builder: (context, child, model) { if (model.isLoading) { return ScreenLoader(); } bool languageSet = model.language != null; if (languageSet) { CategoryModel.of(context).load(model.language); QuestionModel.of(context).load(model.language); } return MaterialApp( title: 'Zgadula', localeResolutionCallback: (locale, locales) { if (!languageSet) { model.changeLanguage(locale.languageCode); } return locale; }, localizationsDelegates: [ SettingsLocalizationsDelegate( languageSet ? Locale(model.language, '') : null, ), AppLocalizationsDelegate(), GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: LanguageService.getCodes().map((code) => Locale(code, '')), theme: createTheme(context), home: HomeScreen(), routes: { '/category': (context) => CategoryDetailScreen(), '/game-play': (context) => GamePlayScreen(), '/game-summary': (context) => GameSummaryScreen(), '/game-gallery': (context) => GameGalleryScreen(), '/settings': (context) => SettingsScreen(), '/tutorial': (context) => TutorialScreen(), '/contributors': (context) => ContributorsScreen(), }, navigatorObservers: [ FirebaseAnalyticsObserver(analytics: AnalyticsService.analytics), ], ); }, ); } } void main() { AdsService.initialize(); CrashlyticsService.initialize(); NotificationsService.initialize(); runApp(App()); }
0
mirrored_repositories/party_flutter
mirrored_repositories/party_flutter/lib/localizations.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:zgadula/services/language.dart'; import 'l10n/messages_all.dart' show initializeMessages; class AppLocalizations { static Future<AppLocalizations> load(Locale locale) { final String name = locale.countryCode.isEmpty ? locale.languageCode : locale.toString(); final String localeName = Intl.canonicalizedLocale(name); return initializeMessages(localeName).then((_) { Intl.defaultLocale = localeName; return AppLocalizations(); }); } static AppLocalizations of(BuildContext context) { return Localizations.of<AppLocalizations>(context, AppLocalizations); } String get tutorialSkip { return Intl.message( 'Play', name: 'tutorialSkip', desc: 'Button which skips the tutorial and takes the player to the game', ); } String get tutorialFirstSectionHeader { return Intl.message( 'Friends', name: 'tutorialFirstSectionHeader', desc: 'Header for the first tutorial section', ); } String get tutorialFirstSectionDescription { return Intl.message( 'Gather a groups of friends and sit together. Youngest player starts.', name: 'tutorialFirstSectionDescription', desc: 'Description for the first tutorial section', ); } String get tutorialSecondSectionHeader { return Intl.message( 'Category', name: 'tutorialSecondSectionHeader', desc: 'Header for the second tutorial section', ); } String get tutorialSecondSectionDescription { return Intl.message( 'Select the category and place the phone on forehead. Guess the word with friends help.', name: 'tutorialSecondSectionDescription', desc: 'Description for the second tutorial section', ); } String get tutorialThirdSectionHeader { return Intl.message( 'Tips', name: 'tutorialThirdSectionHeader', desc: 'Header for the third tutorial section', ); } String get tutorialThirdSectionDescription { return Intl.message( 'Decide on what kind of tips would you use during the round - speak, show, draw or even hum.', name: 'tutorialThirdSectionDescription', desc: 'Description for the third tutorial section', ); } String get tutorialFourthSectionHeader { return Intl.message( 'Fun!', name: 'tutorialFourthSectionHeader', desc: 'Header for the fourth tutorial section', ); } String get tutorialFourthSectionDescription { return Intl.message( 'Tap the screen for next question. Good luck!', name: 'tutorialFourthSectionDescription', desc: 'Description for the fourth tutorial section', ); } String get preparationPlay { return Intl.message( 'Play', name: 'preparationPlay', desc: 'Button which confirms the selected category and starts the main game', ); } String get preparationOrientationDescription { return Intl.message( 'Place the phone on forehead', name: 'preparationOrientationDescription', desc: 'Message which reminds player to put the phone in landscape orientation before game starts', ); } String get gameCancelConfirmation { return Intl.message( 'Do you want to cancel the current game?', name: 'gameCancelConfirmation', desc: 'Description of the dialog which is presented to the player when he tries to quit the game loop', ); } String get gameCancelApprove { return Intl.message( 'OK', name: 'gameCancelApprove', desc: 'Text for approving the decision to cancel current game.', ); } String get gameCancelDeny { return Intl.message( 'Cancel', name: 'gameCancelDeny', desc: 'Text for canceling the decision to cancel current game.', ); } String get lastQuestion { return Intl.message( 'Last Question', name: 'lastQuestion', desc: 'Text shown before presenting last question during the game', ); } String get summaryHeader { return Intl.message( 'Your score', name: 'summaryHeader', desc: 'Header displayed at the top of summary screen, informing player about current score', ); } String get summaryBack { return Intl.message( 'Play again', name: 'summaryBack', desc: 'Button which takes the player from summary screen to category listing', ); } String get settingsHeader { return Intl.message( 'Settings', name: 'settingsHeader', desc: 'Header displayed at the top of settings screen', ); } String get settingsCamera { return Intl.message( 'Camera', name: 'settingsCamera', desc: 'Label for toggling camera support', ); } String get settingsCameraHint { return Intl.message( 'Take temporary photos during game', name: 'settingsCameraHint', desc: 'Hint for toggling camera support', ); } String get settingsSpeech { return Intl.message( 'Microphone', name: 'settingsSpeech', desc: 'Label for toggling speech recognition support', ); } String get settingsSpeechHint { return Intl.message( 'Recognize answers automatically during game', name: 'settingsSpeechHint', desc: 'Hint for toggling speech recognition support', ); } String get settingsAccelerometer { return Intl.message( 'Accelerometer', name: 'settingsAccelerometer', desc: 'Label for toggling accelerometer support', ); } String get settingsAccelerometerHint { return Intl.message( 'Tilt the phone down if you guess the word correctly', name: 'settingsAccelerometerHint', desc: 'Hint for toggling accelerometer support', ); } String get settingsAudio { return Intl.message( 'Audio', name: 'settingsAudio', desc: 'Label for toggling audio support', ); } String get settingsLanguage { return Intl.message( 'Language', name: 'settingsLanguage', desc: 'Label for changing game language', ); } String get settingsPrivacyPolicy { return Intl.message( 'Privacy policy', name: 'settingsPrivacyPolicy', desc: 'Label for opening privacy policy', ); } String get settingsStartTutorial { return Intl.message( 'How to play?', name: 'settingsStartTutorial', desc: 'Label for opening tutorial', ); } String get gameTime { return Intl.message( 'Game time', name: 'gameTime', desc: 'Label for game time slider', ); } String categoryItemQuestionsCount(int count) { return Intl.message( "$count items", name: "categoryItemQuestionsCount", args: [count], desc: "Metadata showing total count of questions in category", ); } String get emptyFavorites { return Intl.message( 'Add favorite categories to find them quicker', name: 'emptyFavorites', desc: 'Hint shown when there are no favorites defined', ); } } class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> { const AppLocalizationsDelegate(); @override bool isSupported(Locale locale) => LanguageService.getCodes().contains(locale.languageCode); @override Future<AppLocalizations> load(Locale locale) => AppLocalizations.load(locale); @override bool shouldReload(AppLocalizationsDelegate old) => false; } class SettingsLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> { final Locale overriddenLocale; const SettingsLocalizationsDelegate(this.overriddenLocale); @override bool isSupported(Locale locale) => overriddenLocale != null; @override Future<AppLocalizations> load(Locale locale) => AppLocalizations.load(overriddenLocale); @override bool shouldReload(SettingsLocalizationsDelegate old) => true; }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/repository/language.dart
import 'dart:core'; import 'package:meta/meta.dart'; import 'package:shared_preferences/shared_preferences.dart'; class LanguageRepository { static const String storageLanguageKey = 'language'; final SharedPreferences storage; LanguageRepository({@required this.storage}); String getLanguage() { return storage.getString(storageLanguageKey); } String setLanguage(String language) { storage.setString(storageLanguageKey, language); return language; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/repository/question.dart
import 'dart:core'; import 'dart:convert'; import 'package:flutter/services.dart' show rootBundle; import 'package:zgadula/models/question.dart'; class QuestionRepository { Future<Map<String, List<Question>>> getAll(String languageCode) async { languageCode = languageCode.toLowerCase(); List<dynamic> categoryList = json.decode(await rootBundle .loadString('assets/data/categories_$languageCode.json')); Map<String, List<Question>> questions = {}; for (Map<String, dynamic> categoryMap in categoryList) { questions[categoryMap['id']] = List.from(categoryMap['questions'] .map((name) => Question(name, categoryMap['name']))); } return questions; } _getRandomQuestions(List<Question> questions, int limit, {List<Question> excluded = const []}) { var allowedQuestions = questions.where((q) => !excluded.contains(q)).toList(); allowedQuestions.shuffle(); allowedQuestions = allowedQuestions.sublist(0, limit); return allowedQuestions; } List<Question> getRandomMixUp( Map<String, List<Question>> questions, int limit, ) { var keys = questions.keys.where((q) => q != 'mixup').toList(); keys.shuffle(); keys = keys.sublist(0, 3); List<Question> result = List.from( keys .map((k) => _getRandomQuestions(questions[k], (limit ~/ 3) + 1)) .expand((i) => i), ); return _getRandomQuestions(result, limit); } List<Question> getRandom( Map<String, List<Question>> questions, String categoryId, int limit, {List<Question> excluded = const []}) { if (categoryId == 'mixup') { return getRandomMixUp(questions, limit); } return _getRandomQuestions( questions[categoryId], limit, excluded: excluded, ); } Question getNext(List<Question> questions, Question current) { int nextIndex = questions.indexOf(current) + 1; if (nextIndex == questions.length) { return null; } return questions[nextIndex]; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/repository/category.dart
import 'dart:core'; import 'dart:convert'; import 'package:meta/meta.dart'; import 'package:flutter/services.dart' show rootBundle; import 'package:shared_preferences/shared_preferences.dart'; import 'package:zgadula/models/category.dart'; class CategoryRepository { static const String storageCategoryPlayedCountKey = 'category_played_count'; static const String storageFavoriteListKey = 'category_favorite_list'; final SharedPreferences storage; CategoryRepository({@required this.storage}); Future<List<Category>> getAll(String languageCode) async { languageCode = languageCode.toLowerCase(); List<dynamic> categoryList = json.decode(await rootBundle .loadString('assets/data/categories_$languageCode.json')); List<Category> categories = []; for (Map<String, dynamic> categoryMap in categoryList) { categories.add(Category.fromJson(categoryMap)); } return categories; } List<String> toggleFavorite(List<String> favourites, Category selected) { if (favourites.contains(selected.id)) { favourites.remove(selected.id); } else { favourites.add(selected.id); } storage.setStringList(storageFavoriteListKey, favourites); return favourites; } List<String> getFavorites() { return storage.getStringList(storageFavoriteListKey) ?? []; } String _playedCountStorageKey(Category category) { return 'storageCategoryPlayedCountKey_${category.id}'; } int getPlayedCount(Category category) { return storage.getInt(_playedCountStorageKey(category)) ?? 0; } int increasePlayedCount(Category category) { var gamesPlayed = getPlayedCount(category) + 1; storage.setInt(_playedCountStorageKey(category), gamesPlayed); return gamesPlayed; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/repository/contributor.dart
import 'dart:core'; import 'dart:convert'; import 'package:flutter/services.dart' show rootBundle; import 'package:zgadula/models/contributor.dart'; class ContributorRepository { Future<List<Contributor>> getAll() async { List<dynamic> contributorsJson = json .decode(await rootBundle.loadString('assets/data/contributors.json')); List<Contributor> contributors = contributorsJson.map((data) { return Contributor(data['name'], data['username']); }).toList(); return contributors; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/repository/settings.dart
import 'dart:core'; import 'package:meta/meta.dart'; import 'package:package_info/package_info.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SettingsRepository { static const String storageAudioEnabledKey = 'is_audio_enabled'; static const String storageRotationControlEnabledKey = 'is_rotation_control_enabled'; static const String storageCameraEnabledKey = 'is_camera_enabled'; static const String storageSpeechEnabledKey = 'is_speech_enabled'; static const String storageRoundTimeKey = 'round_time'; static const String storageGamesPlayedKey = 'games_played'; static const String storageGamesFinishedKey = 'games_finished'; static const String storageNotificationsEnabledKey = 'is_notifications_enabled'; final SharedPreferences storage; SettingsRepository({@required this.storage}); bool isAudioEnabled() { return storage.getBool(storageAudioEnabledKey) ?? true; } bool toggleAudio() { var value = !isAudioEnabled(); storage.setBool(storageAudioEnabledKey, value); return value; } bool isRotationControlEnabled() { return storage.getBool(storageRotationControlEnabledKey) ?? false; } bool toggleRotationControl() { var value = !isRotationControlEnabled(); storage.setBool(storageRotationControlEnabledKey, value); return value; } bool isCameraEnabled() { return storage.getBool(storageCameraEnabledKey) ?? false; } bool toggleCamera() { var value = !isCameraEnabled(); storage.setBool(storageCameraEnabledKey, value); return value; } bool isSpeechEnabled() { return storage.getBool(storageSpeechEnabledKey) ?? false; } bool toggleSpeech() { var value = !isSpeechEnabled(); storage.setBool(storageSpeechEnabledKey, value); return value; } int getRoundTime() { return storage.getInt(storageRoundTimeKey) ?? 60; } int setRoundTime(int roundTime) { storage.setInt(storageRoundTimeKey, roundTime); return roundTime; } int getGamesPlayed() { return storage.getInt(storageGamesPlayedKey) ?? 0; } int increaseGamesPlayed() { var gamesPlayed = getGamesPlayed() + 1; storage.setInt(storageGamesPlayedKey, gamesPlayed); return gamesPlayed; } int getGamesFinished() { return storage.getInt(storageGamesFinishedKey) ?? 0; } int increaseGamesFinished() { var gamesFinished = getGamesFinished() + 1; storage.setInt(storageGamesFinishedKey, gamesFinished); return gamesFinished; } bool isNotificationsEnabled() { return storage.getBool(storageNotificationsEnabledKey) ?? false; } void enableNotifications() { storage.setBool(storageNotificationsEnabledKey, true); } Future<String> getAppVersion() async { return (await PackageInfo.fromPlatform()).version; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/repository/tutorial.dart
import 'dart:core'; import 'package:meta/meta.dart'; import 'package:shared_preferences/shared_preferences.dart'; class TutorialRepository { static const String storageWatchKey = 'is_tutorial_watched'; final SharedPreferences storage; TutorialRepository({@required this.storage}); isWatched() { return storage.getBool(storageWatchKey) ?? false; } watch() { storage.setBool(storageWatchKey, true); return true; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/models/question.dart
class Question { final String name; final String categoryName; bool isPassed; Question(this.name, this.categoryName); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/models/category.dart
import 'package:zgadula/models/question.dart'; class Category { final String id; final String name; final String image; final String description; List<Question> questions; Category( this.id, this.name, this.image, this.description, this.questions, ); Category.fromJson(Map<String, dynamic> json) : id = json['id'], name = json['name'], image = json['image'], description = json['description'], questions = List.from( json['questions'].map((name) => Question(name, json['name']))); String toString() { return name; } String getImagePath() { return 'assets/images/categories/$image'; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/models/contributor.dart
class Contributor { final String name; final String username; Contributor(this.name, this.username); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/ui/theme.dart
import 'package:flutter/material.dart'; import 'package:flutter_device_type/flutter_device_type.dart'; const Color primaryColor = Color(0xFF102636); const Color primaryDarkColor = Color(0xFF0a1822); const Color primaryLightColor = Color(0xFF16344a); const Color secondaryColor = Color(0xFF984E99); const Color secondaryDarkColor = Color(0xFF874588); const Color secondaryLightColor = Color(0xFFa857a9); const Color successColor = Colors.green; const Color textColor = Color(0xFFEEEEEE); final isTablet = Device.get().isTablet; ThemeData createTheme(BuildContext context) { ThemeData theme = ThemeData( fontFamily: 'Lato', brightness: Brightness.dark, buttonColor: secondaryColor, backgroundColor: primaryDarkColor, indicatorColor: secondaryColor, scaffoldBackgroundColor: Colors.transparent, primaryColorDark: primaryDarkColor, primaryColorLight: primaryLightColor, primaryColor: primaryColor, accentColor: secondaryColor, toggleableActiveColor: secondaryLightColor, iconTheme: IconThemeData( color: Color(0xFFFFFFFF), ), dividerColor: Colors.white30, textTheme: Theme.of(context).textTheme.apply( bodyColor: textColor, displayColor: Color(0xFF757575), fontSizeFactor: isTablet ? 1.75 : 1.0, ), buttonTheme: ButtonThemeData( height: isTablet ? 56.0 : 42.0, minWidth: 180, buttonColor: secondaryColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(1000), ), ), sliderTheme: SliderTheme.of(context).copyWith( activeTickMarkColor: Colors.transparent, activeTrackColor: secondaryDarkColor, thumbColor: secondaryColor, inactiveTickMarkColor: secondaryColor, inactiveTrackColor: primaryDarkColor, overlayColor: secondaryLightColor.withOpacity(0.5), ), ); return theme; } class ThemeConfig { static final appBarHeight = isTablet ? 74.0 : 32.0; static final appBarIconSize = isTablet ? 50.0 : 24.0; static final appBarFontSize = isTablet ? 36.0 : 20.0; static final backButtonHeight = isTablet ? 80.0 : 50.0; static final categoriesGridCount = isTablet ? 3 : 2; static final categoriesTextHeight = isTablet ? 55.0 : 35.0; static final categoriesTextSize = isTablet ? 22.0 : 14.0; static final categoriesMetaSize = isTablet ? 14.0 : 10.0; static final categoryImageSize = isTablet ? 280.0 : 170.0; static final fullScreenIconSize = isTablet ? 164.0 : 96.0; }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/category_list_item.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/localizations.dart'; import 'package:zgadula/store/category.dart'; import 'package:zgadula/ui/theme.dart'; import 'package:zgadula/models/category.dart'; import 'category_image.dart'; class CategoryListItem extends StatefulWidget { CategoryListItem({ this.category, this.onTap, }); final Category category; final VoidCallback onTap; @override _CategoryListItemState createState() => _CategoryListItemState(); } class _CategoryListItemState extends State<CategoryListItem> { Widget buildMetaItem(String text, [IconData icon]) { return Opacity( opacity: 0.7, child: Row( children: [ icon != null ? Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: Icon(icon, size: 14), ) : null, Text( text, style: TextStyle( color: Colors.white, fontSize: ThemeConfig.categoriesMetaSize, ), ), ].where((o) => o != null).toList(), ), ); } @override Widget build(BuildContext context) { int questionCount = widget.category.questions.length; return GestureDetector( onTap: widget.onTap, child: Stack( children: [ Hero( tag: 'categoryImage-${widget.category.name}', child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(8)), child: CategoryImage(photo: widget.category.getImagePath())), ), Align( alignment: Alignment.topRight, child: ClipRRect( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(8), topRight: Radius.circular(8), ), child: Container( color: Theme.of(context).primaryColor.withOpacity(0.5), padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8), child: Text( widget.category.name, textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: ThemeConfig.categoriesTextSize, ), ), ), ), ), Positioned( bottom: 0, left: 0, right: 0, height: 30, child: ClipRRect( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8), ), child: Container( height: double.infinity, color: Theme.of(context).primaryColor.withOpacity(0.5), ), ), ), ScopedModelDescendant<CategoryModel>( builder: (context, child, model) { return Positioned( bottom: 10, left: 10, child: buildMetaItem( model.getPlayedCount(widget.category).toString(), Icons.play_arrow, ), ); }, ), questionCount > 0 ? Positioned( bottom: 10, right: 10, child: buildMetaItem( AppLocalizations.of(context) .categoryItemQuestionsCount(questionCount), ), ) : null, ].where((o) => o != null).toList(), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/category_image.dart
import 'package:flutter/material.dart'; class CategoryImage extends StatelessWidget { CategoryImage({ Key key, this.photo, }) : super(key: key); final String photo; Widget build(BuildContext context) { return Material( color: Colors.transparent, child: Stack( children: [ Image.asset( photo, fit: BoxFit.contain, ), Positioned( right: 0.0, left: 0.0, bottom: 0.0, top: 0.0, child: Container( decoration: BoxDecoration( color: Theme.of(context).primaryColor.withOpacity(0.3), ), ), ), ], ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/widgets.dart
export 'category_image.dart'; export 'category_list_item.dart'; export 'category_list.dart'; export 'flag_image.dart'; export 'screen_loader.dart'; export 'gallery_horizontal.dart'; export 'game_controller.dart';
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/flag_image.dart
import 'package:flutter/material.dart'; class FlagImage extends StatelessWidget { FlagImage({ Key key, this.country, }) : super(key: key); final String country; Widget build(BuildContext context) { return Material( color: Colors.transparent, child: Image.asset( 'assets/images/flags/$country.png', fit: BoxFit.cover, width: 36.0, height: 24.0, ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/game_controller.dart
import 'package:flutter/material.dart'; class GameController extends StatefulWidget { GameController({ Key key, this.child, this.alignment, this.color, this.onTap, }) : super(key: key); final Widget child; final Alignment alignment; final Color color; final Function onTap; @override _GameControllerState createState() => _GameControllerState(); } class _GameControllerState extends State<GameController> { Widget build(BuildContext context) { return Expanded( child: GestureDetector( onTap: widget.onTap, child: Container( alignment: widget.alignment, child: Opacity(opacity: 0.6, child: widget.child), height: double.infinity, decoration: BoxDecoration(color: widget.color), ), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/gallery_horizontal.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:carousel_slider/carousel_slider.dart'; class GalleryHorizontal extends StatelessWidget { GalleryHorizontal({ this.items, this.onTap, }); final List<FileSystemEntity> items; final Function(FileSystemEntity) onTap; @override Widget build(BuildContext context) { return CarouselSlider( enableInfiniteScroll: true, height: 100.0, enlargeCenterPage: true, autoPlay: true, viewportFraction: 0.23, items: items.map((item) { return Builder( builder: (BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: GestureDetector( onTap: () { onTap(item); }, child: Image.file(item, fit: BoxFit.contain)), ); }, ); }).toList(), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/category_list.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/services/analytics.dart'; import 'package:zgadula/store/category.dart'; import 'package:zgadula/ui/theme.dart'; import 'package:zgadula/models/category.dart'; import 'category_list_item.dart'; class CategoryList extends StatelessWidget { CategoryList({ Key key, this.categories, }) : super(key: key); final List<Category> categories; @override Widget build(BuildContext context) { return ScopedModelDescendant<CategoryModel>( builder: (context, child, model) { return ListView( children: [ GridView.count( shrinkWrap: true, primary: false, padding: EdgeInsets.all(8), crossAxisSpacing: 8, mainAxisSpacing: 8, crossAxisCount: ThemeConfig.categoriesGridCount, children: categories.asMap().keys.map((index) { var category = categories[index]; return CategoryListItem( category: category, onTap: () { model.setCurrent(category); AnalyticsService.logEvent( 'category_select', {'category': category.name}, ); Navigator.pushNamed( context, '/category', ); }, ); }).toList(), ), ], ); }); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/shared/screen_loader.dart
import 'package:flutter/material.dart'; class ScreenLoader extends StatelessWidget { Widget build(BuildContext context) { return Container( child: Center( child: CircularProgressIndicator(), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui/shared
mirrored_repositories/party_flutter/lib/ui/shared/reveal/pager_indicator.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import '../../theme.dart'; import 'pages.dart'; class PagerIndicator extends StatelessWidget { final PagerIndicatorViewModel viewModel; PagerIndicator({ this.viewModel, }); @override Widget build(BuildContext context) { List<PageBubble> bubbles = []; for (var i = 0; i < viewModel.pages.length; ++i) { final page = viewModel.pages[i]; var percentActive; if (i == viewModel.activeIndex) { percentActive = 1.0 - viewModel.slidePercent; } else if (i == viewModel.activeIndex - 1 && viewModel.slideDirection == SlideDirection.leftToRight) { percentActive = viewModel.slidePercent; } else if (i == viewModel.activeIndex + 1 && viewModel.slideDirection == SlideDirection.rightToLeft) { percentActive = viewModel.slidePercent; } else { percentActive = 0.0; } bool isHollow = i != viewModel.activeIndex; bubbles.add( PageBubble( viewModel: PageBubbleViewModel( page.color, isHollow, percentActive, ), ), ); } return Column( children: [ Expanded(child: Container()), Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: bubbles, ), ), ], ); } } enum SlideDirection { leftToRight, rightToLeft, none, } class PagerIndicatorViewModel { final List<PageViewModel> pages; final int activeIndex; final SlideDirection slideDirection; final double slidePercent; PagerIndicatorViewModel( this.pages, this.activeIndex, this.slideDirection, this.slidePercent, ); } class PageBubble extends StatelessWidget { final PageBubbleViewModel viewModel; PageBubble({ this.viewModel, }); @override Widget build(BuildContext context) { Color color = secondaryDarkColor; return Container( width: 25.0, height: 55.0, child: Center( child: Container( width: lerpDouble(12.0, 16.0, viewModel.activePercent), height: lerpDouble(12.0, 16.0, viewModel.activePercent), decoration: BoxDecoration( shape: BoxShape.rectangle, borderRadius: BorderRadius.circular(2.0), color: viewModel.isHollow ? color.withOpacity(viewModel.activePercent) : secondaryColor, border: Border.all( color: viewModel.isHollow ? color.withOpacity(1 - viewModel.activePercent) : Colors.transparent, width: 2.0, ), ), ), ), ); } } class PageBubbleViewModel { final Color color; final bool isHollow; final double activePercent; PageBubbleViewModel( this.color, this.isHollow, this.activePercent, ); }
0
mirrored_repositories/party_flutter/lib/ui/shared
mirrored_repositories/party_flutter/lib/ui/shared/reveal/page_reveal.dart
import 'dart:math'; import 'package:flutter/material.dart'; class PageReveal extends StatelessWidget { final double revealPercent; final Widget child; PageReveal({ this.revealPercent, this.child, }); @override Widget build(BuildContext context) { return ClipOval( clipper: CircleRevealClipper(revealPercent), child: child, ); } } class CircleRevealClipper extends CustomClipper<Rect> { final double revealPercent; CircleRevealClipper( this.revealPercent, ); @override Rect getClip(Size size) { final epicenter = Offset(size.width / 2, size.height * 0.9); // Calculate distance from epicenter to the top left corner to make sure we fill the screen. double theta = atan(epicenter.dy / epicenter.dx); final distanceToCorner = epicenter.dy / sin(theta); final radius = distanceToCorner * revealPercent; final diameter = 2 * radius; return Rect.fromLTWH( epicenter.dx - radius, epicenter.dy - radius, diameter, diameter); } @override bool shouldReclip(CustomClipper<Rect> oldClipper) { return true; } }
0
mirrored_repositories/party_flutter/lib/ui/shared
mirrored_repositories/party_flutter/lib/ui/shared/reveal/widgets.dart
export 'pager_indicator.dart'; export 'page_dragger.dart'; export 'page_reveal.dart'; export 'pages.dart';
0
mirrored_repositories/party_flutter/lib/ui/shared
mirrored_repositories/party_flutter/lib/ui/shared/reveal/page_dragger.dart
import 'dart:async'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'pager_indicator.dart'; class PageDragger extends StatefulWidget { final bool canDragLeftToRight; final bool canDragRightToLeft; final StreamController<SlideUpdate> slideUpdateStream; PageDragger({ this.canDragLeftToRight, this.canDragRightToLeft, this.slideUpdateStream, }); @override _PageDraggerState createState() => _PageDraggerState(); } class _PageDraggerState extends State<PageDragger> { static const FULL_TRANSITION_PX = 300.0; Offset dragStart; SlideDirection slideDirection; double slidePercent = 0.0; onDragStart(DragStartDetails details) { dragStart = details.globalPosition; } onDragUpdate(DragUpdateDetails details) { if (dragStart != null) { final newPosition = details.globalPosition; final dx = dragStart.dx - newPosition.dx; if (dx > 0.0 && widget.canDragRightToLeft) { slideDirection = SlideDirection.rightToLeft; } else if (dx < 0.0 && widget.canDragLeftToRight) { slideDirection = SlideDirection.leftToRight; } else { slideDirection = SlideDirection.none; } if (slideDirection != SlideDirection.none) { slidePercent = (dx / FULL_TRANSITION_PX).abs().clamp(0.0, 1.0); } else { slidePercent = 0.0; } widget.slideUpdateStream.add( SlideUpdate(UpdateType.dragging, slideDirection, slidePercent)); } } onDragEnd(DragEndDetails details) { widget.slideUpdateStream.add(SlideUpdate( UpdateType.doneDragging, SlideDirection.none, 0.0, )); dragStart = null; } @override Widget build(BuildContext context) { return GestureDetector( onHorizontalDragStart: onDragStart, onHorizontalDragUpdate: onDragUpdate, onHorizontalDragEnd: onDragEnd, ); } } class AnimatedPageDragger { static const PERCENT_PER_MILLISECOND = 0.005; final slideDirection; final transitionGoal; AnimationController completionAnimationController; AnimatedPageDragger({ this.slideDirection, this.transitionGoal, slidePercent, StreamController<SlideUpdate> slideUpdateStream, TickerProvider vsync, }) { final startSlidePercent = slidePercent; var endSlidePercent; var duration; if (transitionGoal == TransitionGoal.open) { endSlidePercent = 1.0; final slideRemaining = 1.0 - slidePercent; duration = Duration( milliseconds: (slideRemaining / PERCENT_PER_MILLISECOND).round()); } else { endSlidePercent = 0.0; duration = Duration( milliseconds: (slidePercent / PERCENT_PER_MILLISECOND).round()); } completionAnimationController = AnimationController(duration: duration, vsync: vsync) ..addListener(() { slidePercent = lerpDouble( startSlidePercent, endSlidePercent, completionAnimationController.value, ); slideUpdateStream.add(SlideUpdate( UpdateType.animating, slideDirection, slidePercent, )); }) ..addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { slideUpdateStream.add(SlideUpdate( UpdateType.doneAnimating, slideDirection, endSlidePercent, )); } }); } run() { completionAnimationController.forward(from: 0.0); } dispose() { completionAnimationController.dispose(); } } enum TransitionGoal { open, close, } enum UpdateType { dragging, doneDragging, animating, doneAnimating, } class SlideUpdate { final updateType; final direction; final slidePercent; SlideUpdate( this.updateType, this.direction, this.slidePercent, ); }
0
mirrored_repositories/party_flutter/lib/ui/shared
mirrored_repositories/party_flutter/lib/ui/shared/reveal/pages.dart
import 'package:flutter/material.dart'; class Page extends StatelessWidget { final PageViewModel viewModel; final double percentVisible; final VoidCallback onSkip; Page({ this.viewModel, this.percentVisible = 1.0, this.onSkip, }); @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration(color: viewModel.color), width: double.infinity, child: Padding( padding: const EdgeInsets.only(left: 16.0, right: 16.0), child: Opacity( opacity: percentVisible, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Transform( transform: Matrix4.translationValues( 0.0, 50.0 * (1.0 - percentVisible), 0.0, ), child: Padding( padding: EdgeInsets.only(bottom: 25.0), child: Image.asset( viewModel.heroAssetPath, width: 200.0, height: 200.0, ), ), ), Transform( transform: Matrix4.translationValues( 0.0, 30.0 * (1.0 - percentVisible), 0.0, ), child: Padding( padding: EdgeInsets.only( top: 10.0, bottom: 10.0, ), child: Text( viewModel.title, style: TextStyle( fontSize: 34.0, ), ), ), ), Transform( transform: Matrix4.translationValues( 0.0, 30.0 * (1.0 - percentVisible), 0.0, ), child: Text( viewModel.body, textAlign: TextAlign.center, style: TextStyle( height: 1.2, fontSize: 18.0, ), ), ), Transform( transform: Matrix4.translationValues( 0.0, 30.0 * (1.0 - percentVisible), 0.0, ), child: Padding( padding: const EdgeInsets.only(top: 35.0, bottom: 75.0), child: RaisedButton.icon( label: Text(viewModel.skip), icon: Icon(Icons.play_circle_outline), onPressed: onSkip, ), ), ), ], ), ), ), ); } } class PageViewModel { final Color color; final String heroAssetPath; final String title; final String body; final String skip; PageViewModel( this.color, this.heroAssetPath, this.title, this.body, this.skip, ); }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/templates/screen.dart
import 'package:flutter/material.dart'; class ScreenTemplate extends StatelessWidget { ScreenTemplate({ @required this.child, this.showBack = false, this.onBack, }); final Widget child; final bool showBack; final Function onBack; @override Widget build(BuildContext context) { return Scaffold( body: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, stops: [0.4, 0.9], colors: [ Color(0xFF141E30), Color(0xFF243B55), ], ), ), child: Stack( children: [ child, showBack || onBack != null ? Positioned( top: 0, left: 0, child: SafeArea( child: IconButton( onPressed: () => onBack != null ? onBack() : Navigator.pop(context), icon: Icon(Icons.arrow_back_ios), ), ), ) : null, ].where((o) => o != null).toList(), ), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/contributors.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/store/contributor.dart'; import 'package:zgadula/ui/templates/screen.dart'; class ContributorsScreen extends StatefulWidget { @override _ContributorsScreenState createState() => _ContributorsScreenState(); } class _ContributorsScreenState extends State<ContributorsScreen> { @override void initState() { super.initState(); ContributorModel.of(context).load(); } @override Widget build(BuildContext context) { return ScreenTemplate( child: SafeArea( child: Stack( children: [ ScopedModelDescendant<ContributorModel>( builder: (context, child, model) { return ListView( children: model.contributors.map((contributor) { return ListTile( leading: Icon(Icons.person), title: Text(contributor.name), subtitle: Text(contributor.username), ); }).toList(), ); }, ), Positioned( top: 0, right: 0, child: IconButton( onPressed: () => Navigator.pop(context), icon: Icon(Icons.close), ), ), ], ), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/game_gallery.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:zgadula/services/analytics.dart'; import 'package:zgadula/store/gallery.dart'; import 'package:esys_flutter_share/esys_flutter_share.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:zgadula/ui/templates/screen.dart'; import 'package:path/path.dart'; import '../theme.dart'; class GameGalleryScreen extends StatelessWidget { Widget buildGallery() { return ScopedModelDescendant<GalleryModel>( builder: (context, child, model) { var images = model.images; return CarouselSlider( enableInfiniteScroll: true, height: MediaQuery.of(context).size.height * 0.8, enlargeCenterPage: false, autoPlay: false, viewportFraction: 1.0, initialPage: images.indexOf(model.activeImage), items: images.map((item) { return Stack(children: [ Positioned( top: 0, left: 0, right: 0, bottom: 0, child: SpinKitRing(color: secondaryColor, size: 70.0), ), Builder( builder: (BuildContext context) { return Center( child: Stack( children: [ Image.file(item, fit: BoxFit.contain), Positioned( top: 10, right: 10, child: FloatingActionButton( elevation: 0.0, child: Icon(Icons.share), backgroundColor: Theme.of(context).primaryColor, onPressed: () async { AnalyticsService.logEvent('picture_share', {}); await Share.file( 'Zgadula', basename(item.path), File(item.path).readAsBytesSync(), 'image/png', ); }, ), ), ], ), ); }, ), ]); }).toList(), onPageChanged: (index) { model.setActive(images[index]); }, ); }); } @override Widget build(BuildContext context) { return ScreenTemplate( showBack: true, child: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: buildGallery(), ), ], ), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/category_detail.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/services/analytics.dart'; import 'package:zgadula/localizations.dart'; import 'package:zgadula/store/category.dart'; import 'package:zgadula/store/settings.dart'; import 'package:zgadula/ui/templates/screen.dart'; import 'package:zgadula/ui/theme.dart'; import '../shared/widgets.dart'; class CategoryDetailScreen extends StatelessWidget { Widget buildFavorite({bool isFavorite, Function onPressed}) { return IconButton( onPressed: onPressed, icon: Icon( isFavorite ? Icons.favorite : Icons.favorite_border, color: isFavorite ? secondaryDarkColor : Colors.white, ), ); } Widget buildRoundTimeSelectItem(String text) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 12.0), child: Text( text, style: TextStyle(color: Colors.white), ), ); } @override Widget build(BuildContext context) { return ScreenTemplate( showBack: true, child: ScopedModelDescendant<CategoryModel>( builder: (context, child, model) { var category = model.currentCategory; return SafeArea( child: Stack( children: [ Container( width: double.infinity, child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 8), child: Container( width: ThemeConfig.categoryImageSize, height: ThemeConfig.categoryImageSize, child: Hero( tag: 'categoryImage-${category.name}', child: ClipOval( child: CategoryImage( photo: category.getImagePath(), ), ), ), ), ), Container( width: 320, child: Padding( padding: const EdgeInsets.only(top: 32), child: Text( category.description, textAlign: TextAlign.center, style: TextStyle(height: 1.2), ), ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: Divider( indent: 32, endIndent: 32, ), ), ScopedModelDescendant<SettingsModel>( builder: (context, child, settingsModel) { return Column( children: [ Padding( padding: const EdgeInsets.only(bottom: 8), child: RichText( text: TextSpan( text: AppLocalizations.of(context).gameTime, style: Theme.of(context).textTheme.body1, ), ), ), CupertinoSegmentedControl( padding: EdgeInsets.only(top: 8), borderColor: Colors.white, selectedColor: secondaryColor, pressedColor: secondaryDarkColor, unselectedColor: Theme.of(context).primaryColor, children: { 30: buildRoundTimeSelectItem("30s"), 60: buildRoundTimeSelectItem("60s"), 90: buildRoundTimeSelectItem("90s"), 120: buildRoundTimeSelectItem("120s"), }, groupValue: settingsModel.roundTime.toDouble(), onValueChanged: (value) { AnalyticsService.logEvent( "settings_round_time", {"value": value}); settingsModel.changeRoundTime(value.toInt()); }, ), ], ); }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 32), child: RaisedButton.icon( label: Text( AppLocalizations.of(context).preparationPlay), icon: Icon(Icons.play_circle_outline), onPressed: () { SettingsModel.of(context).increaseGamesPlayed(); Navigator.pushReplacementNamed( context, '/game-play', ); }, ), ), ], ), ), Positioned( top: 0, right: 0, child: buildFavorite( isFavorite: model.isFavorite(category), onPressed: () => model.toggleFavorite(category), ), ) ], ), ); }, ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/camera_preview.dart
import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:camera/camera.dart'; import 'package:zgadula/services/analytics.dart'; import 'package:zgadula/services/pictures.dart'; class CameraPreviewScreen extends StatefulWidget { @override CameraPreviewScreenState createState() => CameraPreviewScreenState(); } class CameraPreviewScreenState extends State<CameraPreviewScreen> with TickerProviderStateMixin, WidgetsBindingObserver { static const pictureInterval = 8; CameraController controller; Directory pictureDir; Timer pictureTimer; FileSystemEntity lastImage; AnimationController imageAnimationController; Animation<double> imageAnimation; double lastImageOpacity; Duration opacityAnimationDuration = Duration(milliseconds: 1000); @override void initState() { super.initState(); startTimer(); initCamera(); initAnimations(); WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); controller?.dispose(); imageAnimationController?.dispose(); stopTimer(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.inactive) { controller?.dispose(); } else if (state == AppLifecycleState.resumed) { if (controller != null) { initCamera(); } } } initCamera() async { if (controller != null) { await controller.dispose(); } pictureDir = await PicturesService.getDirectory(context); var frontCamera = await PicturesService.getCamera(); if (frontCamera == null) { return; } controller = CameraController( frontCamera, ResolutionPreset.high, enableAudio: false, ); controller.addListener(() { if (mounted) { setState(() {}); } }); try { await controller.initialize(); } on CameraException { print("Camera initialization exception"); } if (mounted) { setState(() {}); } } initAnimations() { imageAnimationController = AnimationController( vsync: this, duration: Duration(milliseconds: 1500)); imageAnimation = Tween<double>(begin: 0, end: 1).animate(imageAnimationController) ..addStatusListener((status) { if (status == AnimationStatus.completed) { setState(() { lastImageOpacity = 0; Future.delayed(opacityAnimationDuration).then((_) { imageAnimationController.reset(); }); }); } }); } startTimer() { pictureTimer = Timer.periodic(const Duration(seconds: pictureInterval), savePicture); } stopTimer() { pictureTimer?.cancel(); } savePicture(Timer timer) { if (controller == null) { return false; } AnalyticsService.logEvent('picture_taken', {}); controller.takePicture('${pictureDir.path}/${DateTime.now().millisecondsSinceEpoch}.png'); Future.delayed(Duration(seconds: 1)).then((_) async { List<FileSystemEntity> files = await PicturesService.getFiles(context); setState(() { lastImageOpacity = 1; lastImage = files.last; imageAnimationController.forward(); }); }); } Widget buildImageTaken() { return Positioned( right: 0, top: 0, child: AnimatedOpacity( opacity: lastImageOpacity, duration: opacityAnimationDuration, child: ScaleTransition( scale: imageAnimationController, child: Image.file( lastImage, fit: BoxFit.cover, width: 100, height: 100, ), ), ), ); } @override Widget build(BuildContext context) { if (controller == null || !controller.value.isInitialized) { return Container(); } return Center( child: RotatedBox( quarterTurns: 1, child: Stack( children: [ CameraPreview(controller), lastImage != null ? buildImageTaken() : null, ].where((w) => w != null).toList(), ), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/game_summary.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:quiver/iterables.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/localizations.dart'; import 'package:zgadula/models/question.dart'; import 'package:zgadula/store/gallery.dart'; import 'package:zgadula/store/question.dart'; import 'package:zgadula/store/settings.dart'; import 'package:zgadula/ui/theme.dart'; import '../shared/widgets.dart'; import 'package:zgadula/ui/templates/screen.dart'; class GameSummaryScreen extends StatelessWidget { Widget buildQuestionItem(BuildContext context, Question question) { if (question == null) { return Container(); } return Padding( padding: const EdgeInsets.symmetric(vertical: 6.0), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Icon( question.isPassed ? Icons.check : Icons.close, size: 20.0, color: question.isPassed ? successColor : Colors.white, ), Expanded( child: Padding( padding: const EdgeInsets.only(left: 8.0), child: Text( question.name, style: Theme.of(context).textTheme.body1, ), ), ), ], ), ); } List<Widget> buildQuestionsList( BuildContext context, List<Question> questions, ) { var chunks = partition(questions, 2).toList(); return List.generate( chunks.length, (index) => Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: Row( children: [ Expanded( child: buildQuestionItem( context, chunks[index].elementAt(0))), Expanded( child: buildQuestionItem( context, chunks[index].length > 1 ? chunks[index].elementAt(1) : null)), ], ), )).toList(); } openGallery(BuildContext context, FileSystemEntity item) { GalleryModel.of(context).setActive(item); Navigator.pushNamed( context, '/game-gallery', ); } @override Widget build(BuildContext context) { return ScopedModelDescendant<QuestionModel>( builder: (context, child, model) { return ScreenTemplate( child: SafeArea( child: Column( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only(bottom: 4, top: 8), child: Text( AppLocalizations.of(context).summaryHeader, style: Theme.of(context).textTheme.caption, ), ), Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context).accentColor, ), child: Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 16.0, ), child: Text( model.questionsPassed.length.toString(), style: Theme.of(context).textTheme.display2.copyWith( color: Theme.of(context).textTheme.body1.color, ), ), ), ), ], ), ScopedModelDescendant<GalleryModel>( builder: (context, child, model) { if (model.images.isEmpty) { return Container(); } return Padding( padding: const EdgeInsets.only(top: 16.0), child: GalleryHorizontal( items: model.images, onTap: (item) => openGallery(context, item), ), ); }, ), ListView( padding: EdgeInsets.only(top: 16), shrinkWrap: true, children: buildQuestionsList(context, model.questionsAnswered), ), Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: Divider( indent: 32, endIndent: 32, ), ), RaisedButton.icon( label: Text(AppLocalizations.of(context).summaryBack), icon: Icon(Icons.play_circle_outline), onPressed: () { if (!SettingsModel.of(context).isNotificationsEnabled) { SettingsModel.of(context).enableNotifications(); } Navigator.popUntil(context, ModalRoute.withName('/')); }, ), ], ), ), ); }, ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/game_play.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:sensors/sensors.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:rflutter_alert/rflutter_alert.dart'; import 'package:pedantic/pedantic.dart'; import 'package:zgadula/localizations.dart'; import 'package:zgadula/services/audio.dart'; import 'package:zgadula/services/vibration.dart'; import 'package:zgadula/services/analytics.dart'; import 'package:zgadula/store/category.dart'; import 'package:zgadula/models/category.dart'; import 'package:zgadula/store/question.dart'; import 'package:zgadula/store/settings.dart'; import 'package:zgadula/store/gallery.dart'; import 'package:zgadula/ui/screens/camera_preview.dart'; import 'package:zgadula/ui/templates/screen.dart'; import 'package:zgadula/ui/theme.dart'; import 'package:zgadula/services/pictures.dart'; import 'package:zgadula/services/ads.dart'; import '../shared/widgets.dart'; class GamePlayScreen extends StatefulWidget { GamePlayScreen({Key key}) : super(key: key); @override GamePlayScreenState createState() => GamePlayScreenState(); } class GamePlayScreenState extends State<GamePlayScreen> with TickerProviderStateMixin { static const _rotationChannel = MethodChannel('zgadula/orientation'); static const backgroundOpacity = 0.9; Timer gameTimer; int secondsMax; int secondsLeft = 5; bool isStarted = false; bool isPaused = false; bool isCameraEnabled = false; bool showAd = false; StreamSubscription<dynamic> _rotateSubscription; Category category; AnimationController invalidAC; Animation<double> invalidAnimation; AnimationController validAC; Animation<double> validAnimation; @override void initState() { super.initState(); startTimer(); category = CategoryModel.of(context).currentCategory; QuestionModel.of(context).generateCurrentQuestions(category.id); SettingsModel settings = SettingsModel.of(context); secondsMax = settings.roundTime; isCameraEnabled = settings.isCameraEnabled; if (settings.isRotationControlEnabled) { enableRotationControl(); } var gamesCount = settings.gamesFinished + 1; showAd = gamesCount % 2 == 0; if (showAd) { AdsService.loadInterstitialAd(); } SystemChrome.setPreferredOrientations([ DeviceOrientation.landscapeRight, ]); // TODO: Remove it when fixed in Flutter // https://github.com/flutter/flutter/issues/13238 try { _rotationChannel.invokeMethod('setLandscape'); } catch (error) { print("Error on landscape"); } initAnimations(); AnalyticsService.logEvent('play_game', {'category': category.name}); } AnimationController createAnswerAnimationController() { const duration = Duration(milliseconds: 1500); var controller = AnimationController(vsync: this, duration: duration); controller ..addStatusListener((listener) { if (listener == AnimationStatus.completed) { controller.reset(); nextQuestion(); } }); return controller; } initAnimations() { invalidAC = createAnswerAnimationController(); invalidAnimation = CurvedAnimation(parent: invalidAC, curve: Curves.elasticOut); validAC = createAnswerAnimationController(); validAnimation = CurvedAnimation(parent: validAC, curve: Curves.elasticOut); } @protected @mustCallSuper void dispose() { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); // TODO: Remove it when fixed in Flutter // https://github.com/flutter/flutter/issues/13238 try { _rotationChannel.invokeMethod('setPortrait'); } catch (error) { print("Error on portrait"); } if (_rotateSubscription != null) { _rotateSubscription.cancel(); } validAC?.dispose(); invalidAC?.dispose(); super.dispose(); stopTimer(); } enableRotationControl() { bool safePosition = true; double rotationBorder = 9.5; _rotateSubscription = accelerometerEvents.listen((AccelerometerEvent event) { if (!isStarted || isPaused) { return; } if (event.z > rotationBorder) { if (safePosition) { safePosition = false; handleInvalid(); } } else if (event.z < -rotationBorder) { if (safePosition) { safePosition = false; handleValid(); } } else if (event.z.abs() > rotationBorder / 2) { safePosition = true; } }); } startTimer() { gameTimer = Timer.periodic(const Duration(seconds: 1), gameLoop); } stopTimer() { gameTimer?.cancel(); } void gameLoop(Timer timer) { if (isPaused) { return; } if (secondsLeft <= 0 && !isPaused) { return handleTimeout(); } setState(() { secondsLeft -= 1; }); } savePictures() async { GalleryModel.of(context).update(await PicturesService.getFiles(context)); } showScore() { SettingsModel.of(context).increaseGamesFinished(); CategoryModel.of(context).increasePlayedCount(category); AnalyticsService.logEvent('game_score', { 'valid': QuestionModel.of(context).questionsPassed.length, 'invalid': QuestionModel.of(context).questionsFailed.length, }); Navigator.pushReplacementNamed(context, '/game-summary'); AdsService.showInterstitialAd(); } Future<bool> confirmBack() async { Completer completer = Completer<bool>(); unawaited( Alert( context: context, type: AlertType.warning, title: 'Zgadula', style: AlertStyle( isCloseButton: false, isOverlayTapDismiss: false, alertBorder: Border(), titleStyle: TextStyle(color: Colors.white), descStyle: TextStyle(color: Colors.white, height: 1.05), buttonAreaPadding: EdgeInsets.fromLTRB(16.0, 24.0, 16.0, 8.0), ), desc: AppLocalizations.of(context).gameCancelConfirmation, buttons: [ DialogButton( child: Text(AppLocalizations.of(context).gameCancelDeny), onPressed: () { Navigator.pop(context); completer.complete(false); }, color: Colors.transparent, ), DialogButton( child: Text(AppLocalizations.of(context).gameCancelApprove), onPressed: () { Navigator.pop(context); completer.complete(true); }, color: Theme.of(context).accentColor, ), ], ).show(), ); return completer.future; } void gameOver() { savePictures(); showScore(); } nextQuestion() { stopTimer(); if (secondsLeft == 0) { return gameOver(); } QuestionModel.of(context).setNextQuestion(); if (QuestionModel.of(context).currentQuestion == null) { return gameOver(); } setState(() { isPaused = false; }); startTimer(); } postAnswer({@required bool isValid}) { VibrationService.vibrate(); QuestionModel.of(context).answerQuestion(isValid); setState(() { isPaused = true; }); AnalyticsService.logEvent('answer_question', { 'valid': isValid, 'question': QuestionModel.of(context).currentQuestion.name, 'category': category.name, }); } handleValid() { if (isPaused) { return; } AudioService.valid(context); validAC.forward(); postAnswer(isValid: true); } handleInvalid() { if (isPaused) { return; } AudioService.invalid(context); invalidAC.forward(); postAnswer(isValid: false); } void handleTimeout() { if (isStarted) { handleInvalid(); } else { setState(() { isStarted = true; secondsLeft = secondsMax; }); } } Widget buildHeader(String text) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Text( text, textAlign: TextAlign.center, style: TextStyle( fontSize: 64.0, fontWeight: FontWeight.bold, ), ), ); } Widget buildHeaderIcon(IconData icon) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Icon( icon, size: ThemeConfig.fullScreenIconSize, color: Theme.of(context).textTheme.body1.color, ), ); } Widget buildSplashContent(Widget child, Color background, [IconData icon]) { return Container( decoration: BoxDecoration(color: background), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Center( child: child, ), ), QuestionModel.of(context).isPreLastQuestion() ? Padding( padding: EdgeInsets.only(bottom: 16), child: Text( AppLocalizations.of(context).lastQuestion, style: TextStyle( fontSize: 36.0, fontWeight: FontWeight.bold, color: Colors.white, ), ), ) : null, ].where((o) => o != null).toList(), ), ); } Widget buildGameContent() { return ScopedModelDescendant<QuestionModel>( builder: (context, child, model) { var currentQuestion = model.currentQuestion; return Stack( children: [ Row( children: [ GameController( child: buildHeaderIcon(Icons.sentiment_very_satisfied), alignment: Alignment.bottomCenter, color: successColor.withOpacity(backgroundOpacity), onTap: handleValid, ), GameController( child: buildHeaderIcon(Icons.sentiment_very_dissatisfied), alignment: Alignment.bottomCenter, color: Theme.of(context) .errorColor .withOpacity(backgroundOpacity), onTap: handleInvalid, ), ], ), IgnorePointer( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ currentQuestion == null ? null : Padding( padding: EdgeInsets.only(top: 8.0), child: SafeArea( child: Text( currentQuestion.categoryName, style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), currentQuestion == null ? null : Expanded( child: Center( child: buildHeader(currentQuestion.name), ), ), Padding( padding: EdgeInsets.only(bottom: 20.0), child: Text( secondsLeft.toString(), style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ].where((o) => o != null).toList(), ), ), ), ], ); }, ); } Widget buildContent() { if (isPaused || isStarted) { return Stack( children: [ buildGameContent(), ScaleTransition( scale: invalidAnimation, child: buildSplashContent( buildHeaderIcon(Icons.sentiment_very_dissatisfied), Theme.of(context).errorColor, ), ), ScaleTransition( scale: validAnimation, child: buildSplashContent( buildHeaderIcon(Icons.sentiment_very_satisfied), successColor, ), ), ], ); } return buildSplashContent( Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Text( AppLocalizations.of(context).preparationOrientationDescription, textAlign: TextAlign.center, style: TextStyle( fontSize: 40.0, fontWeight: FontWeight.bold, ), ), ), buildHeader(secondsLeft.toString()), ], ), Colors.transparent, ); } @override Widget build(BuildContext context) { bool showCamera = isCameraEnabled && isStarted; return ScreenTemplate( onBack: () async { if (await confirmBack()) { Navigator.pop(context); } }, child: WillPopScope( onWillPop: () async { return await confirmBack(); }, child: Stack( children: [ showCamera ? CameraPreviewScreen() : null, buildContent(), ].where((o) => o != null).toList(), ), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/settings.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:package_info/package_info.dart'; import 'package:zgadula/localizations.dart'; import 'package:zgadula/services/analytics.dart'; import 'package:zgadula/services/language.dart'; import 'package:zgadula/store/settings.dart'; import 'package:zgadula/store/language.dart'; import '../shared/widgets.dart'; import 'package:zgadula/ui/templates/screen.dart'; class SettingsScreen extends StatelessWidget { Future<bool> _requestPermissions( List<PermissionGroup> permissionGroups) async { Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions(permissionGroups); return permissions.values .where((status) => status != PermissionStatus.granted) .isEmpty; } Future<bool> requestCameraPermissions() async { return _requestPermissions([ PermissionGroup.camera, PermissionGroup.microphone, ]); } void logChange(String field, dynamic value) { AnalyticsService.logEvent(field, {"value": value}); } Widget buildContent(context) { return Container( child: ScopedModelDescendant<SettingsModel>( builder: (context, child, model) { return ListView( children: [ SwitchListTile( title: Text(AppLocalizations.of(context).settingsCamera), subtitle: Text(AppLocalizations.of(context).settingsCameraHint), value: model.isCameraEnabled, onChanged: (bool value) async { if (value && !await requestCameraPermissions()) { return; } logChange('settings_camera', value); model.toggleCamera(); }, secondary: Icon(Icons.camera_alt), ), SwitchListTile( title: Text(AppLocalizations.of(context).settingsAccelerometer), subtitle: Text( AppLocalizations.of(context).settingsAccelerometerHint), value: model.isRotationControlEnabled, onChanged: (bool value) { logChange('settings_accelerometer', value); model.toggleRotationControl(); }, secondary: Icon(Icons.screen_rotation), ), SwitchListTile( title: Text(AppLocalizations.of(context).settingsAudio), value: model.isAudioEnabled, onChanged: (bool value) { logChange('settings_audio', value); model.toggleAudio(); }, secondary: Icon(Icons.music_note), ), ScopedModelDescendant<LanguageModel>( builder: (context, child, model) { return ListTile( title: Text(AppLocalizations.of(context).settingsLanguage), leading: Icon(Icons.flag), trailing: DropdownButtonHideUnderline( child: DropdownButton( value: model.language, items: LanguageService.getCodes() .map( (code) => DropdownMenuItem( child: Row( children: [ Padding( padding: EdgeInsets.only(right: 8.0), child: FlagImage(country: code), ), Text(code.toUpperCase()), ], ), value: code, ), ) .toList(), onChanged: (String language) { logChange('settings_language', language); model.changeLanguage(language); }, ), )); }, ), ListTile( leading: Icon(Icons.open_in_browser), title: Text(AppLocalizations.of(context).settingsPrivacyPolicy), onTap: openPrivacyPolicy, ), ListTile( leading: Icon(Icons.help), title: Text(AppLocalizations.of(context).settingsStartTutorial), onTap: () => openTutorial(context), ), ], ); }, ), ); } @override Widget build(BuildContext context) { return ScreenTemplate( child: SafeArea( child: Column( children: [ Expanded( child: buildContent(context), ), FutureBuilder<PackageInfo>( future: PackageInfo.fromPlatform(), builder: (context, snapshot) { if (snapshot.hasData) { return GestureDetector( onTap: () => openCredits(context), child: Padding( padding: EdgeInsets.only(bottom: 8), child: Text('v ${snapshot.data.version}'), ), ); } return Container(); }, ), ], ), ), ); } openTutorial(BuildContext context) { AnalyticsService.logEvent('settings_tutorial', {}); Navigator.pushNamed( context, '/tutorial', ); } openCredits(BuildContext context) { Navigator.pushNamed( context, '/contributors', ); } openPrivacyPolicy() async { AnalyticsService.logEvent('settings_privacy', {}); const url = SettingsModel.privacyPolicyUrl; if (await canLaunch(url)) { await launch(url); } } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/category_list.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/store/category.dart'; import '../shared/widgets.dart'; import 'package:zgadula/ui/templates/screen.dart'; class CategoryListScreen extends StatefulWidget { @override _CategoryListScreenState createState() => _CategoryListScreenState(); } class _CategoryListScreenState extends State<CategoryListScreen> { @override Widget build(BuildContext context) { return ScreenTemplate( child: ScopedModelDescendant<CategoryModel>( builder: (context, child, model) => CategoryList(categories: model.categories), ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/home.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/store/category.dart'; import 'package:zgadula/store/question.dart'; import 'package:zgadula/store/tutorial.dart'; import 'package:zgadula/ui/screens/category_list.dart'; import 'package:zgadula/ui/screens/category_favorites.dart'; import 'package:zgadula/ui/screens/settings.dart'; import 'package:zgadula/ui/templates/screen.dart'; import '../shared/widgets.dart'; import '../theme.dart'; class HomeScreen extends StatefulWidget { @override HomeScreenState createState() { return HomeScreenState(); } } class HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin { final List<Tab> tabs = <Tab>[ Tab(icon: Icon(Icons.play_circle_filled)), Tab(icon: Icon(Icons.favorite)), Tab(icon: Icon(Icons.settings)), ]; TabController _tabController; @override void initState() { super.initState(); _tabController = TabController(vsync: this, length: tabs.length); if (!isTutorialWatched()) { WidgetsBinding.instance.addPostFrameCallback((_) => Navigator.pushNamed( context, '/tutorial', )); } } @override void dispose() { _tabController.dispose(); super.dispose(); } bool isTutorialWatched() { return TutorialModel.of(context).isWatched; } @override Widget build(BuildContext context) { return ScopedModelDescendant<CategoryModel>( builder: (context, child, model) => ScopedModelDescendant<QuestionModel>( builder: (context, child, qModel) { if (model.isLoading || qModel.isLoading || !isTutorialWatched()) { return ScreenLoader(); } return ScreenTemplate( child: Scaffold( bottomNavigationBar: Container( color: primaryDarkColor, height: 55, child: Container( decoration: BoxDecoration( border: Border( top: BorderSide( color: primaryColor, width: 1, ), ), ), child: TabBar( controller: _tabController, labelColor: Theme.of(context).buttonColor, unselectedLabelColor: primaryLightColor, indicatorColor: primaryDarkColor, indicatorSize: TabBarIndicatorSize.label, tabs: tabs, ), ), ), body: TabBarView( controller: _tabController, children: [ CategoryListScreen(), CategoryFavoritesScreen(), SettingsScreen(), ], ), ), ); }, ), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/category_favorites.dart
import 'package:flutter/material.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/store/category.dart'; import 'package:zgadula/localizations.dart'; import '../shared/widgets.dart'; import 'package:zgadula/ui/templates/screen.dart'; class CategoryFavoritesScreen extends StatelessWidget { @override Widget build(BuildContext context) { return ScreenTemplate( child: ScopedModelDescendant<CategoryModel>( builder: (context, child, model) { if (model.favourites.isEmpty) { return Opacity( opacity: 0.5, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon(Icons.favorite_border, size: 96), Container( width: 160, child: Text( AppLocalizations.of(context).emptyFavorites, textAlign: TextAlign.center, style: TextStyle( height: 1.3, ), ), ), ], ), ), ); } return CategoryList(categories: model.favourites); }), ); } }
0
mirrored_repositories/party_flutter/lib/ui
mirrored_repositories/party_flutter/lib/ui/screens/tutorial.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:zgadula/localizations.dart'; import 'package:zgadula/store/tutorial.dart'; import '../shared/reveal/widgets.dart'; class TutorialScreen extends StatefulWidget { @override TutorialScreenState createState() => TutorialScreenState(); } class TutorialScreenState extends State<TutorialScreen> with TickerProviderStateMixin { StreamController<SlideUpdate> slideUpdateStream; AnimatedPageDragger animatedPageDragger; int activeIndex = 0; int nextPageIndex = 0; SlideDirection slideDirection = SlideDirection.none; double slidePercent = 0.0; TutorialScreenState() { slideUpdateStream = StreamController<SlideUpdate>(); slideUpdateStream.stream.listen((SlideUpdate event) { setState(() { if (event.updateType == UpdateType.dragging) { slideDirection = event.direction; slidePercent = event.slidePercent; if (slideDirection == SlideDirection.leftToRight) { nextPageIndex = activeIndex - 1; } else if (slideDirection == SlideDirection.rightToLeft) { nextPageIndex = activeIndex + 1; } else { nextPageIndex = activeIndex; } } else if (event.updateType == UpdateType.doneDragging) { if (slidePercent > 0.2) { animatedPageDragger = AnimatedPageDragger( slideDirection: slideDirection, transitionGoal: TransitionGoal.open, slidePercent: slidePercent, slideUpdateStream: slideUpdateStream, vsync: this, ); } else { animatedPageDragger = AnimatedPageDragger( slideDirection: slideDirection, transitionGoal: TransitionGoal.close, slidePercent: slidePercent, slideUpdateStream: slideUpdateStream, vsync: this, ); nextPageIndex = activeIndex; } animatedPageDragger.run(); } else if (event.updateType == UpdateType.animating) { slideDirection = event.direction; slidePercent = event.slidePercent; } else if (event.updateType == UpdateType.doneAnimating) { activeIndex = nextPageIndex; slideDirection = SlideDirection.none; slidePercent = 0.0; animatedPageDragger.dispose(); } }); }); } @override void initState() { TutorialModel.of(context).watch(); super.initState(); } @override dispose() { super.dispose(); slideUpdateStream.close(); } skipTutorial() { Navigator.pop(context); } List<PageViewModel> getPages(BuildContext context) { final pages = [ PageViewModel( Theme.of(context).primaryColor, 'assets/images/tutorial_1.png', AppLocalizations.of(context).tutorialFirstSectionHeader, AppLocalizations.of(context).tutorialFirstSectionDescription, AppLocalizations.of(context).tutorialSkip, ), PageViewModel( Theme.of(context).primaryColorDark, 'assets/images/tutorial_2.png', AppLocalizations.of(context).tutorialSecondSectionHeader, AppLocalizations.of(context).tutorialSecondSectionDescription, AppLocalizations.of(context).tutorialSkip, ), PageViewModel( Theme.of(context).primaryColor, 'assets/images/tutorial_3.png', AppLocalizations.of(context).tutorialThirdSectionHeader, AppLocalizations.of(context).tutorialThirdSectionDescription, AppLocalizations.of(context).tutorialSkip, ), PageViewModel( Theme.of(context).primaryColorDark, 'assets/images/tutorial_4.png', AppLocalizations.of(context).tutorialFourthSectionHeader, AppLocalizations.of(context).tutorialFourthSectionDescription, AppLocalizations.of(context).tutorialSkip, ), ]; return pages; } @override Widget build(BuildContext context) { List<PageViewModel> pages = getPages(context); return Scaffold( body: Stack( children: [ Page( viewModel: pages[activeIndex], percentVisible: 1.0, onSkip: skipTutorial, ), PageReveal( revealPercent: slidePercent, child: Page( viewModel: pages[nextPageIndex], percentVisible: slidePercent, onSkip: skipTutorial, ), ), PagerIndicator( viewModel: PagerIndicatorViewModel( pages, activeIndex, slideDirection, slidePercent, ), ), PageDragger( canDragLeftToRight: activeIndex > 0, canDragRightToLeft: activeIndex < pages.length - 1, slideUpdateStream: this.slideUpdateStream, ), ], ), ); } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/vibration.dart
import 'package:vibration/vibration.dart'; class VibrationService { static vibrate() async { bool canVibrate = await Vibration.hasVibrator(); if (canVibrate) { await Vibration.vibrate(); } } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/language.dart
class LanguageService { static List<String> getCodes() { return ['en', 'pl']; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/notifications.dart
import 'package:firebase_messaging/firebase_messaging.dart'; class NotificationsService { static FirebaseMessaging _instance; static initialize() { _instance = FirebaseMessaging(); } static register() { _instance.requestNotificationPermissions(); } static Future<String> getToken() async { return await _instance.getToken(); } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/audio.dart
import 'package:audioplayers/audio_cache.dart'; import 'package:flutter/widgets.dart'; import 'package:zgadula/store/settings.dart'; class AudioService { static AudioCache sfxPlayer = AudioCache(prefix: 'sfx/'); static _playSfx(BuildContext context, String name) async { bool canAudio = SettingsModel.of(context).isAudioEnabled; if (canAudio) { await sfxPlayer.play(name); } } static invalid(context) { _playSfx(context, 'choice_invalid.wav'); } static valid(context) { _playSfx(context, 'choice_valid.wav'); } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/crashlytics.dart
import 'package:flutter/material.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; class CrashlyticsService { static initialize() { // Crashlytics.instance.enableInDevMode = true; FlutterError.onError = (FlutterErrorDetails details) { Crashlytics.instance.recordFlutterError(details); }; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/analytics.dart
import 'package:firebase_analytics/firebase_analytics.dart'; class AnalyticsService { static FirebaseAnalytics analytics = FirebaseAnalytics(); static logEvent(String name, Map<String, dynamic> parameters) { analytics.logEvent(name: name, parameters: parameters); } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/ads.dart
import 'dart:io' show Platform; import 'package:firebase_admob/firebase_admob.dart'; class AdsService { static final String appId = Platform.isAndroid ? 'ca-app-pub-4764697513834958~1271811266' : 'ca-app-pub-4764697513834958~9794133262'; static InterstitialAd interstitialAd; static final String interstitialId = Platform.isAndroid ? 'ca-app-pub-4764697513834958/4585204466' : 'ca-app-pub-4764697513834958/6701066069'; static final String rewardId = Platform.isAndroid ? 'ca-app-pub-4764697513834958/8632433661' : 'ca-app-pub-4764697513834958/8353232062'; static initialize() { FirebaseAdMob.instance.initialize(appId: appId); } static loadInterstitialAd() async { if (interstitialAd != null) { await interstitialAd.dispose(); } interstitialAd = InterstitialAd( adUnitId: interstitialId, ); await interstitialAd.load(); } static showInterstitialAd() { interstitialAd.show(); } static loadRewardAd() { RewardedVideoAd.instance.load(adUnitId: rewardId); } static showRewardAd() { RewardedVideoAd.instance.show(); } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/formatters.dart
class FormatterService { static String secondsToTime(int value) { int minutes = (value / 60).floor(); int seconds = value % 60; return '${minutes.toString().padLeft(2, "0")}:${seconds.toString().padLeft(2, "0")}'; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/services/pictures.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; import 'package:zgadula/store/settings.dart'; class PicturesService { static Future<Directory> getDirectory(BuildContext context) async { var baseDir = await getTemporaryDirectory(); var folder = SettingsModel.of(context).gamesPlayed.toString(); return await Directory('${baseDir.path}/game_$folder') .create(recursive: true); } static Future<List<FileSystemEntity>> getFiles(BuildContext context) async { var dir = await getDirectory(context); return dir.listSync(); } static Future<CameraDescription> getCamera() async { var cameras = await availableCameras(); var frontCamera = cameras.firstWhere((cameraDescription) => cameraDescription.lensDirection == CameraLensDirection.front); return frontCamera; } }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/store.dart
import 'package:scoped_model/scoped_model.dart'; class StoreModel extends Model { Future initialize() async {} }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/language.dart
import 'package:scoped_model/scoped_model.dart'; import 'package:flutter/widgets.dart'; import 'package:zgadula/repository/language.dart'; import 'package:zgadula/store/store.dart'; class LanguageModel extends StoreModel { LanguageRepository repository; bool _isLoading = true; bool get isLoading => _isLoading; String _language; String get language => _language; LanguageModel(this.repository); @override initialize() async { _language = repository.getLanguage(); _isLoading = false; notifyListeners(); } changeLanguage(String language) async { _language = repository.setLanguage(language); notifyListeners(); } static LanguageModel of(BuildContext context) => ScopedModel.of<LanguageModel>(context); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/question.dart
import 'package:flutter/widgets.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/models/question.dart'; import 'package:zgadula/repository/question.dart'; import 'package:zgadula/store/store.dart'; const QUESTIONS_PER_GAME = 10; class QuestionModel extends StoreModel { QuestionRepository repository; bool _isLoading = true; bool get isLoading => _isLoading; Map<String, List<Question>> _questions = {}; Map<String, List<Question>> get questions => _questions; List<Question> _currentQuestions = []; List<Question> get currentQuestions => _currentQuestions; List<Question> get questionsAnswered => _currentQuestions.where((q) => q.isPassed != null).toList(); List<Question> get questionsPassed => questionsAnswered.where((q) => q.isPassed).toList(); List<Question> get questionsFailed => questionsAnswered.where((q) => !q.isPassed).toList(); List<Question> _latestQuestions = []; List<Question> get latestQuestions => _latestQuestions; Question _currentQuestion; Question get currentQuestion => _currentQuestion; QuestionModel(this.repository); load(String languageCode) async { _isLoading = true; notifyListeners(); _questions = await repository.getAll(languageCode); _isLoading = false; notifyListeners(); } generateCurrentQuestions(String categoryId) { _currentQuestions = repository.getRandom( _questions, categoryId, QUESTIONS_PER_GAME, excluded: _latestQuestions, ); _currentQuestions.forEach((q) { q.isPassed = null; }); _latestQuestions.addAll(_currentQuestions); _currentQuestion = _currentQuestions[0]; notifyListeners(); } isPreLastQuestion() { var nextQuestion = repository.getNext(_currentQuestions, _currentQuestion); if (nextQuestion == null) { return false; } return repository.getNext(_currentQuestions, nextQuestion) == null; } setNextQuestion() { _currentQuestion = repository.getNext(_currentQuestions, _currentQuestion); notifyListeners(); } answerQuestion(bool isValid) { _currentQuestion.isPassed = isValid; notifyListeners(); } static QuestionModel of(BuildContext context) => ScopedModel.of<QuestionModel>(context); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/gallery.dart
import 'dart:io'; import 'package:scoped_model/scoped_model.dart'; import 'package:flutter/widgets.dart'; import 'package:zgadula/store/store.dart'; class GalleryModel extends StoreModel { FileSystemEntity _activeImage; FileSystemEntity get activeImage => _activeImage; List<FileSystemEntity> _images = []; List<FileSystemEntity> get images => _images; update(List<FileSystemEntity> images) { _images = images; notifyListeners(); } setActive(FileSystemEntity image) { _activeImage = image; notifyListeners(); } static GalleryModel of(BuildContext context) => ScopedModel.of<GalleryModel>(context); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/category.dart
import 'package:flutter/widgets.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/models/category.dart'; import 'package:zgadula/repository/category.dart'; import 'package:zgadula/store/store.dart'; class CategoryModel extends StoreModel { CategoryRepository repository; bool _isLoading = true; bool get isLoading => _isLoading; Map<String, Category> _categories = {}; List<Category> get categories => _categories.values.toList(); List<String> _favourites = []; List<Category> get favourites => _favourites.map((id) => _categories[id]).where((c) => c != null).toList(); Category _currentCategory; Category get currentCategory => _currentCategory; Map<String, int> _playedCount = {}; Map<String, int> get playedCount => _playedCount; CategoryModel(this.repository); load(String languageCode) async { _isLoading = true; notifyListeners(); _categories = Map.fromIterable( await repository.getAll(languageCode), key: (c) => c.id, value: (c) => c, ); _favourites = repository.getFavorites(); _isLoading = false; notifyListeners(); } setCurrent(Category category) { _currentCategory = category; notifyListeners(); } isFavorite(Category category) { return _favourites.contains(category.id); } toggleFavorite(Category category) { _favourites = repository.toggleFavorite(_favourites, category); notifyListeners(); } getPlayedCount(Category category) { if (!_playedCount.containsKey(category.id)) { _playedCount[category.id] = repository.getPlayedCount(category); } return _playedCount[category.id]; } increasePlayedCount(Category category) async { _playedCount[category.id] = repository.increasePlayedCount(category); notifyListeners(); } static CategoryModel of(BuildContext context) => ScopedModel.of<CategoryModel>(context); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/contributor.dart
import 'package:flutter/widgets.dart'; import 'package:scoped_model/scoped_model.dart'; import 'package:zgadula/models/contributor.dart'; import 'package:zgadula/repository/contributor.dart'; import 'package:zgadula/store/store.dart'; class ContributorModel extends StoreModel { ContributorRepository repository; bool _isLoading = true; bool get isLoading => _isLoading; List<Contributor> _contributors = []; List<Contributor> get contributors => _contributors; ContributorModel(this.repository); load() async { if (_contributors.isNotEmpty) { return; } _isLoading = true; notifyListeners(); _contributors = await repository.getAll(); _isLoading = false; notifyListeners(); } static ContributorModel of(BuildContext context) => ScopedModel.of<ContributorModel>(context); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/settings.dart
import 'package:scoped_model/scoped_model.dart'; import 'package:flutter/widgets.dart'; import 'package:zgadula/repository/settings.dart'; import 'package:zgadula/services/notifications.dart'; import 'package:zgadula/store/store.dart'; class SettingsModel extends StoreModel { SettingsRepository repository; static const String androidId = 'com.puppybox.zgadula'; static const String appleId = '1181083547'; static const String privacyPolicyUrl = 'https://github.com/vintage/party_flutter/blob/master/PRIVACY_POLICY.md'; bool _isLoading = true; bool get isLoading => _isLoading; bool _isAudioEnabled; bool get isAudioEnabled => _isAudioEnabled; bool _isRotationControlEnabled; bool get isRotationControlEnabled => _isRotationControlEnabled; bool _isCameraEnabled; bool get isCameraEnabled => _isCameraEnabled; bool _isSpeechEnabled; bool get isSpeechEnabled => _isSpeechEnabled; int _roundTime; int get roundTime => _roundTime; String _version; String get version => _version; int _gamesPlayed; int get gamesPlayed => _gamesPlayed; int _gamesFinished; int get gamesFinished => _gamesFinished; bool _isNotificationsEnabled; bool get isNotificationsEnabled => _isNotificationsEnabled; SettingsModel(this.repository); @override initialize() async { _isLoading = true; notifyListeners(); _isAudioEnabled = repository.isAudioEnabled(); _isRotationControlEnabled = repository.isRotationControlEnabled(); _isCameraEnabled = repository.isCameraEnabled(); _isSpeechEnabled = repository.isSpeechEnabled(); _roundTime = repository.getRoundTime(); _version = await repository.getAppVersion(); _gamesPlayed = repository.getGamesPlayed(); _gamesFinished = repository.getGamesFinished(); _isNotificationsEnabled = repository.isNotificationsEnabled(); _isLoading = false; notifyListeners(); } toggleAudio() async { _isAudioEnabled = repository.toggleAudio(); notifyListeners(); } toggleRotationControl() async { _isRotationControlEnabled = repository.toggleRotationControl(); notifyListeners(); } toggleCamera() async { _isCameraEnabled = repository.toggleCamera(); notifyListeners(); } toggleSpeech() async { _isSpeechEnabled = repository.toggleSpeech(); notifyListeners(); } changeRoundTime(int roundTime) async { _roundTime = repository.setRoundTime(roundTime); notifyListeners(); } increaseGamesPlayed() async { _gamesPlayed = repository.increaseGamesPlayed(); notifyListeners(); } increaseGamesFinished() async { _gamesFinished = repository.increaseGamesFinished(); notifyListeners(); } enableNotifications() { NotificationsService.register(); _isNotificationsEnabled = true; repository.enableNotifications(); notifyListeners(); } static SettingsModel of(BuildContext context) => ScopedModel.of<SettingsModel>(context); }
0
mirrored_repositories/party_flutter/lib
mirrored_repositories/party_flutter/lib/store/tutorial.dart
import 'package:scoped_model/scoped_model.dart'; import 'package:flutter/widgets.dart'; import 'package:zgadula/repository/tutorial.dart'; import 'package:zgadula/store/store.dart'; class TutorialModel extends StoreModel { TutorialRepository repository; bool _isWatched = false; bool get isWatched => _isWatched; TutorialModel(this.repository); @override initialize() async { _isWatched = await repository.isWatched(); notifyListeners(); } watch() async { _isWatched = await repository.watch(); notifyListeners(); } static TutorialModel of(BuildContext context) => ScopedModel.of<TutorialModel>(context); }
0
mirrored_repositories/party_flutter
mirrored_repositories/party_flutter/test/widget_test.dart
import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('dummy', (WidgetTester tester) async { expect("foo", equals("foo")); }); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/BoxDecoration.dart
import 'package:flutter/material.dart'; void main() { var myDecoration = BoxDecoration( color: Colors.green, border: Border.all(color: Colors.blueAccent, width: 10), borderRadius: BorderRadius.circular(12)); runApp(MaterialApp( home: Scaffold( body: Container( decoration: myDecoration, child: const Icon(Icons.image, size: 50))))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/ContainerAttributes.dart
import 'package:flutter/material.dart'; void main() { var myMargin = const EdgeInsets.all(25); var myPadding = const EdgeInsets.all(25); var myDecoration = BoxDecoration( border: Border.all(color: Colors.blueAccent, width: 10), color: Colors.yellow); var myTransform = Matrix4.skewX(0.3); const icon1 = Icon( Icons.looks_one, color: Colors.red, size: 50.0, ); const icon2 = Icon( Icons.looks_two, color: Colors.grey, size: 50.0, ); const icon3 = Icon( Icons.looks_3, color: Colors.blue, size: 50.0, ); runApp(MaterialApp( home: Scaffold( body: Column(children: [ Container(padding: myPadding, child: icon1, decoration: myDecoration ), Container(margin: myMargin, child: icon2, decoration: myDecoration), Container(padding: myPadding, transform: myTransform, child: icon3) ])))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/AddingPadding.dart
import 'package:flutter/material.dart'; void main() { var text = 'Inside Container\n' * 10; const myMargin = EdgeInsets.all(10); const myPadding = EdgeInsets.all(75); runApp(MaterialApp( home: Scaffold( backgroundColor: Colors.yellow, body: Container( margin: myMargin, padding: myPadding, color: Colors.red, child: Text(text, style: const TextStyle(color: Colors.white)))))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/Alignment.dart
import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: Scaffold( body: Align( alignment: Alignment.topRight, child: Icon( Icons.center_focus_strong, color: Colors.red, size: 100.0, ) ) ) ) ); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/Row.dart
import 'package:flutter/material.dart'; void main() { const icon1 = Icon( Icons.looks_one, color: Colors.red, size: 100.0, ); const icon2 = Icon( Icons.looks_two, color: Colors.grey, size: 100.0, ); const icon3 = Icon( Icons.looks_3, color: Colors.blue, size: 100.0, ); runApp(MaterialApp( home: Scaffold( body: Row( children: [icon1, icon2, icon3] ) ) )); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/RowColumnAlignment.dart
import 'package:flutter/material.dart'; void main() { const icon1 = Icon( Icons.looks_one, color: Colors.red, size: 100.0, ); const icon2 = Icon( Icons.looks_two, color: Colors.grey, size: 100.0, ); const icon3 = Icon( Icons.looks_3, color: Colors.blue, size: 100.0, ); runApp(MaterialApp( home: Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: const [icon1, icon2, icon3] ) ) )); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/BoxDecoration2.dart
import 'package:flutter/material.dart'; void main() { // Add decoration here v var myDecoration = BoxDecoration( color: Colors.green, border: Border.all(color: Colors.blueAccent, width: 10), borderRadius: BorderRadius.circular(12) ); runApp(MaterialApp( home: Scaffold( body: Container( decoration: myDecoration, child: const Icon(Icons.brush, size: 50))))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/AddingTransforms.dart
import 'package:flutter/material.dart'; void main() { //var myTransform = Matrix4.skewX(0); var myTransform = Matrix4.skewX(0.3); //var myTransform = Matrix4.rotationZ(3.14); var myContainer = Container(transform: myTransform, child: const Text('Hi')); runApp(MaterialApp( home: Scaffold( body: Container(padding: const EdgeInsets.all(50), child: myContainer)))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/AddingMargins.dart
import 'package:flutter/material.dart'; void main() { const icon1 = Icon( Icons.looks_one, color: Colors.red, size: 50.0, ); const icon2 = Icon( Icons.looks_two, color: Colors.grey, size: 50.0, ); const icon3 = Icon( Icons.looks_3, color: Colors.blue, size: 50.0, ); var myMargin = const EdgeInsets.all(10); runApp(MaterialApp( home: Scaffold( body: Column(children: [ Container(margin: myMargin, child: icon1), Container(margin: myMargin, child: icon2), Container(margin: myMargin, child: icon3) ])))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/YellowHand.dart
// import 'package:flutter/material.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( // title: 'Flutter Demo', // theme: ThemeData( // // This is the theme of your application. // // // // TRY THIS: Try running your application with "flutter run". You'll see // // the application has a blue toolbar. Then, without quitting the app, // // try changing the seedColor in the colorScheme below to Colors.green // // and then invoke "hot reload" (save your changes or press the "hot // // reload" button in a Flutter-supported IDE, or press "r" if you used // // the command line to start the app). // // // // Notice that the counter didn't reset back to zero; the application // // state is not lost during the reload. To reset the state, use hot // // restart instead. // // // // This works for code too, not just values: Most code changes can be // // tested with just a hot reload. // colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), // useMaterial3: true, // ), // home: const MyHomePage(title: 'Flutter Demo Home Page'), // ); // } // } // // 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. // ); // } // } import 'package:flutter/material.dart'; void main() { const myIcon = Icon( // Change the icon below (See linked site) Icons.waving_hand, // Change the color below color: Colors.yellow, // Change the size below size: 100.0, ); runApp( const MaterialApp( home: Scaffold( body: myIcon ) ) ); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/FlutterDemo.dart
import 'package:flutter/material.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( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // TRY THIS: Try running your application with "flutter run". You'll see // the application has a blue toolbar. Then, without quitting the app, // try changing the seedColor in the colorScheme below to Colors.green // and then invoke "hot reload" (save your changes or press the "hot // reload" button in a Flutter-supported IDE, or press "r" if you used // the command line to start the app). // // Notice that the counter didn't reset back to zero; the application // state is not lost during the reload. To reset the state, use hot // restart instead. // // This works for code too, not just values: Most code changes can be // tested with just a hot reload. colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } 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/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/LearnLyouts.dart
import 'package:flutter/material.dart'; void main() { const headerStyle = TextStyle(color: Colors.blueAccent, fontSize: 32); var header = const Align( alignment: Alignment.bottomCenter, child: Text('Learn Flutter Layouts', style: headerStyle)); var row = Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: const [ Icon(Icons.wb_sunny_outlined, color: Colors.yellow, size: 50), Icon(Icons.waving_hand_outlined, color: Colors.green, size: 50), Icon(Icons.favorite, color: Colors.red, size: 50) ]); var column = Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [header, row]); runApp(MaterialApp(home: Scaffold(body: column))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/Center_Red_Icon.dart
import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: Scaffold( body: Center ( child: Icon( Icons.center_focus_strong, color: Colors.red, size: 100.0, ) ) ) ) ); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/main.dart
// import 'package:flutter/material.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( // title: 'Flutter Demo', // theme: ThemeData( // // This is the theme of your application. // // // // TRY THIS: Try running your application with "flutter run". You'll see // // the application has a blue toolbar. Then, without quitting the app, // // try changing the seedColor in the colorScheme below to Colors.green // // and then invoke "hot reload" (save your changes or press the "hot // // reload" button in a Flutter-supported IDE, or press "r" if you used // // the command line to start the app). // // // // Notice that the counter didn't reset back to zero; the application // // state is not lost during the reload. To reset the state, use hot // // restart instead. // // // // This works for code too, not just values: Most code changes can be // // tested with just a hot reload. // colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), // useMaterial3: true, // ), // home: const MyHomePage(title: 'Flutter Demo Home Page'), // ); // } // } // // 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. // ); // } // } import 'package:flutter/material.dart'; void main() { const myIcon = Icon( // Change the icon below (See linked site) Icons.waving_hand, // Change the color below color: Colors.yellow, // Change the size below size: 100.0, ); runApp( const MaterialApp( home: Scaffold( body: myIcon ) ) ); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/MoreAlignment.dart
import 'package:flutter/material.dart'; void main() { var column1 = Column( mainAxisAlignment: MainAxisAlignment.start, children: const [Icon(Icons.looks_one), Icon(Icons.looks_two)] ); var column2 = Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: const [Icon(Icons.looks_3), Icon(Icons.looks_4)] ); var column3 = Column( mainAxisAlignment: MainAxisAlignment.end, children: const [Icon(Icons.looks_5), Icon(Icons.looks_6)] ); var row = Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children:[column1, column2, column3]); runApp(MaterialApp( home: Scaffold( body: row ) )); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/Column.dart
import 'package:flutter/material.dart'; void main() { const icon1 = Icon( Icons.looks_one, color: Colors.red, size: 100.0, ); const icon2 = Icon( Icons.looks_two, color: Colors.grey, size: 100.0, ); const icon3 = Icon( Icons.looks_3, color: Colors.blue, size: 100.0, ); runApp(MaterialApp( home: Scaffold( body: Column( children: const [icon1, icon2, icon3] ) ) )); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/NossoApp.dart
import 'package:flutter/material.dart'; void main() { //const bigRedStyle = TextStyle(color:Colors.red, // fontSize: 24); const myIcon = Icon( Icons.check, color: Colors.blue, size: 100.0, ); runApp( const MaterialApp( home: Scaffold( body: myIcon ) // Text('Codecademy: Flutter Edition', // style: bigRedStyle // ) ) ); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/lib/Container.dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Scaffold( body: Center( child: Container( decoration: BoxDecoration( border: Border.all(color: Colors.blueAccent, width: 10), color: Colors.yellow), margin: const EdgeInsets.all(50), padding: const EdgeInsets.all(50), transform: Matrix4.skewY(0.3), child: const FlutterLogo(size: double.infinity)))))); }
0
mirrored_repositories/CodecademyIntroFlutter
mirrored_repositories/CodecademyIntroFlutter/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:codecademy_intro_flutter/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/blaze/blaze
mirrored_repositories/blaze/blaze/lib/wrapper.dart
import 'package:blaze/views/home/home_screen.dart'; import 'package:blaze/views/login/login_screen.dart'; import 'package:blaze/views/on_boarding/on_boarding_screen.dart'; import 'package:blaze/views/social_layout/social_layout.dart'; import 'package:flutter/material.dart'; class Wrapper { static Widget start({String? uId, bool? onBarding}) { Widget? startWidget; if (onBarding != null) { if (uId == null) { startWidget = SocialLogin(); } else { startWidget = SocialLayout(); } } else{ startWidget = const OnBoarding(); } return startWidget; } }
0
mirrored_repositories/blaze/blaze
mirrored_repositories/blaze/blaze/lib/main.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/views/edit_profile/edit_profile.dart'; import 'package:blaze/views/login/login_screen.dart'; import 'package:blaze/views/post/post_screen.dart'; import 'package:blaze/views/register/register_screen.dart'; import 'package:blaze/views/search/search_screen.dart'; import 'package:blaze/views/settings/settings_screen.dart'; import 'package:blaze/views/social_layout/social_layout.dart'; import 'package:blaze/wrapper.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'components/themes.dart'; import 'helpers/bloc_observer.dart'; import 'helpers/local/chache_helper.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:easy_localization/easy_localization.dart'; import './translations/codegen_loader.g.dart'; Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async{ print(message.data.toString()); } void main(List<String> args) async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); await Firebase.initializeApp(); var token = await FirebaseMessaging.instance.getToken(); print(token); //FCM: //foreground fcm FirebaseMessaging.onMessage.listen((event) { print(event.data.toString()); }); //when click on notification to open app FirebaseMessaging.onMessageOpenedApp.listen((event) { print(event.data.toString()); }); //background fcm FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler); await CacheHelper.init(); bool? onBoarding = CacheHelper.getData(key: 'onBoarding'); uId = CacheHelper.getData(key: 'uId'); lang = CacheHelper.getData(key: 'lang'); print(lang); if (CacheHelper.getData(key: 'isDark') == null){ CacheHelper.saveData(key: 'isDark', value: true); } bool isDark = CacheHelper.getData(key: 'isDark'); lang ??= 'en'; Widget startWidget = Wrapper.start(uId: uId, onBarding: onBoarding); BlocOverrides.runZoned( () { runApp( EasyLocalization( assetLoader: const CodegenLoader(), supportedLocales: const [Locale('en'), Locale('ar')], path: 'assets/translations', fallbackLocale: const Locale('en'), child: MyApp(startWidget: startWidget, isDark: isDark)), ); }, blocObserver: MyBlocObserver(), ); } class MyApp extends StatelessWidget { final Widget startWidget; final bool isDark; const MyApp({Key? key, required this.startWidget, required this.isDark}) : super(key: key); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (context) => SocialCubit()..changeAppMode(fromShared: isDark)..getAllUsers()..getPosts()..getUserData()..getFollowers(), ) ], child: BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { return MaterialApp( supportedLocales: context.supportedLocales, localizationsDelegates: context.localizationDelegates, locale: context.locale, debugShowCheckedModeBanner: false, theme: lightTheme(), darkTheme: darkTheme(), themeMode: SocialCubit.get(context).isDark ? ThemeMode.dark : ThemeMode.light, home: startWidget, routes: { '/login': (context) => SocialLogin(), '/register': (context) => RegisterScreen(), '/home': (context) => SocialLayout(), '/new_post': (context) => const NewPostScreen(), '/edit_profile':(context) => const EditProfileScreen(), '/search':(context) => const SearchScreen(), '/settings':(context) => const SettingsScreen(), }, ); }), ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/post/post_screen.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/components/default_app_bar.dart'; import 'package:blaze/components/styles/icon_broken.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../components/default_text_button.dart'; import 'package:easy_localization/easy_localization.dart'; class NewPostScreen extends StatelessWidget { const NewPostScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { TextEditingController postController = TextEditingController(); return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return SafeArea( child: Scaffold( appBar: defaultAppBar( context: context, function: () { cubit.postImage = null; Navigator.pop(context); }, title: LocaleKeys.create_post.tr(), actions: [ defaultTextButton( function: () { var now = DateTime.now(); if (cubit.postImage == null) { cubit.createPost( text: postController.text, dateTime: now.toString()); } else { cubit.uploadPostImage( text: postController.text, dateTime: now.toString()); } Navigator.pop(context); }, text: LocaleKeys.post.tr()), const SizedBox(width: 8.0), ]), body: Column(children: [ if (state is SocialCreatePostLoadingState) const LinearProgressIndicator(), const SizedBox(height: 5.0), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ const SizedBox(width: 20.0), CircleAvatar( radius: 25.0, backgroundImage: NetworkImage( cubit.user.image, ), ), const SizedBox(width: 15.0), Text( cubit.user.name, style: Theme.of(context).textTheme.bodyText1, ), ], ), const SizedBox(height: 20.0), Expanded( child: TextFormField( controller: postController, maxLines: 50, decoration: const InputDecoration( hintText: "what's in your mind?", hintStyle: TextStyle(fontWeight: FontWeight.w200, fontSize: 14.0, color: defaultColor1), border: InputBorder.none, ), ), ), if (cubit.postImage != null) Stack( alignment: AlignmentDirectional.topEnd, children: [ Container( height: 140.0, width: double.infinity, decoration: BoxDecoration( borderRadius: const BorderRadius.only( topLeft: Radius.circular(10.0), topRight: Radius.circular(10.0), ), image: DecorationImage( image: FileImage(cubit.postImage!), fit: BoxFit.cover, ), ), ), IconButton( onPressed: () { cubit.removePostImage(); }, icon: const CircleAvatar( radius: 20.0, backgroundColor: Colors.lightBlue, child: Icon( Icons.close, color: Colors.white, ), ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( onPressed: () { cubit.getPostImage(); }, child: Row( children: [ const Icon(IconBroken.Image_2, size: 30.0), const SizedBox(width: 5.0), Text(LocaleKeys.add_photo.tr(), style: const TextStyle(fontSize: 16.0)), ], ), ), TextButton( onPressed: () {}, child: const Text('# add tag', style: TextStyle(fontSize: 16.0)), ), ], ) ]), ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/full_image/full_image_screen.dart
import 'package:blaze/components/styles/icon_broken.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/models/post.dart'; import 'package:blaze/views/comment_screen/comment_screen.dart'; import 'package:flutter/material.dart'; import 'package:iconsax/iconsax.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FullImageScreen extends StatelessWidget { FullImageScreen({required this.index, required this.post, Key? key}) : super(key: key); SocialPost post; int index; @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return Scaffold( backgroundColor: Colors.black, body: Column( children: [ Expanded( child: Container( decoration: BoxDecoration( image: DecorationImage(image: NetworkImage(post.postImage!)), ), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ IconButton( onPressed: () { cubit.saveImage(post.postImage!); }, icon: const Icon(Iconsax.document_download, color: Colors.white), ), IconButton( onPressed: () { cubit.getCommetns(postId: post.pId!); Navigator.push( context, MaterialPageRoute( builder: (context) => CommentScreen(postId: post.pId!))); }, icon: const Icon(Icons.comment_outlined, color: Colors.white), ), IconButton( onPressed: () { cubit.likePost(post.pId!, cubit.posts[index].likes!, index); }, icon: const Icon(IconBroken.Heart, color: Colors.white), ), ], ) ], ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/notifications/notifications_screen.dart
import 'package:flutter/cupertino.dart'; class NotificationsScreen extends StatelessWidget { const NotificationsScreen({ Key? key }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Text('Notifications'), ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/login/login_screen.dart
import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/local/chache_helper.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../components/const.dart'; import '../../components/default_button.dart'; import '../../components/default_format_field.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import '../../components/toast.dart'; import 'cubit/login_cubit.dart'; import 'cubit/login_state.dart'; import 'package:easy_localization/easy_localization.dart'; class SocialLogin extends StatelessWidget { SocialLogin({Key? key}) : super(key: key); var loginFormKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { var emailController = TextEditingController(); var passwordController = TextEditingController(); return BlocProvider( create: (BuildContext context) => SocialLoginCubit(), child: BlocConsumer<SocialLoginCubit, SocialLoginStates>( listener: (context, state) { if (state is SocialLoginErrorState) { String msg = state.error.substring(state.error.lastIndexOf(']') + 1); showToast(text: msg, state: ToastState.ERROR); } if (state is SocialLoginSuccessState) { CacheHelper.saveData(key: 'uId', value: state.uId).then((value) { uId = CacheHelper.getData(key: 'uId'); SocialCubit.get(context) ..getUserData() ..getPosts() ..getFollowers(); Navigator.pushNamedAndRemoveUntil( context, '/home', (route) => false); }); } }, builder: (context, state) { return Scaffold( body: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.only(left: 20.0, right: 20.0), child: Form( key: loginFormKey, child: Column( children: [ SizedBox( height: MediaQuery.of(context).size.height / 5, child: const Image( image: AssetImage('assets/images/2.png'), fit: BoxFit.cover, ), ), Text( "blaze", style: Theme.of(context) .textTheme .bodyText1! .copyWith(fontSize: 40.0), ), const SizedBox(height: 20.0), Text( LocaleKeys.keep_in.tr(), style: Theme.of(context).textTheme.bodyText1, ), const SizedBox( height: 30.0, ), defaultFormField( context: context, controller: emailController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.email.tr(), prefix: Icons.email_outlined, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.email.tr(); return msg; } return null; }, ), const SizedBox( height: 15.0, ), defaultFormField( context: context, controller: passwordController, keyboardType: TextInputType.visiblePassword, label: LocaleKeys.password.tr(), prefix: Icons.lock_outline, suffix: SocialLoginCubit.get(context).suffix, isPassword: SocialLoginCubit.get(context).showPassword, suffixPressed: () { SocialLoginCubit.get(context) .changePasswordVisibility(); }, onSubmit: (value) { if (loginFormKey.currentState!.validate()) { SocialLoginCubit.get(context).userLogin( email: emailController.text, password: passwordController.text, ); } }, validate: (value) { if (value!.isEmpty) { return 'password is too short'; } return null; }), const SizedBox( height: 30.0, ), ConditionalBuilder( condition: state is! SocialLoginLoadingState, builder: (context) => defaultButton( gradient: const LinearGradient(colors: [ defaultColor1, Colors.orange, ]), text: LocaleKeys.log_in.tr(), isUpperCase: true, function: () { if (loginFormKey.currentState!.validate()) { SocialLoginCubit.get(context).userLogin( email: emailController.text, password: passwordController.text, ); } }), fallback: (context) => const Center( child: Padding( padding: EdgeInsets.all(70.0), child: CircularProgressIndicator(), ), ), ), const SizedBox( height: 30.0, ), defaultButton( gradient: const LinearGradient(colors: [ defaultColor1, Colors.orange, ]), text: LocaleKeys.register.tr(), isUpperCase: true, function: () { Navigator.pushNamed(context, '/register'); }), ], ), ), ), ), ), ); }, ), ); } }
0
mirrored_repositories/blaze/blaze/lib/views/login
mirrored_repositories/blaze/blaze/lib/views/login/cubit/login_cubit.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'login_state.dart'; class SocialLoginCubit extends Cubit<SocialLoginStates> { SocialLoginCubit() : super(SocialLoginInitialState()); static SocialLoginCubit get(context) => BlocProvider.of(context); void userLogin({required String email, required String password}) async { emit(SocialLoginLoadingState()); try { await FirebaseAuth.instance .signInWithEmailAndPassword(email: email, password: password) .then((value) { emit(SocialLoginSuccessState(value.user!.uid)); }).catchError((error) { print(error.toString()); emit(SocialLoginErrorState(error.toString())); }); } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { print('No user found for that email.'); } else if (e.code == 'wrong-password') { print('Wrong password provided for that user.'); } } } IconData suffix = Icons.visibility_outlined; bool showPassword = true; void changePasswordVisibility() { showPassword = !showPassword; suffix = showPassword ? Icons.visibility_outlined : Icons.visibility_off_outlined; emit(SocialChangePasswordVisisbilityState()); } }
0
mirrored_repositories/blaze/blaze/lib/views/login
mirrored_repositories/blaze/blaze/lib/views/login/cubit/login_state.dart
abstract class SocialLoginStates {} class SocialLoginInitialState extends SocialLoginStates {} class SocialLoginLoadingState extends SocialLoginStates {} class SocialLoginSuccessState extends SocialLoginStates { final String uId; SocialLoginSuccessState(this.uId); } class SocialLoginErrorState extends SocialLoginStates { final String error; SocialLoginErrorState(this.error); } class SocialChangePasswordVisisbilityState extends SocialLoginStates {}
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/comment_screen/comment_screen.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/components/default_app_bar.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import '../../components/styles/icon_broken.dart'; import '../../models/comments.dart'; import 'package:easy_localization/easy_localization.dart'; class CommentScreen extends StatelessWidget { CommentScreen({Key? key, required this.postId}) : super(key: key); final String postId; @override Widget build(BuildContext context) { TextEditingController commentController = TextEditingController(); return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return Scaffold( appBar: defaultAppBar( context: context, function: () { cubit.comments.clear(); Navigator.pop(context); }, title: LocaleKeys.comments.tr()), body: state is SocialGetCommentsLoadingState ? const Center(child: CircularProgressIndicator()) : Padding( padding: const EdgeInsets.all(8.0), child: RefreshIndicator( onRefresh: () async { // cubit.refershPage(1); }, child: Column( children: [ ConditionalBuilder( condition: cubit.comments.isNotEmpty, builder: (context) { return Expanded( child: ListView.separated( shrinkWrap: true, physics: const BouncingScrollPhysics(), itemBuilder: (context, index) { return commentItem( cubit.comments[index], context, postId); }, separatorBuilder: (context, index) { return const SizedBox(height: 20.0); }, itemCount: cubit.comments.length, ), ); }, fallback: (context) { return Expanded( child: Center( child: Text(LocaleKeys.no_comments.tr())), ); }, ), if (SocialCubit.get(context).commentImage != null) Stack( alignment: AlignmentDirectional.topEnd, children: [ Container( height: 100.0, width: double.infinity, decoration: BoxDecoration( borderRadius: const BorderRadius.only( topLeft: Radius.circular(10.0), topRight: Radius.circular(10.0), ), image: DecorationImage( image: FileImage( SocialCubit.get(context).commentImage!), fit: BoxFit.contain, ), ), ), IconButton( onPressed: () { SocialCubit.get(context).removeCommentImage(); }, icon: const CircleAvatar( radius: 20.0, backgroundColor: Colors.lightBlue, child: Icon( Icons.close, color: Colors.white, ), ), ), ], ), const SizedBox(height: 5.0), Row( children: [ CircleAvatar( radius: 18.0, backgroundImage: NetworkImage( SocialCubit.get(context).user.image), ), const SizedBox(width: 5.0), Expanded( child: TextFormField( onFieldSubmitted: (value) { if (value.isNotEmpty) { SocialCubit.get(context).addComment( text: value, postId: postId, dateTime: DateTime.now().toString()); commentController.clear(); } }, controller: commentController, style: Theme.of(context).textTheme.caption, decoration: InputDecoration( fillColor: Colors.white, filled: true, hintText: LocaleKeys.comment.tr(), hintStyle: Theme.of(context).textTheme.caption, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(25.0), borderSide: const BorderSide( color: defaultColor1, ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(25.0), borderSide: const BorderSide( color: Colors.grey, width: 1.0, ), ), suffixIcon: IconButton( onPressed: () { SocialCubit.get(context) .getCommentImage(); }, icon: const Icon( IconBroken.Image, color: Colors.black, size: 20, ), ), ), ), ), ], ), ], ), ), ), ); }, ); } } Widget commentItem(SocialComment comment, context, String postId) { TextEditingController commentController = TextEditingController(); return Card( clipBehavior: Clip.antiAliasWithSaveLayer, elevation: 5.0, color: SocialCubit.get(context).isDark ? Color.fromARGB(255, 40, 51, 77): Colors.white, margin: const EdgeInsets.symmetric(horizontal: 8.0), child: Padding( padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ CircleAvatar( radius: 25.0, backgroundImage: NetworkImage(comment.image), ), const SizedBox(width: 15.0), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text( comment.name, style: Theme.of(context).textTheme.bodyText1 ), const SizedBox(width: 5.0), const Icon( Icons.check_circle, color: Colors.lightBlue, size: 16.0, ) ], ), Text( DateFormat("h:mm a d/M/y") .format(DateTime.parse(comment.dateTime)) .toString(), style: Theme.of(context) .textTheme .caption! .copyWith(height: 1.4), ), ], ), ), PopupMenuButton( child: const Icon(IconBroken.More_Circle), itemBuilder: (context) { return <PopupMenuItem<String>>[ PopupMenuItem<String>( child: TextButton( onPressed: () { SocialCubit.get(context) .deleteComment(comment, postId); }, child: Text(LocaleKeys.delete_comment.tr()))), ]; }, ) ], ), Padding( padding: const EdgeInsets.symmetric(vertical: 15.0), child: Container( width: double.infinity, height: 1.0, color: Colors.grey[300]), ), Text(comment.text, style: Theme.of(context).textTheme.subtitle1), if (comment.commentImage != null) Padding( padding: const EdgeInsets.only(top: 8.0), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Image( image: NetworkImage(comment.commentImage!), ), ), ), ], ), ), ); }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/profile/profile_screen.dart
import 'package:blaze/components/default_post.dart'; import 'package:blaze/components/styles/icon_broken.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import 'package:iconsax/iconsax.dart'; import 'package:easy_localization/easy_localization.dart'; import '../../components/const.dart'; import '../../components/default_button.dart'; class ProfileScreen extends StatelessWidget { const ProfileScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, states) {}, builder: (context, states) { var cubit = SocialCubit.get(context); return Scaffold( body: RefreshIndicator( onRefresh: () async { cubit.refershPage(3); }, child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: Column( children: [ SizedBox( height: 200, child: Stack( alignment: AlignmentDirectional.bottomCenter, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Align( child: Container( height: 160.0, width: double.infinity, clipBehavior: Clip.antiAlias, child: FadeInImage( placeholder: const AssetImage('assets/images/3.png'), image: NetworkImage( cubit.user.cover, ), fit: BoxFit.cover, ), decoration: const BoxDecoration( borderRadius: BorderRadius.only( bottomRight: Radius.circular( 15.0, ), bottomLeft: Radius.circular( 15.0, ), ), ), ), alignment: AlignmentDirectional.topCenter, ), ), CircleAvatar( radius: 64.0, backgroundColor: Theme.of(context).scaffoldBackgroundColor, child: CircleAvatar( radius: 60.0, backgroundImage: NetworkImage( cubit.user.image, ), ), ), ], ), ), const SizedBox( height: 5.0, ), Text( cubit.user.name, style: Theme.of(context).textTheme.bodyText1, ), Text( cubit.user.bio, style: Theme.of(context).textTheme.caption, ), Padding( padding: const EdgeInsets.symmetric( vertical: 20.0, ), child: Row( children: [ Expanded( child: InkWell( child: Column( children: [ Text( cubit.userPosts.length.toString(), style: Theme.of(context).textTheme.subtitle1, ), Text( LocaleKeys.posts.tr(), style: Theme.of(context).textTheme.caption, ), ], ), onTap: () {}, ), ), Expanded( child: InkWell( child: Column( children: [ Text( cubit.user.followers.toString(), style: Theme.of(context).textTheme.subtitle1, ), Text( LocaleKeys.followers.tr(), style: Theme.of(context).textTheme.caption, ), ], ), onTap: () {}, ), ), Expanded( child: InkWell( child: Column( children: [ Text( cubit.followers.length.toString(), style: Theme.of(context).textTheme.subtitle1, ), Text( LocaleKeys.following.tr(), style: Theme.of(context).textTheme.caption, ), ], ), onTap: () {}, ), ), ], ), ), Row( children: [ const SizedBox( width: 10.0, ), Expanded( child: OutlinedButton( onPressed: () { Navigator.pushNamed(context, '/new_post'); }, child: Text( LocaleKeys.create_post.tr(), ), ), ), const SizedBox( width: 10.0, ), OutlinedButton( onPressed: () { Navigator.pushNamed(context, '/edit_profile'); cubit.coverImage = null; cubit.profileImage = null; }, child: const Icon( IconBroken.Edit, size: 16.0, ), ), const SizedBox( width: 10.0, ), OutlinedButton( onPressed: () { //Navigator.pushNamed(context, '/settings'); showModalBottomSheet( backgroundColor: cubit.isDark ? const Color(0xFF202A44) : defaultColor4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), clipBehavior: Clip.antiAlias, elevation: 5.0, context: context, builder: (context) { return Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const Divider( color: Colors.black, thickness: 5.0, indent: 150.0, endIndent: 150.0, ), const SizedBox(height: 10.0), defaultButton( function: () { cubit.logOut(context); }, text: LocaleKeys.log_out.tr(), ), const SizedBox(height: 10.0), defaultButton( function: () { cubit.changeAppMode( fromShared: !cubit.isDark); }, text: cubit.isDark ? LocaleKeys.light_mode.tr() : LocaleKeys.dark_mode.tr()), const SizedBox(height: 20.0), Text( LocaleKeys.change_lang.tr(), style: Theme.of(context) .textTheme .bodyText1 ), const SizedBox(height: 20.0), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all< RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular( 20.0), ), ), fixedSize: MaterialStateProperty.all( const Size(100, 50))), onPressed: () async { cubit.changeLanguage('ar'); cubit.isSelected[0] = true; cubit.isSelected[1] = false; await context.setLocale( const Locale('ar')); }, child: const Text('العربية', style: TextStyle( color: Colors.white)), ), const SizedBox(width: 20.0), ElevatedButton( style: ButtonStyle( fixedSize: MaterialStateProperty.all( const Size(100, 50)), shape: MaterialStateProperty.all< RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular( 20.0), ), )), onPressed: () async { cubit.changeLanguage('en'); cubit.isSelected[1] = true; cubit.isSelected[0] = false; await context.setLocale( const Locale('en')); }, child: const Text('English', style: TextStyle( color: Colors.white)), ), ], ), const SizedBox(height: 10.0), ], ), ); }); }, child: const Icon( Iconsax.setting, size: 16.0, ), ), const SizedBox( width: 10.0, ), ], ), const Divider( thickness: 5.0, ), ConditionalBuilder( condition: cubit.userPosts.isNotEmpty, builder: (context) { return ListView.separated( shrinkWrap: true, physics: const ClampingScrollPhysics(), itemBuilder: (context, index) => buildPostItem( cubit.userPosts[index], context, index), separatorBuilder: (context, index) => const Divider(thickness: 8.0), itemCount: cubit.userPosts.length, ); }, fallback: (context) { return const Center(child: CircularProgressIndicator()); }, ), ], ), ), ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/chat_details/chat_details.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/models/message.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; import '../../components/styles/icon_broken.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import '../../models/user.dart'; import 'package:easy_localization/easy_localization.dart'; final TextEditingController messageController = TextEditingController(); class ChatDetailsScreen extends StatelessWidget { ChatDetailsScreen({required this.receiver, Key? key}) : super(key: key); SocialUser receiver; @override Widget build(BuildContext context) { SocialCubit.get(context).getMessages(receiverId: receiver.uId); return Builder( builder: (context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return SafeArea( child: Scaffold( appBar: AppBar( titleSpacing: 0.0, leading: IconButton( icon: const Icon(IconBroken.Arrow___Left_2), onPressed: () { Navigator.pop(context); }, ), title: Padding( padding: const EdgeInsets.only(top: 8.0), child: Row( children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(100.0), color: defaultColor2, ), padding: const EdgeInsetsDirectional.all(2.0), child: CircleAvatar( radius: 20.0, backgroundImage: NetworkImage(receiver.image), ), ), const SizedBox(width: 15.0), Text( receiver.name, style: Theme.of(context) .textTheme .subtitle1! .copyWith(fontSize: 20.0), ), ], ), ), ), body: Padding( padding: const EdgeInsets.only( top: 15.0, left: 15.0, right: 15.0, bottom: 5.0), child: Column( children: [ ConditionalBuilder( condition: cubit.messages.isNotEmpty, builder: (contxt) { return Expanded( child: ListView.separated( itemBuilder: (context, index) { SocialMessage message = cubit.messages[index]; if (message.senderId == cubit.user.uId) { return MyMessage(message: message); } else { return Message(message: message); } }, separatorBuilder: (context, index) { return const SizedBox(height: 5.0); }, itemCount: cubit.messages.length), ); }, fallback: (context) => Expanded( child: Center( child: Text( LocaleKeys.no_message.tr(), style: TextStyle( fontSize: 24, color: Colors.grey.shade600, ), ), ), ), ), Row( children: [ Expanded( child: TextFormField( controller: messageController, style: const TextStyle(color: Colors.white), decoration: InputDecoration( hintText: LocaleKeys.type_message.tr(), hintStyle: const TextStyle(color: Colors.white), fillColor: defaultColor2, filled: true, labelStyle: TextStyle(color: Colors.white), ), ), ), const SizedBox(width: 5.0), CircleAvatar( backgroundColor: defaultColor1, radius: 25.0, child: MaterialButton( onPressed: () { cubit.sendMessage( receiver.uId, DateTime.now().toString(), messageController.text); messageController.clear(); }, child: const Icon(Icons.send, size: 20.0, color: Colors.white), ), ) ], ), ], ), ), ), ); }, ); }, ); } } class MyMessage extends StatelessWidget { MyMessage({ required this.message, Key? key, }) : super(key: key); SocialMessage message; @override Widget build(BuildContext context) { return Align( alignment: Alignment.bottomLeft, child: Container( padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0), decoration: const BoxDecoration( color: defaultColor4, borderRadius: BorderRadiusDirectional.only( bottomEnd: Radius.circular(10.0), topStart: Radius.circular(10.0), topEnd: Radius.circular(10.0), )), child: Wrap( crossAxisAlignment: WrapCrossAlignment.end, children: [ Text(message.text, style: const TextStyle(fontSize: 17.0)), const SizedBox(width: 3.0), Text(DateFormat("h:mm a").format(DateTime.parse(message.dateTime)).toString() , style: const TextStyle(fontSize: 8.0)), ], ), ), ); } } class Message extends StatelessWidget { Message({ required this.message, Key? key, }) : super(key: key); SocialMessage message; @override Widget build(BuildContext context) { return Align( alignment: Alignment.bottomRight, child: Container( padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 15.0), decoration: BoxDecoration( color: defaultColor3.withOpacity(0.5), borderRadius: const BorderRadiusDirectional.only( bottomStart: Radius.circular(10.0), topStart: Radius.circular(10.0), topEnd: Radius.circular(10.0), )), child: Wrap( crossAxisAlignment: WrapCrossAlignment.end, children: [ Text(message.text, style: const TextStyle(fontSize: 17.0)), const SizedBox(width: 3.0), Text(DateFormat("h:mm a").format(DateTime.parse(message.dateTime)).toString() , style: const TextStyle(fontSize: 8.0)), ], ), ), ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/social_layout/social_layout.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/components/styles/icon_broken.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:iconsax/iconsax.dart'; import 'package:google_fonts/google_fonts.dart'; class SocialLayout extends StatefulWidget { SocialLayout({Key? key}) : super(key: key); @override State<SocialLayout> createState() => _SocialLayoutState(); } class _SocialLayoutState extends State<SocialLayout> with SingleTickerProviderStateMixin { late TabController tabController; @override void initState() { super.initState(); tabController = TabController(vsync: this, length: 4); tabController.addListener(() { setState(() {}); }); } @override void dispose() { tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: ((context, state) {}), builder: (context, state) { var cubit = SocialCubit.get(context); return Scaffold( appBar: AppBar( title: Row( children: [ const SizedBox(child: Image(image: AssetImage('assets/images/2.png'), fit: BoxFit.cover), width: 35.0, height: 35.0), const SizedBox(width: 5.0), Text(cubit.titles[tabController.index], style: GoogleFonts.laila().copyWith(fontSize: 20.0)), ], ), bottom: TabBar( controller: tabController, labelColor: defaultColor1, unselectedLabelColor: Colors.grey, tabs: const [ Tab(icon: Icon(Iconsax.home, size: 30)), Tab(icon: Icon(Iconsax.discover_13, size: 30)), Tab(icon: Icon(Iconsax.message, size: 30)), Tab(icon: Icon(IconBroken.Profile, size: 30)), ], onTap: (index) { print(index); cubit.changeNav(index); }, ), actions: [ IconButton( onPressed: () { Navigator.pushNamed(context, '/search'); }, icon: const Icon(IconBroken.Search)), IconButton( onPressed: () {}, icon: const Icon(IconBroken.Notification, size: 30.0)), ], ), body: TabBarView( children: cubit.screens, controller: tabController, ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/on_boarding/on_boarding_screen.dart
import 'package:blaze/components/default_text_button.dart'; import 'package:blaze/helpers/local/chache_helper.dart'; import 'package:blaze/models/on_barding.dart'; import 'package:flutter/material.dart'; import 'package:smooth_page_indicator/smooth_page_indicator.dart'; import '../../components/const.dart'; class OnBoarding extends StatefulWidget { const OnBoarding({Key? key}) : super(key: key); @override State<OnBoarding> createState() => _OnBoardingState(); } class _OnBoardingState extends State<OnBoarding> { PageController boardController = PageController(); bool isLast = false; Icon icon = const Icon(Icons.arrow_forward_ios); void submit() { CacheHelper.saveData( key: 'onBoarding', value: true, ).then((value) { if (value) { Navigator.pushNamedAndRemoveUntil( context, '/login', (Route<dynamic> route) => false); } }); } List<BoardingModel> boarding = [ BoardingModel( image: 'assets/images/onboard_1.png', title: 'Welcome to blaze', body: 'Share with the world your beauty'), BoardingModel( image: 'assets/images/onboard_2.png', body: 'Keeping up with friends is faster \n and easier than ever.', title: 'Hi There!'), BoardingModel( image: 'assets/images/onboard_3.png', body: 'Share updates and photos,\n engage with friends and Pages', title: 'Keep in touch'), BoardingModel( image: 'assets/images/onboard_4.png', body: 'join our community now', title: 'ARE YOU READY'), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ defaultTextButton( function: submit, text: 'skip', ) ], ), body: Padding( padding: const EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 20.0), child: Column( children: [ Expanded( child: PageView.builder( physics: ClampingScrollPhysics(), controller: boardController, onPageChanged: (int index) { if (index == boarding.length - 1) { setState(() { isLast = true; icon = const Icon(Icons.login); }); } else { setState(() { isLast = false; icon = const Icon(Icons.arrow_forward_ios); }); } }, itemBuilder: (context, index) => buildBoardingItem(boarding[index]), itemCount: boarding.length, ), ), const SizedBox( height: 40, ), Row( children: [ SmoothPageIndicator( controller: boardController, count: boarding.length, effect: const ExpandingDotsEffect( dotWidth: 10.0, radius: 16.0, dotHeight: 12.0, dotColor: Colors.grey, strokeWidth: 10, activeDotColor: defaultColor1, )), const Spacer(), FloatingActionButton( onPressed: () { if (isLast) { submit(); } else { boardController.nextPage( duration: const Duration(microseconds: 750), curve: Curves.fastLinearToSlowEaseIn); } }, child: icon, ) ], ) ], ), )); } Widget buildBoardingItem(BoardingModel model) => Column( children: [ Expanded(child: Image(image: AssetImage(model.image))), Text( model.title, style: Theme.of(context).textTheme.bodyText1!.copyWith(fontSize: 30.0) ), const SizedBox( height: 30, ), Text( model.body, style: Theme.of(context).textTheme.subtitle1, ), const SizedBox( height: 30, ), ], ); }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/home/home_screen.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/components/toast.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/models/user.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import '../../components/default_post.dart'; import 'package:easy_localization/easy_localization.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>(listener: (context, state) { if (state is SocialCommentPostsSuccessState) { showToast( text: LocaleKeys.comment_successfully.tr(), state: ToastState.SUCCESS); } if (state is SocialCommentPostsErrorState) { showToast(text: state.error, state: ToastState.ERROR); } }, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return NotificationListener<UserScrollNotification>( onNotification: (notification) { if (notification.direction == ScrollDirection.forward && !cubit.isFabVisible) { cubit.changeHomeFab(true); } else if (notification.direction == ScrollDirection.reverse && cubit.isFabVisible) { cubit.changeHomeFab(false); } return true; }, child: Scaffold( floatingActionButton: cubit.isFabVisible ? FloatingActionButton( onPressed: () { Navigator.pushNamed(context, '/new_post'); }, child: const Icon(Icons.post_add), ) : null, body: ConditionalBuilder( condition: cubit.posts.isNotEmpty && cubit.user != SocialUser.empty(), builder: (context) { return RefreshIndicator( onRefresh: () async { cubit.refershPage(0); }, child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), child: Column( mainAxisSize: MainAxisSize.min, children: [ Card( clipBehavior: Clip.antiAliasWithSaveLayer, elevation: 5.0, margin: const EdgeInsets.all(8.0), child: Stack( alignment: Alignment.bottomLeft, children: [ const FadeInImage( placeholder: AssetImage('assets/images/3.png'), image: NetworkImage( 'https://img.freepik.com/free-photo/students-giving-five_23-2147663448.jpg?w=900'), fit: BoxFit.cover, height: 200.0, width: double.infinity, ), Padding( padding: const EdgeInsets.all(10.0), child: Text(LocaleKeys.keep_in.tr(), style: const TextStyle( fontSize: 11.5, color: Colors.white, shadows: [ Shadow( offset: Offset(-1, -1), color: Colors.black), Shadow( offset: Offset(1, -1), color: Colors.black), Shadow( offset: Offset(1, 1), color: Colors.black), Shadow( offset: Offset(-1, 1), color: Colors.black), ], fontWeight: FontWeight.bold), ), ), ], ), ), Padding( padding: const EdgeInsets.only( bottom: 10.0, right: 5, left: 5), child: SizedBox( height: 60.0, child: Card( color: cubit.isDark ? Colors.grey : Colors.white, elevation: 5.0, child: InkWell( child: Row( children: [ const SizedBox(width: 10.0), Container( padding: const EdgeInsets.all(2.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(100.0), color: Colors.black, ), child: CircleAvatar( radius: 18.0, backgroundImage: NetworkImage(cubit.user.image), ), ), const SizedBox(width: 15.0), Container( padding: const EdgeInsets.all(10.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(30.0), color: cubit.isDark ? Colors.grey : Colors.white, ), child: Text("what's in your mind?", style: Theme.of(context).textTheme.subtitle1, ), ), const Spacer(), const Icon( Icons.post_add, size: 30.0, ), const SizedBox(width: 15.0), ], ), onTap: () { Navigator.pushNamed(context, '/new_post'); }, ), ), ), ), ConditionalBuilder( condition: cubit.posts.isNotEmpty && cubit.user != null, builder: (context) { return ListView.separated( shrinkWrap: true, physics: const ClampingScrollPhysics(), itemBuilder: (context, index) => buildPostItem( cubit.posts[index], context, index), separatorBuilder: (context, index) => const Divider(thickness: 8.0), itemCount: cubit.posts.length, ); }, fallback: (context) { return const Center( child: CircularProgressIndicator()); }, ), const SizedBox(height: 10.0), ], ), ), ); }, fallback: (context) { return const Center(child: CircularProgressIndicator()); }, ), ), ); }); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/edit_profile/edit_profile.dart
import 'package:blaze/components/default_app_bar.dart'; import 'package:blaze/components/default_text_button.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../components/default_format_field.dart'; import '../../components/styles/icon_broken.dart'; import 'package:easy_localization/easy_localization.dart'; class EditProfileScreen extends StatelessWidget { const EditProfileScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { TextEditingController bioController = TextEditingController(); TextEditingController phoneController = TextEditingController(); TextEditingController nameController = TextEditingController(); return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); nameController.text = cubit.user.name; bioController.text = cubit.user.bio; phoneController.text = cubit.user.phone; return Scaffold( appBar: defaultAppBar(context: context, function: (){ cubit.coverImage = null; cubit.profileImage = null; Navigator.pop(context); } , title: LocaleKeys.edit_profile.tr(), actions: [ defaultTextButton(function: (){ if(cubit.coverImage != null){ cubit.uploadCoverImage(name: nameController.text, phone: phoneController.text, bio: bioController.text); } if(cubit.profileImage != null){ cubit.uploadProfileImage(name: nameController.text, phone: phoneController.text, bio: bioController.text); } if(cubit.profileImage == null && cubit.coverImage == null){ cubit.updateUser(name: nameController.text, phone: phoneController.text, bio: bioController.text); } }, text: LocaleKeys.update.tr()), const SizedBox(width: 5.0), ]), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ if(state is SocialUploadImageErrorState || state is SocialUserUpdateLoadingState) const LinearProgressIndicator(), const SizedBox(height: 5.0), SizedBox( height: 190.0, child: Stack( alignment: AlignmentDirectional.bottomCenter, children: [ Align( child: Stack( alignment: AlignmentDirectional.topEnd, children: [ Container( height: 140.0, width: double.infinity, decoration: BoxDecoration( borderRadius: const BorderRadius.only( topLeft: Radius.circular( 10.0, ), topRight: Radius.circular( 10.0, ), ), image: DecorationImage( image: cubit.coverImage == null ? NetworkImage(cubit.user.cover) : FileImage(cubit.coverImage!) as ImageProvider, fit: BoxFit.cover, ), ), ), IconButton( onPressed: () { cubit.getCoverImage(); }, icon: const CircleAvatar( radius: 20.0, backgroundColor: Colors.lightBlue, child: Icon( IconBroken.Camera, color: Colors.white, ), ), ), ], ), alignment: AlignmentDirectional.topCenter, ), Stack( alignment: AlignmentDirectional.bottomEnd, children: [ CircleAvatar( radius: 64.0, backgroundColor: Theme.of(context).scaffoldBackgroundColor, child: CircleAvatar( radius: 60.0, backgroundImage: cubit.profileImage == null ? NetworkImage(cubit.user.image) : FileImage(cubit.profileImage!) as ImageProvider, ), ), IconButton( onPressed: () { cubit.getProfileImage(); }, icon: const CircleAvatar( radius: 20.0, backgroundColor: Colors.lightBlue, child: Icon( IconBroken.Camera, color: Colors.white, ), ), ), ], ), ], ), ), const SizedBox( height: 20.0, ), defaultFormField( context: context, controller: nameController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.name.tr(), prefix: IconBroken.User, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.name.tr(); return msg; } return null; }, ), const SizedBox( height: 20.0, ), defaultFormField( context: context, controller: bioController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.bio.tr(), prefix: IconBroken.Info_Circle, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.bio.tr(); return msg; } return null; }, ), const SizedBox( height: 20.0, ), defaultFormField( context: context, controller: phoneController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.phone.tr(), prefix: IconBroken.Call, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.password.tr(); return msg; } return null; }, ), ], ), ), ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/user_screen/user_screen.dart
import 'package:blaze/components/default_app_bar.dart'; import 'package:blaze/components/default_button.dart'; import 'package:blaze/components/default_post.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/models/user.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import 'package:easy_localization/easy_localization.dart'; class UserScreen extends StatelessWidget { UserScreen({required this.user, Key? key}) : super(key: key); SocialUser user; @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { var cubit = SocialCubit.get(context); return Scaffold( appBar: defaultAppBar( context: context, function: () { Navigator.pop(context); }), body: Padding( padding: const EdgeInsets.all(10.0), child: SingleChildScrollView( child: Column( children: [ SizedBox( height: 200.0, child: Stack( alignment: AlignmentDirectional.bottomStart, children: [ Align( child: Container( height: 140.0, width: double.infinity, decoration: BoxDecoration( borderRadius: const BorderRadius.all( Radius.circular( 10.0, ), ), image: DecorationImage( image: NetworkImage( user.cover, ), fit: BoxFit.cover, ), ), ), alignment: AlignmentDirectional.topCenter, ), CircleAvatar( radius: 64.0, backgroundColor: Theme.of(context).scaffoldBackgroundColor, child: CircleAvatar( radius: 60.0, backgroundImage: NetworkImage( user.image, ), ), ), ], ), ), const SizedBox( height: 10.0, ), Text( user.name, style: Theme.of(context).textTheme.bodyText1, ), const SizedBox( height: 5.0, ), Text( user.bio, style: Theme.of(context).textTheme.caption, ), Padding( padding: const EdgeInsets.symmetric( vertical: 20.0, ), child: Row( children: [ Expanded( child: Column( children: [ Text( cubit.userPosts.length.toString(), style: Theme.of(context).textTheme.subtitle1, ), Text( LocaleKeys.posts.tr(), style: Theme.of(context).textTheme.caption, ), ], ), ), Expanded( child: Column( children: [ Text( user.followers.toString(), style: Theme.of(context).textTheme.subtitle1, ), Text( LocaleKeys.followers.tr(), style: Theme.of(context).textTheme.caption, ), ], ), ), Expanded( child: Column( children: [ Text( cubit.followers.length.toString(), style: Theme.of(context).textTheme.subtitle1, ), Text( LocaleKeys.following.tr(), style: Theme.of(context).textTheme.caption, ), ], ), ), ], ), ), Row( children: [ cubit.followers.indexWhere( (element) => element.uId == user.uId) != -1 ? Expanded( child: defaultButton( text: LocaleKeys.unfollow.tr(), function: () { cubit.unfollow(user.uId); }), ) : Expanded( child: defaultButton( text: LocaleKeys.follow.tr(), function: () { cubit.follow(user.uId); }), ), ], ), const SizedBox(height: 10.0), ConditionalBuilder( condition: cubit.userPosts.isNotEmpty && cubit.user != null, builder: (context) { return ListView.separated( shrinkWrap: true, physics: const ClampingScrollPhysics(), itemBuilder: (context, index) => buildPostItem( cubit.userPosts[index], context, index), separatorBuilder: (context, index) => const Divider(thickness: 8.0), itemCount: cubit.userPosts.length, ); }, fallback: (context) { return const Padding( padding: EdgeInsets.all(10.0), child: Center(child: CircularProgressIndicator()), ); }, ), ], ), ), ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/users/users_screen.dart
import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/views/user_screen/user_screen.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import '../../components/styles/icon_broken.dart'; class UsersScreen extends StatelessWidget { const UsersScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return Scaffold( body: ConditionalBuilder( condition: cubit.allUsers.isNotEmpty, builder: (context) { return RefreshIndicator( onRefresh: () async { cubit.refershPage(1); }, child: SizedBox( height: MediaQuery.of(context).size.height, child: ListView.separated( shrinkWrap: true,physics: const AlwaysScrollableScrollPhysics(), itemBuilder: (context, index) { return UserItem(cubit: cubit, index: index); }, separatorBuilder: (context, index) { return const Divider(); }, itemCount: cubit.allUsers.length, ), ), ); }, fallback: (context) { return const Center(child: CircularProgressIndicator()); }, ), ); }, ); } } class UserItem extends StatelessWidget { const UserItem({ Key? key, required this.cubit, required this.index, }) : super(key: key); final SocialCubit cubit; final int index; @override Widget build(BuildContext context) { return InkWell( onTap: () { cubit.getUserPosts(id: cubit.allUsers[index].uId); Navigator.push( context, MaterialPageRoute( builder: (context) => UserScreen(user: cubit.allUsers[index])), ); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), child: Row( children: [ CircleAvatar( radius: 25.0, backgroundImage: NetworkImage(cubit.allUsers[index].image), ), const SizedBox(width: 15.0), Expanded( child: Row( children: [ Text( cubit.allUsers[index].name, style: Theme.of(context).textTheme.bodyText1 ), const SizedBox(width: 5.0), const Icon( Icons.check_circle, color: Colors.lightBlue, size: 16.0, ) ], ), ), const SizedBox(width: 15.0), IconButton( onPressed: () { cubit.follow(cubit.allUsers[index].uId); }, icon: const Icon(IconBroken.Add_User)), ], ), ), ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/register/register_screen.dart
import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../components/const.dart'; import '../../components/default_button.dart'; import '../../components/default_format_field.dart'; import '../../components/styles/icon_broken.dart'; import '../../components/toast.dart'; import '../../helpers/local/chache_helper.dart'; import 'cubit/register_cubit.dart'; import 'cubit/register_state.dart'; import 'package:easy_localization/easy_localization.dart'; class RegisterScreen extends StatelessWidget { RegisterScreen({Key? key}) : super(key: key); var registerFormKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { var emailController = TextEditingController(); var phoneController = TextEditingController(); var nameController = TextEditingController(); var passwordController = TextEditingController(); return BlocProvider( create: (BuildContext context) => RegisterCubit(), child: BlocConsumer<RegisterCubit, RegisterStates>( listener: (context, state) { if (state is CreateUserErrorState) { String msg = state.error.substring(state.error.lastIndexOf(']') + 1); showToast(text: msg, state: ToastState.ERROR); } if (state is CreateUserSuccessState) { CacheHelper.saveData(key: 'uId', value: state.uId).then((value) { uId = CacheHelper.getData(key: 'uId'); SocialCubit.get(context) ..getUserData() ..getPosts() ..getAllUsers() ..getFollowers(); Navigator.pushNamedAndRemoveUntil( context, '/home', (route) => false); }); } }, builder: (context, state) { return SafeArea( child: Scaffold( body: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20.0), child: Form( key: registerFormKey, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( height: MediaQuery.of(context).size.height / 5, child: const Image( image: AssetImage('assets/images/2.png'), fit: BoxFit.cover, ), ), const SizedBox(height: 20), Text( LocaleKeys.join_now.tr(), style: Theme.of(context).textTheme.bodyText1, ), const SizedBox( height: 30.0, ), defaultFormField( context: context, controller: nameController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.name.tr(), prefix: IconBroken.User, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.name.tr(); return msg; } return null; }, ), const SizedBox( height: 30.0, ), defaultFormField( context: context, controller: emailController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.email.tr(), prefix: Icons.email_outlined, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.email.tr(); return msg; } return null; }, ), const SizedBox( height: 30.0, ), defaultFormField( context: context, controller: phoneController, keyboardType: TextInputType.emailAddress, label: LocaleKeys.phone.tr(), prefix: IconBroken.Call, validate: (value) { if (value!.isEmpty) { String msg = LocaleKeys.please.tr() + LocaleKeys.phone.tr(); return msg; } return null; }, ), const SizedBox( height: 30.0, ), defaultFormField( context: context, controller: passwordController, keyboardType: TextInputType.visiblePassword, label: LocaleKeys.password.tr(), prefix: Icons.lock_outline, suffix: RegisterCubit.get(context).suffix, isPassword: RegisterCubit.get(context).showPassword, suffixPressed: () { RegisterCubit.get(context) .changePasswordVisibility(); }, onSubmit: (value) { if (registerFormKey.currentState!.validate()) {} }, validate: (value) { if (value!.isEmpty) { return 'password is too short'; } return null; }), const SizedBox( height: 30.0, ), ConditionalBuilder( condition: state is! RegisterLoadingState, builder: (context) => defaultButton( gradient: const LinearGradient(colors: [ defaultColor1, Colors.orange, ]), text: LocaleKeys.register.tr(), isUpperCase: true, function: () { if (registerFormKey.currentState! .validate()) { RegisterCubit.get(context).userRegister( email: emailController.text, password: passwordController.text, name: nameController.text, phone: phoneController.text, ); } }), fallback: (context) => const Center( child: Padding( padding: EdgeInsets.all(100.0), child: LinearProgressIndicator(), ), ), ), ], ), ), ), ), ), ), ); }, ), ); } }
0
mirrored_repositories/blaze/blaze/lib/views/register
mirrored_repositories/blaze/blaze/lib/views/register/cubit/register_state.dart
abstract class RegisterStates {} class RegisterInitialState extends RegisterStates {} class RegisterLoadingState extends RegisterStates {} class RegisterSuccessState extends RegisterStates {} class RegisterErrorState extends RegisterStates { final String error; RegisterErrorState(this.error); } class CreateUserSuccessState extends RegisterStates { final String uId; CreateUserSuccessState(this.uId); } class CreateUserErrorState extends RegisterStates { final String error; CreateUserErrorState(this.error); } class RegisterePasswordVisisbilityState extends RegisterStates {}
0
mirrored_repositories/blaze/blaze/lib/views/register
mirrored_repositories/blaze/blaze/lib/views/register/cubit/register_cubit.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'register_state.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:blaze/models/user.dart'; class RegisterCubit extends Cubit<RegisterStates> { RegisterCubit() : super(RegisterInitialState()); static RegisterCubit get(context) => BlocProvider.of(context); void userRegister({required String email, required String password, required String name, required String phone}){ emit(RegisterLoadingState()); FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password) .then((value){ userCreate(email: email, uId: value.user!.uid, name: name, phone: phone); }) .catchError((error){ print(error.toString()); emit(RegisterErrorState(error.toString())); }); } void userCreate({required String email, required String uId, required String name, required String phone}){ SocialUser user = SocialUser( followers: 0, email: email, uId: uId, name: name, phone: phone, image: 'https://cbcs.ac.in/wp-content/uploads/2020/10/placeholder.jpg', bio: 'write you bio ...', cover: 'https://image.freepik.com/free-photo/photo-attractive-bearded-young-man-with-cherful-expression-makes-okay-gesture-with-both-hands-likes-something-dressed-red-casual-t-shirt-poses-against-white-wall-gestures-indoor_273609-16239.jpg', ); FirebaseFirestore.instance.collection('users') .doc(uId) .set(user.toJson()) .then((value){ emit(CreateUserSuccessState(uId)); }) .catchError((error){ emit(CreateUserErrorState(error.toString())); }); } IconData suffix = Icons.visibility_outlined; bool showPassword = true; void changePasswordVisibility() { showPassword = !showPassword; suffix = showPassword ? Icons.visibility_outlined : Icons.visibility_off_outlined; emit(RegisterePasswordVisisbilityState()); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/settings/settings_screen.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/components/default_app_bar.dart'; import 'package:blaze/components/default_button.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/easy_localization.dart'; class SettingsScreen extends StatelessWidget { const SettingsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return Scaffold( appBar: defaultAppBar( context: context, function: () { Navigator.pop(context); }, title: LocaleKeys.settings.tr()), body: Padding( padding: const EdgeInsets.all(8.0), child: SingleChildScrollView( child: Column( children: [ defaultButton( function: () { cubit.logOut(context); }, text: LocaleKeys.log_out.tr(), ), const SizedBox(height: 10.0), defaultButton(function: (){ cubit.changeAppMode(fromShared: !cubit.isDark); }, text: cubit.isDark ? LocaleKeys.light_mode.tr() : LocaleKeys.dark_mode.tr() ), const SizedBox(height: 20.0), Text(LocaleKeys.change_lang.tr(), style: Theme.of(context).textTheme.bodyText1!.copyWith(color: defaultColor1),), const SizedBox(height: 20.0), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all< RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), ), fixedSize: MaterialStateProperty.all( const Size(100, 50))), onPressed: () async { cubit.changeLanguage('ar'); cubit.isSelected[0] = true; cubit.isSelected[1] = false; await context.setLocale(const Locale('ar')); }, child: const Text('العربية', style: TextStyle(color: Colors.white)), ), const SizedBox(width: 20.0), ElevatedButton( style: ButtonStyle( fixedSize: MaterialStateProperty.all( const Size(100, 50)), shape: MaterialStateProperty.all< RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), )), onPressed: () async { cubit.changeLanguage('en'); cubit.isSelected[1] = true; cubit.isSelected[0] = false; await context.setLocale(const Locale('en')); }, child: const Text('English', style: TextStyle(color: Colors.white)), ), ], ), ], ), ), ), ); }, ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/chats/chats_screen.dart
import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:blaze/views/chat_details/chat_details.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import '../../components/styles/icon_broken.dart'; import 'package:easy_localization/easy_localization.dart'; class ChatsScreen extends StatelessWidget { const ChatsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return Scaffold( body: state is SocialGetFollowersLoadingState ? const Center(child: CircularProgressIndicator()) : SizedBox( height: MediaQuery.of(context).size.height, child: RefreshIndicator( onRefresh: () async { cubit.refershPage(2); }, child: ConditionalBuilder( condition: cubit.followers.isNotEmpty, builder: (context) { return ListView.separated( shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(), itemBuilder: (context, index) { return ChatItem(cubit: cubit, index: index); }, separatorBuilder: (context, index) { return const Divider(); }, itemCount: cubit.followers.length, ); }, fallback: (context) { return Center( child: Text(LocaleKeys.no_follow.tr())); }, ), ), ), ); }, ); } } class ChatItem extends StatelessWidget { const ChatItem({ Key? key, required this.cubit, required this.index, }) : super(key: key); final SocialCubit cubit; final int index; @override Widget build(BuildContext context) { return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ChatDetailsScreen(receiver: cubit.followers[index])), ); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0), child: Row( children: [ CircleAvatar( radius: 25.0, backgroundImage: NetworkImage(cubit.followers[index].image), ), const SizedBox(width: 15.0), Expanded( child: Row( children: [ Text( cubit.followers[index].name, style: Theme.of(context).textTheme.bodyText1 ), const SizedBox(width: 5.0), const Icon( Icons.check_circle, color: Colors.lightBlue, size: 16.0, ) ], ), ), const SizedBox(width: 15.0), IconButton( onPressed: () { cubit.unfollow(cubit.followers[index].uId); }, icon: const Icon(IconBroken.Delete)), ], ), ), ); } }
0
mirrored_repositories/blaze/blaze/lib/views
mirrored_repositories/blaze/blaze/lib/views/search/search_screen.dart
import 'package:blaze/components/default_app_bar.dart'; import 'package:blaze/components/default_format_field.dart'; import 'package:blaze/components/styles/icon_broken.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/helpers/cubits/social_state.dart'; import 'package:blaze/views/user_screen/user_screen.dart'; import 'package:blaze/views/users/users_screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter/material.dart'; class SearchScreen extends StatelessWidget { const SearchScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SocialCubit, SocialStates>( listener: (context, state) {}, builder: (context, state) { SocialCubit cubit = SocialCubit.get(context); return Scaffold( appBar: defaultAppBar( context: context, function: () { cubit.searchResualt = []; Navigator.pop(context); }, title: 'search'), body: Padding( padding: const EdgeInsets.all(8.0), child: SingleChildScrollView( child: Column( children: [ TextFormField( onChanged: (value) { cubit.searchResualt = []; cubit.search(s: value); }, ), state is SocialSearchLoadingState ? const Center(child: CircularProgressIndicator()) : ListView.separated( shrinkWrap: true, physics: const AlwaysScrollableScrollPhysics(), itemBuilder: (context, index) { return InkWell( onTap: () { cubit.getUserPosts(id: cubit.searchResualt[index].uId); Navigator.push( context, MaterialPageRoute( builder: (context) => UserScreen(user: cubit.searchResualt[index])), ); }, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 20.0, vertical: 10.0), child: Row( children: [ CircleAvatar( radius: 25.0, backgroundImage: NetworkImage(cubit.searchResualt[index].image), ), const SizedBox(width: 15.0), Expanded( child: Row( children: [ Text( cubit.searchResualt[index].name, style: const TextStyle( height: 1.4, ), ), const SizedBox(width: 5.0), const Icon( Icons.check_circle, color: Colors.lightBlue, size: 16.0, ) ], ), ), const SizedBox(width: 15.0), IconButton( onPressed: () { cubit.follow(cubit.searchResualt[index].uId); }, icon: const Icon(IconBroken.Add_User)), ], ), ), ); }, separatorBuilder: (context, index) { return const Divider(); }, itemCount: cubit.searchResualt.length, ), ], ), ), )); }, ); } }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/translations/codegen_loader.g.dart
// DO NOT EDIT. This is code generated via package:easy_localization/generate.dart // ignore_for_file: prefer_single_quotes import 'dart:ui'; import 'package:easy_localization/easy_localization.dart' show AssetLoader; class CodegenLoader extends AssetLoader{ const CodegenLoader(); @override Future<Map<String, dynamic>> load(String fullPath, Locale locale ) { return Future.value(mapLocales[locale.toString()]); } static const Map<String,dynamic> ar = { "like": "إعجاب", "comment": "تعليق", "comments": "التعليقات", "post": "منشور", "add_photo": "أضف صورة", "follow": "تابع", "followers": "متابعين", "following": "المتابعون", "posts": "منشورات", "likes": "الإعجابات", "log_in": "تسجيل الدخول", "register": "التسجيل", "log_out": "تسجيل الخروج", "password": "كلمة المرور", "email": "البريد الإلكتروني", "keep_in": "ابق على اتصال مع أصدقائك", "home": "الرئيسية", "profile": "الصفحة الشخصية", "chats": "المحادثات", "users": "المستخدمين", "settings": "الاعدادات", "dark_mode": "التحويل للوضع الليلي", "light_mode": "التحويل للوضع المضيئ", "phone": "رقم الهاتف", "name": "الاسم", "no_message": "لا يوجد رسائل", "type_message": "ادخل رسالتك هنا..", "no_follow": "لم تتابع احد بعد", "no_comments": "لا يوجد تعليقات حتى الأن", "delete_comment": "حذف التعليق", "edit_profile": "تعديل الملف الشخصي", "update": "تحديث", "please": "رجاءاً ادخل ", "bio": "السيرة الذاتية", "comment_successfully": "تم اضافة تعليقك بنجاح", "create_post": "اضافة منشور", "join_now": "انضم لنا الأن", "change_lang": "تغير اللغة لـ:", "delelte_post": "حذف المنشور", "write_comment": "اكتب تعليقك!", "unfollow": "إلغاء المتابعة" }; static const Map<String,dynamic> en = { "like": "like", "comment": "comment", "comments": "comments", "post": "post", "add_photo": "add photo", "follow": "follow", "followers": "followers", "following": "following", "posts": "posts", "likes": "likes", "log_in": "log in", "register": "register", "log_out": "log out", "password": "password", "email": "email", "keep_in": "keep in touch with your friends", "home": "Home", "profile": "profile", "chats": "Chats", "users": "Users", "settings": "Settings", "dark_mode": "switch to dark mode", "light_mode": "switch to light mode", "phone": "phone number", "name": "name", "no_message": "there is no message!", "type_message": "type your message here..", "no_follow": "you don\\'t follow anyone yet!", "no_comments": "There\\'s no comments yet!", "delete_comment": "delete comment", "edit_profile": "edit profile", "update": "update", "please": "please enter your", "bio": "bio", "comment_successfully": "comment added successfully", "create_post": "addpost", "join_now": "join our community now", "change_lang": "Change the language to:", "delelte_post": "delete post", "write_comment": "write a comment!", "unfollow": "unfollow" }; static const Map<String, Map<String,dynamic>> mapLocales = {"ar": ar, "en": en}; }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/translations/locale_keys.g.dart
// DO NOT EDIT. This is code generated via package:easy_localization/generate.dart abstract class LocaleKeys { static const like = 'like'; static const comment = 'comment'; static const comments = 'comments'; static const post = 'post'; static const add_photo = 'add_photo'; static const follow = 'follow'; static const followers = 'followers'; static const following = 'following'; static const posts = 'posts'; static const likes = 'likes'; static const log_in = 'log_in'; static const register = 'register'; static const log_out = 'log_out'; static const password = 'password'; static const email = 'email'; static const keep_in = 'keep_in'; static const home = 'home'; static const profile = 'profile'; static const chats = 'chats'; static const users = 'users'; static const settings = 'settings'; static const dark_mode = 'dark_mode'; static const light_mode = 'light_mode'; static const phone = 'phone'; static const name = 'name'; static const no_message = 'no_message'; static const type_message = 'type_message'; static const no_follow = 'no_follow'; static const no_comments = 'no_comments'; static const delete_comment = 'delete_comment'; static const edit_profile = 'edit_profile'; static const update = 'update'; static const please = 'please'; static const bio = 'bio'; static const comment_successfully = 'comment_successfully'; static const create_post = 'create_post'; static const join_now = 'join_now'; static const change_lang = 'change_lang'; static const delelte_post = 'delelte_post'; static const write_comment = 'write_comment'; static const unfollow = 'unfollow'; }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/toast.dart
import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; void showToast({required String text, required ToastState state}) => Fluttertoast.showToast( msg: text, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 1, backgroundColor: chooseToastColor(state), textColor: Colors.white, fontSize: 16.0, ); // ignore: constant_identifier_names enum ToastState { SUCCESS, ERROR, WARNING } Color chooseToastColor(ToastState state) { Color color; switch (state) { case ToastState.SUCCESS: color = Colors.green; break; case ToastState.ERROR: color = Colors.red; break; case ToastState.WARNING: color = Colors.orange; break; } return color; }
0