repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/pogo_teams/lib
mirrored_repositories/pogo_teams/lib/tools/json_tools.dart
import 'dart:io'; import 'dart:convert'; class JsonTools { static String timestamp({bool utc = false}) { DateTime now; if (utc) { now = DateTime.now().toUtc(); } else { now = DateTime.now(); } return '${now.year}-${now.month}-${now.day} ${now.hour}:${now.minute}:${now.second}'; } static Future<dynamic> loadJson(String filename) async { if (!filename.endsWith('.json')) { filename += '.json'; } if (!await File(filename).exists()) { stderr.writeln('file not found : $filename'); return null; } return jsonDecode(await File(filename).readAsString()); } static Future<void> writeJson(dynamic contents, String filename) async { if (!filename.endsWith('.json')) { filename += '.json'; } File writeFile = await File(filename).create(); JsonEncoder encoder = const JsonEncoder.withIndent(' '); writeFile = await writeFile.writeAsString(encoder.convert(contents)); } }
0
mirrored_repositories/pogo_teams/lib
mirrored_repositories/pogo_teams/lib/enums/battle_outcome.dart
/* -------------------------------------------------------------------- @PogoTeams This enum expresses the outcome of a Pokemon battle. ------------------------------------------------------------------------------- */ enum BattleOutcome { win, loss, tie } extension BattleOutcomeExt on BattleOutcome { String get name { switch (this) { case BattleOutcome.win: return 'win'; case BattleOutcome.loss: return 'loss'; case BattleOutcome.tie: return 'tie'; } } }
0
mirrored_repositories/pogo_teams/lib
mirrored_repositories/pogo_teams/lib/enums/rankings_categories.dart
/* -------------------------------------------------------------------- @PogoTeams This enum expresses different categories for how Pokemon are ranked in a cup. ------------------------------------------------------------------------------- */ enum RankingsCategories { overall, leads, switches, closers, dex } extension RankingsCategoriesExt on RankingsCategories { String get displayName { switch (this) { case RankingsCategories.overall: return 'overall'; case RankingsCategories.leads: return 'leads'; case RankingsCategories.switches: return 'switches'; case RankingsCategories.closers: return 'closers'; case RankingsCategories.dex: return 'dex'; } } }
0
mirrored_repositories/pogo_teams/lib
mirrored_repositories/pogo_teams/lib/enums/cup_filter_type.dart
/* -------------------------------------------------------------------- @PogoTeams This enum is used to specify how a cup should include or exclude Pokemon. ------------------------------------------------------------------------------- */ enum CupFilterType { dex, pokemonId, type, tags }
0
mirrored_repositories/pogo_teams/lib
mirrored_repositories/pogo_teams/lib/battle/pokemon_battler.dart
// Local import '../pogo_objects/battle_pokemon.dart'; import 'battle_result.dart'; import '../modules/data/globals.dart'; import '../modules/data/pogo_debugging.dart'; import '../enums/battle_outcome.dart'; /* -------------------------------------------------------------------- @PogoTeams All battle simulations are managed here. The battle algorithm recursively explores every possibility of every turn in a battle to determine the closest matchup for the owner's Pokemon [self]. ------------------------------------------------------------------------------- */ class PokemonBattler { static const List<int> shieldScenarios = [0, 1, 2]; static void resetPokemon( BattlePokemon self, BattlePokemon opponent, ) { self.resetHp(); opponent.resetHp(); self.resetCooldown(); opponent.resetCooldown(); } static BattleResult battle( BattlePokemon self, BattlePokemon opponent, { int turn = 1, bool makeTimeline = false, }) { return _closestMatchup(_allBattleCombinations( self, opponent, turn, makeTimeline ? [] : null, )) ?? BattleResult( self: self, opponent: opponent, timeline: [], ); } static List<BattleResult> _battle( BattlePokemon self, BattlePokemon opponent, int turn, List<BattleTurnSnapshot>? timeline, ) { if (_battleComplete(self, opponent, turn)) { return [ BattleResult( self: self, opponent: opponent, timeline: timeline, ) ]; } while (!_battleComplete(self, opponent, turn)) { self.cooldown -= 1; opponent.cooldown -= 1; if (_chargeMoveSequenceBoth(self, opponent)) { _chargeMoveSequenceTieBreak(self, opponent); timeline?.add(BattleTurnSnapshot( turn: turn, self: self, opponent: opponent, description: 'Charge move tie break\n' '${self.name} atk : ${self.effectiveAttack}\n' '${opponent.name} atk : ${opponent.effectiveAttack}', )); return _allBattleCombinations(self, opponent, turn + 1, timeline); } else { if (_chargeMoveSequenceReady(self, opponent.cooldown)) { _chargeMoveSequence(self, opponent); timeline?.add(BattleTurnSnapshot( turn: turn, self: self, opponent: opponent, description: '${self.name} used ${self.nextDecidedChargeMove.name}', )); return _selfBattleCombinations( self, opponent, turn + 1, timeline, ); } else if (_chargeMoveSequenceReady(opponent, self.cooldown)) { _chargeMoveSequence(opponent, self); timeline?.add(BattleTurnSnapshot( turn: turn, self: self, opponent: opponent, description: '${opponent.name} used ${opponent.nextDecidedChargeMove.name}', )); return _opponentBattleCombinations( self, opponent, turn + 1, timeline, ); } else { _fastMoveSequence(self, opponent); timeline?.add(BattleTurnSnapshot( turn: turn, self: self, opponent: opponent, description: 'Fast move turn', )); ++turn; } } } return [ BattleResult( self: self, opponent: opponent, timeline: timeline, ) ]; } static bool _chargeMoveSequenceBoth( BattlePokemon self, BattlePokemon opponent, ) { return self.cooldown == 0 && opponent.cooldown == 0 && _chargeMoveSequenceReady(self, opponent.cooldown) && _chargeMoveSequenceReady(opponent, self.cooldown); } static bool _chargeMoveSequenceReady( BattlePokemon pokemon, int opponentCooldown, ) { return !pokemon.nextDecidedChargeMove.isNone() && pokemon.energy + pokemon.nextDecidedChargeMove.energyDelta >= 0 && (pokemon.prioritizeMoveAlignment ? opponentCooldown == 0 : true); } // Both Pokemon have cooled down and have charge moves ready, compare // against effective attack to break the tie. static void _chargeMoveSequenceTieBreak( BattlePokemon self, BattlePokemon opponent, ) { BattlePokemon firstAttacker; BattlePokemon secondAttacker; // There can be a third case here, but for simulation, it is fine to // give self the win if true attacks are equal. if (self.effectiveAttack >= opponent.effectiveAttack) { firstAttacker = self; secondAttacker = opponent; } else { firstAttacker = opponent; secondAttacker = self; } firstAttacker.applyChargeMoveDamage(secondAttacker); self.resetCooldown(); if (secondAttacker.currentHp > 0) { secondAttacker.applyChargeMoveDamage(firstAttacker); opponent.resetCooldown(); } } // One Pokemon |chargeUser| is in a charge move sequence // Apply charge move damage, followed by the defender's immediate fast // move damage static void _chargeMoveSequence( BattlePokemon chargeUser, BattlePokemon defender, ) { chargeUser.applyChargeMoveDamage(defender); if (defender.currentHp > 0) { defender.applyFastMoveDamage(chargeUser); defender.resetCooldown(); } chargeUser.resetCooldown(); } static void _fastMoveSequence( BattlePokemon self, BattlePokemon opponent, ) { if (self.cooldown == 0) { self.applyFastMoveDamage(opponent); self.resetCooldown(); } if (opponent.cooldown == 0) { opponent.applyFastMoveDamage(self); opponent.resetCooldown(); } } static BattleResult? _closestMatchup(List<BattleResult?> results) { results = results.whereType<BattleResult>().toList(); results = results as List<BattleResult>; BattleResult? selfClosestWin; BattleResult? opponentClosestWin; // Gather all of the wins and losses List<BattleResult> wins = results.where((result) => result.outcome == BattleOutcome.win).toList(); List<BattleResult> losses = results .where((result) => result.outcome == BattleOutcome.loss) .toList(); // Find the closest win and loss by comparing the difference in self and // opponent hp ratios. if (wins.isNotEmpty) { selfClosestWin = wins.reduce((rating1, rating2) => (rating1.hpRatioDifference < rating2.hpRatioDifference ? rating1 : rating2)); } if (losses.isNotEmpty) { opponentClosestWin = losses.reduce((rating1, rating2) => (rating1.hpRatioDifference < rating2.hpRatioDifference ? rating1 : rating2)); } // Return the win or loss that resulted in the highest rating. This result // in theory will be the best outcome for self or the opponent for the // win or loss respectively. if (selfClosestWin == null) { return opponentClosestWin; } else if (opponentClosestWin == null) { return selfClosestWin; } return selfClosestWin.self.currentRating > opponentClosestWin.opponent.currentRating ? selfClosestWin : opponentClosestWin; } static bool _battleComplete( BattlePokemon self, BattlePokemon opponent, int turn, ) { return self.currentHp == 0 || opponent.currentHp == 0 || turn > Globals.maxPvpTurns; } static List<BattleResult> _allBattleCombinations( BattlePokemon self, BattlePokemon opponent, int turn, List<BattleTurnSnapshot>? timeline, ) { List<BattleResult> results = [ ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.selectedBattleChargeMoves.first, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.selectedBattleChargeMoves.first, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.selectedBattleChargeMoves.last, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.selectedBattleChargeMoves.last, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.selectedBattleChargeMoves.first, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.selectedBattleChargeMoves.last, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.selectedBattleChargeMoves.last, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.selectedBattleChargeMoves.first, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ]; return results; } static List<BattleResult> _selfBattleCombinations( BattlePokemon self, BattlePokemon opponent, int turn, List<BattleTurnSnapshot>? timeline, { bool prioritizeMoveAlignment = false, }) { return [ ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.selectedBattleChargeMoves.first, prioritizeMoveAlignment: prioritizeMoveAlignment, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.nextDecidedChargeMove, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.selectedBattleChargeMoves.last, prioritizeMoveAlignment: prioritizeMoveAlignment, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.nextDecidedChargeMove, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ]; } static List<BattleResult> _opponentBattleCombinations( BattlePokemon self, BattlePokemon opponent, int turn, List<BattleTurnSnapshot>? timeline, { bool prioritizeMoveAlignment = false, }) { return [ ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.nextDecidedChargeMove, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.selectedBattleChargeMoves.first, prioritizeMoveAlignment: prioritizeMoveAlignment, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ..._battle( BattlePokemon.from( self, nextDecidedChargeMove: self.nextDecidedChargeMove, ), BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.selectedBattleChargeMoves.last, prioritizeMoveAlignment: prioritizeMoveAlignment, ), turn, timeline == null ? null : List<BattleTurnSnapshot>.from(timeline), ), ]; } static void debugPrintInitialization( BattlePokemon self, BattlePokemon opponent, ) { PogoDebugging.printMulti(self.name, [ 'fast : ${self.selectedBattleFastMove.name} : ${self.selectedBattleFastMove.damage} : ' 'energy delta : ${self.selectedBattleFastMove.energyDelta}', 'charge1 : ${self.selectedBattleChargeMoves.first.name} : ${self.selectedBattleChargeMoves.first.damage} : ' 'energy delta : ${self.selectedBattleChargeMoves.first.energyDelta}', 'charge2 : ${self.selectedBattleChargeMoves.last.name} : ${self.selectedBattleChargeMoves.last.damage} : ' 'energy delta : ${self.selectedBattleChargeMoves.last.energyDelta}', 'level : ${self.selectedIVs.level}', 'cp : ${self.cp}', 'ivs : ${self.selectedIVs.atk} ${self.selectedIVs.def} ${self.selectedIVs.hp}' ]); PogoDebugging.printMulti(opponent.name, [ 'fast : ${opponent.selectedBattleFastMove.name} : ${opponent.selectedBattleFastMove.damage} : ' 'energy delta : ${opponent.selectedBattleFastMove.energyDelta}', 'charge1 : ${opponent.selectedBattleChargeMoves.first.name} : ${opponent.selectedBattleChargeMoves.first.damage} : ' 'energy delta : ${opponent.selectedBattleChargeMoves.first.energyDelta}', 'charge2 : ${opponent.selectedBattleChargeMoves.last.name} : ${opponent.selectedBattleChargeMoves.last.damage} : ' 'energy delta : ${opponent.selectedBattleChargeMoves.last.energyDelta}', 'level : ${opponent.selectedIVs.level}', 'cp : ${opponent.cp}', 'ivs : ${opponent.selectedIVs.atk} ${opponent.selectedIVs.def} ${opponent.selectedIVs.hp}' ]); } static void debugPrintBattleOutcome(BattleResult results) { String selfOutcome = results.outcome.name; String opponentOutcome = ''; switch (results.outcome) { case BattleOutcome.tie: opponentOutcome = 'tie'; break; case BattleOutcome.loss: opponentOutcome = 'win'; break; case BattleOutcome.win: opponentOutcome = 'loss'; break; } PogoDebugging.printHeader('Outcome'); PogoDebugging.printMulti(results.self.name, [ selfOutcome, 'score : ${results.self.currentRating}', ]); PogoDebugging.printMulti(results.opponent.name, [ opponentOutcome, 'score : ${results.opponent.currentRating}', ]); PogoDebugging.printFooter(); } } class BattleTurnSnapshot { BattleTurnSnapshot({ required this.turn, required BattlePokemon self, required BattlePokemon opponent, required this.description, }) { this.self = BattlePokemon.from( self, nextDecidedChargeMove: self.nextDecidedChargeMove, ); this.opponent = BattlePokemon.from( opponent, nextDecidedChargeMove: opponent.nextDecidedChargeMove, ); } final int turn; late final BattlePokemon self; late final BattlePokemon opponent; final String description; void debugPrint() { PogoDebugging.printMulti('Turn $turn', [description]); PogoDebugging.printMulti(self.name, [ 'hp : ${self.currentHp} / ${self.maxHp}', 'energy : ${self.energy}', 'cooldown : ${self.cooldown}', '-' * (1 + PogoDebugging.debugHeaderWidth), 'next charge : ${self.nextDecidedChargeMove.name}', ]); PogoDebugging.printMulti(opponent.name, [ 'hp : ${opponent.currentHp} / ${opponent.maxHp}', 'energy : ${opponent.energy}', 'cooldown : ${opponent.cooldown}', '-' * (1 + PogoDebugging.debugHeaderWidth), 'next charge : ${opponent.nextDecidedChargeMove.name}', ]); } }
0
mirrored_repositories/pogo_teams/lib
mirrored_repositories/pogo_teams/lib/battle/battle_result.dart
// Local import 'pokemon_battler.dart'; import '../pogo_objects/battle_pokemon.dart'; import '../modules/data/pogo_debugging.dart'; import '../enums/battle_outcome.dart'; /* -------------------------------------------------------------------- @PogoTeams The result of a simulated battle, including the ratings, the selected movesets, and the timeline of each turn. ------------------------------------------------------------------------------- */ class BattleResult { BattleResult({ required this.self, required this.opponent, required this.timeline, }) { double selfRating = self.currentHpRatio * opponent.damageRecievedRatio; double opponentRating = opponent.currentHpRatio * self.damageRecievedRatio; if (self.currentHp > 0) { outcome = BattleOutcome.win; } else if (opponent.currentHp > 0) { outcome = BattleOutcome.loss; } else { outcome = BattleOutcome.tie; selfRating = 1; opponentRating = 1; } self.currentRating = selfRating; opponent.currentRating = opponentRating; } Map<String, dynamic> toJson() { return { 'opponent': { 'pokemonId': opponent.pokemonId, 'rating': opponent.currentRating, 'selectedFastMove': opponent.selectedBattleFastMove.moveId, 'selectedChargeMoves': [ opponent.selectedBattleChargeMoves.first.moveId, opponent.selectedBattleChargeMoves.last.moveId, ], }, 'outcome': outcome.name, 'rating': self.currentRating, 'selectedFastMove': self.selectedBattleFastMove.moveId, 'selectedChargeMoves': [ self.selectedBattleChargeMoves.first.moveId, self.selectedBattleChargeMoves.last.moveId, ], }; } final BattlePokemon self; final BattlePokemon opponent; BattleOutcome outcome = BattleOutcome.win; List<BattleTurnSnapshot>? timeline; num get hpRatioDifference { return (self.currentHpRatio - opponent.currentHpRatio).abs(); } void debugPrintTimeline() { if (timeline == null) return; for (var snapshot in timeline!) { snapshot.debugPrint(); PogoDebugging.breakpoint(); } } }
0
mirrored_repositories/pogo_teams
mirrored_repositories/pogo_teams/test/widget_test.dart
void main() {}
0
mirrored_repositories/pogo_teams
mirrored_repositories/pogo_teams/bin/pogo_teams_cli.dart
// Packages import 'package:isar/isar.dart'; // Local import 'package:pogo_teams/mapping/niantic_snapshot.dart'; import 'package:pogo_teams/mapping/mapping_tools.dart'; import 'package:pogo_teams/ranker/ranker_main.dart'; /* -------------------------------------------------------------------- @PogoTeams niantic-snapshot -> data/niantic-snapshot.json Maps a Niantic data source (niantic.json) to a snapshot of all fields used by Pogo Teams (snapshot.json). alternate-forms Scans a Niantic data source (niantic.json) for all 'form' fields that are not suffixed with '_NORMAL'. pvpoke-released Generate a list of released Pokemon from a PvPoke gamemaster. snapshot-released Generate a list of released Pokemon from a niantic-snapshot. validate-snapshot-dex Checks to ensure there is a Pokemon entry for every dex number. This is expected to fail for places where there is a known gap in the snapshot. generate-rankings Generate rankings for all cups specified in json/live_lists/cups.json. Every cup will have it's own .json file in the json/rankings directory. test-generate-rankings Step through a battle between 2 pokemon at a specified CP. commit Copy json/niantic-snapshot.json and all rankings in the json/rankings directory to pogo_data_source or pogo_data_source/test. Timestamp.txt will be updated to UTC now. ------------------------------------------------------------------------------- */ void main(List<String> arguments) async { await Isar.initializeIsarCore(download: true); if (arguments.isEmpty) return; switch (arguments[0]) { case 'niantic-snapshot': mapNianticToSnapshot(); break; case 'alternate-forms': buildAlternateFormsList(); break; case 'pvpoke-released': buildPvpokeReleasedIdsList(); break; case 'snapshot-released': buildSnapshotReleasedIdsList(); break; case 'validate-snapshot-dex': validateSnapshotDex(); break; case 'generate-rankings': await generatePokemonRankings(); if (arguments.length > 2) { if (arguments[1] == 'commit' && arguments[2] == 'test') { await copyGeneratedBinFiles('pogo_data_source/test'); } } break; case 'test-generate-rankings': if (arguments.length > 3) { int cp = int.tryParse(arguments[3]) ?? 1500; generatePokemonRankingsTest( arguments[1], arguments[2], cp, ); } break; case 'commit': if (arguments.length > 1) { switch (arguments[1]) { case 'test': await copyGeneratedBinFiles('pogo_data_source/test'); break; case 'production': await copyGeneratedBinFiles('pogo_data_source'); break; } } break; } }
0
mirrored_repositories/chitchat-flutter-project
mirrored_repositories/chitchat-flutter-project/lib/firebase_options.dart
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; import 'package:flutter_dotenv/flutter_dotenv.dart'; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: return macos; case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static FirebaseOptions web = FirebaseOptions( apiKey: dotenv.get('FIREBASE_WEB_API_KEY'), appId: dotenv.get('FIREBASE_WEB_APP_ID'), messagingSenderId: dotenv.get('FIREBASE_WEB_MESSAGING_SENDER_ID'), projectId: dotenv.get('FIREBASE_WEB_PROJECT_ID'), authDomain: dotenv.get('FIREBASE_WEB_AUTH_DOMAIN'), storageBucket: dotenv.get('FIREBASE_WEB_STORAGE_BUCKET'), ); static FirebaseOptions android = FirebaseOptions( apiKey: dotenv.get('FIREBASE_ANDROID_API_KEY'), appId: dotenv.get('FIREBASE_ANDROID_APP_ID'), messagingSenderId: dotenv.get('FIREBASE_ANDROID_MESSAGING_SENDER_ID'), projectId: dotenv.get('FIREBASE_ANDROID_PROJECT_ID'), storageBucket: dotenv.get('FIREBASE_ANDROID_STORAGE_BUCKET'), ); static FirebaseOptions ios = FirebaseOptions( apiKey: dotenv.get('FIREBASE_IOS_API_KEY'), appId: dotenv.get('FIREBASE_IOS_APP_ID'), messagingSenderId: dotenv.get('FIREBASE_IOS_MESSAGING_SENDER_ID'), projectId: dotenv.get('FIREBASE_IOS_PROJECT_ID'), storageBucket: dotenv.get('FIREBASE_IOS_STORAGE_BUCKET'), iosClientId: dotenv.get('FIREBASE_IOS_CLIENT_ID'), iosBundleId: dotenv.get('FIREBASE_IOS_BUNDLE_ID'), ); static FirebaseOptions macos = FirebaseOptions( apiKey: dotenv.get('FIREBASE_MACOS_API_KEY'), appId: dotenv.get('FIREBASE_MACOS_APP_ID'), messagingSenderId: dotenv.get('FIREBASE_MACOS_MESSAGING_SENDER_ID'), projectId: dotenv.get('FIREBASE_MACOS_PROJECT_ID'), storageBucket: dotenv.get('FIREBASE_MACOS_STORAGE_BUCKET'), iosClientId: dotenv.get('FIREBASE_MACOS_CLIENT_ID'), iosBundleId: dotenv.get('FIREBASE_MACOS_BUNDLE_ID'), ); }
0
mirrored_repositories/chitchat-flutter-project
mirrored_repositories/chitchat-flutter-project/lib/main.dart
import 'package:chitchat/screens/auth.dart'; import 'package:chitchat/screens/chats.dart'; import 'package:chitchat/screens/splash.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:google_fonts/google_fonts.dart'; import 'firebase_options.dart'; import 'package:flutter/material.dart'; void main() async { await dotenv.load(); WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Add an artificial delay before running the app await Future.delayed(const Duration(seconds: 1)); runApp(const App()); } class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'FlutterChat', theme: ThemeData().copyWith( useMaterial3: false, colorScheme: ColorScheme.fromSeed( seedColor: const Color(0xFF2296F3), background: const Color(0xFFD9E2D6), ), textTheme: GoogleFonts.latoTextTheme(ThemeData().textTheme), ), home: StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const SplashScreen(); } if (snapshot.hasData) { return const ChatsScreen(); } if (snapshot.hasError) {} return const AuthScreen(); }, ), ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/widgets/message_bubble.dart
import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; // A MessageBubble for showing a single chat message on the ChatScreen. class MessageBubble extends StatelessWidget { // Create a message bubble which is meant to be the first in the sequence. const MessageBubble.first({ super.key, required this.userImage, required this.username, required this.message, required this.isMe, }) : isFirstInSequence = true; // Create a amessage bubble that continues the sequence. const MessageBubble.next({ super.key, required this.message, required this.isMe, }) : isFirstInSequence = false, userImage = null, username = null; // Whether or not this message bubble is the first in a sequence of messages // from the same user. // Modifies the message bubble slightly for these different cases - only // shows user image for the first message from the same user, and changes // the shape of the bubble for messages thereafter. final bool isFirstInSequence; // Image of the user to be displayed next to the bubble. // Not required if the message is not the first in a sequence. final String? userImage; // Username of the user. // Not required if the message is not the first in a sequence. final String? username; final String message; // Controls how the MessageBubble will be aligned. final bool isMe; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Stack( children: [ if (userImage != null) Positioned( top: 15, // Align user image to the right, if the message is from me. right: isMe ? 0 : null, child: CircleAvatar( backgroundImage: CachedNetworkImageProvider(userImage!), backgroundColor: theme.colorScheme.primary.withAlpha(180), radius: 23, ), ), Container( // Add some margin to the edges of the messages, to allow space for the // user's image. margin: const EdgeInsets.symmetric(horizontal: 46), child: Row( // The side of the chat screen the message should show at. mainAxisAlignment: isMe ? MainAxisAlignment.end : MainAxisAlignment.start, children: [ Column( crossAxisAlignment: isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: [ // First messages in the sequence provide a visual buffer at // the top. if (isFirstInSequence) const SizedBox(height: 18), if (username != null) Padding( padding: const EdgeInsets.only( left: 13, right: 13, ), child: Text( username!, style: const TextStyle( fontWeight: FontWeight.bold, color: Colors.black87, ), ), ), // The "speech" box surrounding the message. Container( decoration: BoxDecoration( color: isMe ? Colors.grey[300] : theme.colorScheme.secondary.withAlpha(200), // Only show the message bubble's "speaking edge" if first in // the chain. // Whether the "speaking edge" is on the left or right depends // on whether or not the message bubble is the current user. borderRadius: BorderRadius.only( topLeft: !isMe && isFirstInSequence ? Radius.zero : const Radius.circular(12), topRight: isMe && isFirstInSequence ? Radius.zero : const Radius.circular(12), bottomLeft: const Radius.circular(12), bottomRight: const Radius.circular(12), ), ), // Set some reasonable constraints on the width of the // message bubble so it can adjust to the amount of text // it should show. constraints: const BoxConstraints(maxWidth: 200), padding: const EdgeInsets.symmetric( vertical: 10, horizontal: 14, ), // Margin around the bubble. margin: const EdgeInsets.symmetric( vertical: 4, horizontal: 12, ), child: Text( message, style: TextStyle( // Add a little line spacing to make the text look nicer // when multilined. height: 1.3, color: isMe ? Colors.black87 : theme.colorScheme.onSecondary, ), softWrap: true, ), ), ], ), ], ), ), ], ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/widgets/chat_messages.dart
import 'package:chitchat/widgets/message_bubble.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class ChatMessages extends StatelessWidget { final String chatId; const ChatMessages({super.key, required this.chatId}); @override Widget build(BuildContext context) { final authenticatedUser = FirebaseAuth.instance.currentUser!; return StreamBuilder( stream: FirebaseFirestore.instance .collection('chats/$chatId/messages') .orderBy('createdAt', descending: true) .snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } if (!snapshot.hasData || snapshot.data!.docs.isEmpty) { return const Center( child: Text('No messages found.'), ); } if (snapshot.hasError) { return const Center( child: Text('Something went wrong...'), ); } final loadedMessages = snapshot.data!.docs; return ListView.builder( padding: const EdgeInsets.only(bottom: 40, left: 13, right: 13), reverse: true, itemCount: loadedMessages.length, itemBuilder: (context, index) { final chatMessage = loadedMessages[index].data(); final nextChatMessage = index + 1 < loadedMessages.length ? loadedMessages[index + 1].data() : null; final currentMessageUserId = chatMessage['userId']; final nextMessageUserId = nextChatMessage != null ? nextChatMessage['userId'] : null; final nextUserIsSame = nextMessageUserId == currentMessageUserId; if (nextUserIsSame) { return MessageBubble.next( message: chatMessage['text'], isMe: authenticatedUser.uid == currentMessageUserId, ); } else { return MessageBubble.first( userImage: chatMessage['userImage'], username: chatMessage['username'], message: chatMessage['text'], isMe: authenticatedUser.uid == currentMessageUserId, ); } }, ); }, ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/widgets/custom_image_picker.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; class CustomImagePicker extends StatefulWidget { final String title; final bool label; final String image; final void Function(File pickedImage) onPickImage; const CustomImagePicker({ super.key, required this.title, required this.label, required this.image, required this.onPickImage, }); @override State<StatefulWidget> createState() { return _CustomImagePickerState(); } } class _CustomImagePickerState extends State<CustomImagePicker> { File? _pickedImageFile; void _pickImage() async { final imageSource = await showDialog<ImageSource>( context: context, builder: (BuildContext context) { return AlertDialog( title: Text( widget.title, textAlign: TextAlign.center, ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(ImageSource.camera), child: const Text('Take a photo'), ), TextButton( onPressed: () => Navigator.of(context).pop(ImageSource.gallery), child: const Text('Upload from Photos'), ), ], ); }, ); if (imageSource == null) { return; } final pickedImage = await ImagePicker().pickImage( source: imageSource, imageQuality: 50, maxHeight: 150, ); if (pickedImage == null) { return; } setState(() { _pickedImageFile = File(pickedImage.path); }); widget.onPickImage(_pickedImageFile!); } @override Widget build(BuildContext context) { return Column( children: [ GestureDetector( onTap: _pickImage, child: CircleAvatar( radius: 40, backgroundColor: Colors.grey, backgroundImage: _pickedImageFile != null ? FileImage(_pickedImageFile!) as ImageProvider : AssetImage(widget.image), ), ), if (widget.label) TextButton.icon( onPressed: _pickImage, icon: const Icon(Icons.image), label: Text( widget.title, style: TextStyle(color: Theme.of(context).colorScheme.primary), ), ) ], ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/widgets/new_message.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class NewMessage extends StatefulWidget { final String chatId; const NewMessage({super.key, required this.chatId}); @override State<StatefulWidget> createState() { return _NewMessageState(); } } class _NewMessageState extends State<NewMessage> { final _messageController = TextEditingController(); void _submitMessage() async { final enteredMessage = _messageController.text; if (enteredMessage.trim().isEmpty) { return; } FocusScope.of(context).unfocus(); _messageController.clear(); final user = FirebaseAuth.instance.currentUser!; final userData = await FirebaseFirestore.instance .collection('users') .doc(user.uid) .get(); FirebaseFirestore.instance .collection('chats/${widget.chatId}/messages') .add({ 'text': enteredMessage, 'createdAt': Timestamp.now(), 'userId': user.uid, 'username': userData.data()!['username'], 'userImage': userData.data()!['image_url'], }); await FirebaseFirestore.instance .collection('chats') .doc(widget.chatId) .update({ 'preview_message': '${userData.data()!['username']}: $enteredMessage', }); } @override void dispose() { _messageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 15, right: 1, bottom: 14), child: Row(children: [ Expanded( child: TextField( controller: _messageController, textCapitalization: TextCapitalization.sentences, autocorrect: true, enableSuggestions: true, decoration: const InputDecoration(labelText: 'Send a message...'), ), ), IconButton( color: Theme.of(context).colorScheme.primary, onPressed: _submitMessage, icon: const Icon(Icons.send), ) ]), ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/screens/auth.dart
import 'dart:io'; import 'package:chitchat/widgets/custom_image_picker.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; final _firebase = FirebaseAuth.instance; class AuthScreen extends StatefulWidget { const AuthScreen({super.key}); @override State<AuthScreen> createState() { return AuthScreenState(); } } class AuthScreenState extends State<AuthScreen> { final _form = GlobalKey<FormState>(); var _isLoggingIn = false; var _enteredEmail = ''; var _enteredUsername = ''; var _enteredPassword = ''; File? _selectedImage; var _isAuthenticating = false; void _submit() async { final isValid = _form.currentState!.validate(); if (!isValid) { return; } try { if (!_isLoggingIn && _selectedImage == null) { throw Exception('Please, select a profile photo'); } _form.currentState!.save(); setState(() { _isAuthenticating = true; }); if (_isLoggingIn) { await _firebase.signInWithEmailAndPassword( email: _enteredEmail, password: _enteredPassword); } else { // Check image size final imageFile = _selectedImage!; final imageBytes = await imageFile.readAsBytes(); final imageSizeKB = imageBytes.lengthInBytes / 1024; const maxImageSizeMB = 5; const maxImageSizeKB = maxImageSizeMB * 1024; if (imageSizeKB > maxImageSizeKB) { throw Exception( 'The selected image exceeds the maximum allowed size of $maxImageSizeMB MB.'); } final userCredentials = await _firebase.createUserWithEmailAndPassword( email: _enteredEmail, password: _enteredPassword); final storageRef = FirebaseStorage.instance .ref() .child('user_images') .child('${userCredentials.user!.uid}.jpg'); await storageRef.putFile(_selectedImage!); final imageUrl = await storageRef.getDownloadURL(); await FirebaseFirestore.instance .collection('users') .doc(userCredentials.user!.uid) .set( { 'uid': userCredentials.user!.uid, 'username': _enteredUsername, 'email': _enteredEmail, 'image_url': imageUrl, }, ); } } on FirebaseAuthException catch (error) { var authFailedMessage = 'Authentication failed'; if (error.code == 'email-already-in-use') { authFailedMessage = 'Email address already in use'; } ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(authFailedMessage)), ); } on Exception catch (error) { ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(error.toString().replaceFirst('Exception: ', ''))), ); } setState(() { _isAuthenticating = false; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).colorScheme.background, body: Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( padding: const EdgeInsets.all(20), constraints: const BoxConstraints(maxWidth: 500), child: Card( elevation: 10, margin: const EdgeInsets.all(0), child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20), child: Form( key: _form, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox(height: 10), Text( _isLoggingIn ? 'Login' : 'Create account', style: Theme.of(context) .textTheme .titleLarge! .copyWith( fontWeight: FontWeight.bold, fontSize: 30, ), textAlign: TextAlign.center, ), const SizedBox(height: 30), if (!_isLoggingIn) CustomImagePicker( title: 'Add profile photo', label: true, image: 'assets/images/default_profile_photo_1.png', onPickImage: (pickedImage) { _selectedImage = pickedImage; }, ), if (!_isLoggingIn) const SizedBox(height: 20), TextFormField( decoration: InputDecoration( hintText: 'E-mail', border: OutlineInputBorder( borderSide: const BorderSide( width: 1, color: Colors.grey, ), borderRadius: BorderRadius.circular(5.0), ), ), keyboardType: TextInputType.emailAddress, autocorrect: false, textCapitalization: TextCapitalization.none, validator: (value) { if (value == null || value.trim().isEmpty || !value.contains('@')) { return 'Invalid email address.'; } return null; }, onSaved: (value) { _enteredEmail = value!; }, ), const SizedBox(height: 20), if (!_isLoggingIn) TextFormField( decoration: InputDecoration( hintText: 'Username', border: OutlineInputBorder( borderSide: const BorderSide( width: 1, color: Colors.grey, ), borderRadius: BorderRadius.circular(5.0), ), ), enableSuggestions: false, onSaved: (value) { _enteredUsername = value!; }, validator: (value) { if (value == null || value.trim().isEmpty || value.trim().length < 4) { return 'Invalid username'; } return null; }, ), if (!_isLoggingIn) const SizedBox(height: 20), TextFormField( decoration: InputDecoration( hintText: 'Password', border: OutlineInputBorder( borderSide: const BorderSide( width: 1, color: Colors.grey, ), borderRadius: BorderRadius.circular(5.0), ), ), obscureText: true, validator: (value) { if (value == null || value.trim().length < 6) { return 'Password must be at least 6 characters long.'; } return null; }, onSaved: (value) { _enteredPassword = value!; }, ), const SizedBox(height: 5), if (_isAuthenticating) const SizedBox(height: 20), if (_isAuthenticating) const CircularProgressIndicator(), const SizedBox(height: 5), if (!_isAuthenticating) Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( _isLoggingIn ? 'Do not have an account?' : 'Already have an account?', ), TextButton( onPressed: () { setState(() { _isLoggingIn = !_isLoggingIn; }); }, child: Text( _isLoggingIn ? 'Click here to create one.' : 'Click here to log in.', ), ), ], ), if (!_isAuthenticating) Container( width: double.infinity, alignment: Alignment.center, child: SizedBox( width: 100, child: ElevatedButton( onPressed: _submit, style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), child: Text( _isLoggingIn ? 'Login' : 'Signup', ), ), ), ), const SizedBox(height: 10), ], ), ), ), ), ), ) ], ), ), ), ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/screens/chat.dart
import 'package:chitchat/widgets/chat_messages.dart'; import 'package:chitchat/widgets/new_message.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; class ChatScreen extends StatefulWidget { final String chatId; const ChatScreen({super.key, required this.chatId}); @override State<ChatScreen> createState() => _ChatScreenState(); } class _ChatScreenState extends State<ChatScreen> { void setupPushNotification() async { final fcm = FirebaseMessaging.instance; await fcm.requestPermission(); await fcm.subscribeToTopic('chats'); } @override void initState() { super.initState(); setupPushNotification(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Chat'), actions: [ IconButton( onPressed: () { FirebaseAuth.instance.signOut(); Navigator.of(context).pop(); }, icon: Icon( Icons.exit_to_app, color: Theme.of(context).colorScheme.onPrimary, ), ) ], ), body: Column( children: [ Expanded(child: ChatMessages(chatId: widget.chatId)), NewMessage(chatId: widget.chatId), ], ), ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/screens/create_group.dart
import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:chitchat/screens/chats.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:chitchat/widgets/custom_image_picker.dart'; final authenticatedUser = FirebaseAuth.instance.currentUser!; class CreateGroupScreen extends StatefulWidget { const CreateGroupScreen({super.key}); @override State<CreateGroupScreen> createState() => _CreateGroupScreenState(); } class _CreateGroupScreenState extends State<CreateGroupScreen> { final authenticatedUser = FirebaseAuth.instance.currentUser!; final _form = GlobalKey<FormState>(); File? _selectedImage; var _enteredName = ''; List<String> selectedUsernames = []; List<String> selectedUserUIDs = []; late TextEditingController searchController; String searchQuery = ''; @override void initState() { super.initState(); searchController = TextEditingController(); } @override void dispose() { searchController.dispose(); super.dispose(); } _submit() async { final isValid = _form.currentState!.validate(); if (!isValid) { return; } try { if (_selectedImage == null) { throw Exception('Please, select a profile photo'); } _form.currentState!.save(); setState(() {}); final imageFile = _selectedImage!; final imageBytes = await imageFile.readAsBytes(); final imageSizeKB = imageBytes.lengthInBytes / 1024; const maxImageSizeMB = 5; const maxImageSizeKB = maxImageSizeMB * 1024; if (imageSizeKB > maxImageSizeKB) { throw Exception( 'The selected image exceeds the maximum allowed size of $maxImageSizeMB MB.'); } final storageRef = FirebaseStorage.instance .ref() .child('group_images') .child('${Timestamp.now().hashCode}.jpg'); await storageRef.putFile(_selectedImage!); final imageUrl = await storageRef.getDownloadURL(); final userData = await FirebaseFirestore.instance .collection('users') .doc(authenticatedUser.uid) .get(); final chatName = _enteredName.isEmpty ? '${userData['username']}, ${selectedUsernames.join(', ')}' : _enteredName; await FirebaseFirestore.instance.collection('chats').add({ 'lastActivity': Timestamp.now(), 'name': chatName, 'participants': [authenticatedUser.uid, ...selectedUserUIDs], 'image_url': imageUrl, 'preview_message': 'No message yet...' }); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => const ChatsScreen()), (Route<dynamic> route) => false); } on Exception catch (error) { ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(error.toString().replaceFirst('Exception: ', ''))), ); } setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('New group'), actions: [ if (selectedUsernames.isNotEmpty) IconButton( icon: const Icon(Icons.check), onPressed: () { _submit(); }, ), ], ), body: Container( constraints: const BoxConstraints(maxWidth: 1000), alignment: Alignment.center, child: Column( children: [ const SizedBox(height: 20), Container( alignment: Alignment.topLeft, child: Row( children: [ Padding( padding: const EdgeInsets.only(left: 10), child: CustomImagePicker( title: 'Add picture', label: false, image: 'assets/images/default_upload_photo_3.png', onPickImage: (pickedImage) { _selectedImage = pickedImage; }, ), ), const SizedBox(width: 20), Expanded( child: Form( key: _form, child: TextFormField( decoration: const InputDecoration( hintText: 'Name your group', ), keyboardType: TextInputType.emailAddress, autocorrect: false, textCapitalization: TextCapitalization.none, validator: (value) { if (value == null || value.trim().isEmpty || value.trim().length < 5) { return 'Invalid group name.'; } return null; }, onSaved: (value) { _enteredName = value!; }, ), ), ), const SizedBox(width: 10) ], ), ), const SizedBox(height: 20), Padding( padding: const EdgeInsets.all(8.0), child: TextField( controller: searchController, onChanged: (value) { setState(() { searchQuery = value; }); }, decoration: const InputDecoration( labelText: 'Search users', prefixIcon: Icon(Icons.search), border: OutlineInputBorder(), ), ), ), Expanded( child: StreamBuilder( stream: FirebaseFirestore.instance .collection('users') .orderBy('username') .snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { //return const CircularProgressIndicator(); } if (!snapshot.hasData || snapshot.data!.docs.isEmpty) { return const Center(child: Text('No users found')); } if (snapshot.hasError) { return const Center( child: Text('An error occurred, please try again later')); } final loadedUsers = snapshot.data!.docs .where((u) => u['email'] != authenticatedUser.email && u['username'] .toString() .toLowerCase() .contains(searchQuery.toLowerCase())) .toList(); return SingleChildScrollView( child: ListView.builder( shrinkWrap: true, itemCount: loadedUsers.length, itemBuilder: (context, index) { final user = loadedUsers[index].data(); final uid = loadedUsers[index].id; final username = user['username']; final imageUrl = user['image_url']; return Padding( padding: const EdgeInsets.only(top: 4.0), child: ListTile( leading: CircleAvatar( backgroundImage: imageUrl != null ? CachedNetworkImageProvider(imageUrl) : const AssetImage( 'assets/images/default_profile_photo_1.png') as ImageProvider<Object>, ), title: Text( username.length > 40 ? '${username.substring(0, 40)}...' : username, ), trailing: selectedUsernames.contains(username) ? Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.check, color: Theme.of(context).primaryColor), const SizedBox(width: 8), const Text('Added'), const SizedBox(width: 8), ], ) : ElevatedButton.icon( onPressed: () { setState(() { selectedUsernames.add(username); selectedUserUIDs.add(uid); }); }, icon: const Icon(Icons.add), label: const Text('Add'), style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context) .appBarTheme .backgroundColor, foregroundColor: Colors.white, ), ), onTap: () { setState(() { if (selectedUsernames.contains(username)) { selectedUsernames.remove(username); selectedUserUIDs.remove(uid); } else { selectedUsernames.add(username); selectedUserUIDs.add(uid); } }); }, ), ); }, ), ); }, ), ), ], ), ), ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/screens/chats.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:chitchat/screens/chat.dart'; import 'package:chitchat/screens/create_group.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class ChatsScreen extends StatelessWidget { const ChatsScreen({super.key}); @override Widget build(BuildContext context) { final authenticatedUser = FirebaseAuth.instance.currentUser!; return Scaffold( appBar: AppBar( title: const Text('Chats'), actions: [ IconButton( onPressed: () { FirebaseAuth.instance.signOut(); }, icon: Icon( Icons.exit_to_app, color: Theme.of(context).colorScheme.onPrimary, ), ) ], ), floatingActionButton: FloatingActionButton( onPressed: () async { await Navigator.of(context) .push(MaterialPageRoute(builder: (ctx) => CreateGroupScreen())); }, backgroundColor: Theme.of(context).colorScheme.primary, child: Icon( Icons.add, color: Theme.of(context).colorScheme.onPrimary, ), ), body: StreamBuilder( stream: FirebaseFirestore.instance .collection('chats') .orderBy('lastActivity', descending: true) .snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } if (!snapshot.hasData || snapshot.data!.docs.isEmpty) { return const Center( child: Text('No chats found.'), ); } if (snapshot.hasError) { return const Center( child: Text('Something went wrong...'), ); } final loadedchats = snapshot.data!.docs; final chatsWithUser = loadedchats.where((chat) { final participants = chat['participants'] as List<dynamic>; return participants.contains(authenticatedUser.uid); }).toList(); if (chatsWithUser.isEmpty) { return const Center( child: Text('No chats found.'), ); } return ListView.builder( reverse: false, itemCount: chatsWithUser.length, itemBuilder: (context, index) { final chatWithUser = chatsWithUser[index].data(); return ListTile( leading: CircleAvatar( radius: 26, backgroundImage: chatWithUser['image_url'].toString() != "" ? CachedNetworkImageProvider(chatWithUser['image_url']) : Image.asset('assets/images/default_profile_photo_1.png') .image, ), title: Text((chatWithUser['name'].length > 40) ? '${chatWithUser['name'].substring(0, 37)}...' : chatWithUser['name']), subtitle: Text( chatWithUser['preview_message'] ?? 'No message yet...'), onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (ctx) => ChatScreen(chatId: chatsWithUser[index].id))); }, ); }, ); }, ), ); } }
0
mirrored_repositories/chitchat-flutter-project/lib
mirrored_repositories/chitchat-flutter-project/lib/screens/splash.dart
import 'package:flutter/material.dart'; class SplashScreen extends StatelessWidget { const SplashScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Chat'), ), body: const Center( child: CircularProgressIndicator(), ), ); } }
0
mirrored_repositories/chitchat-flutter-project
mirrored_repositories/chitchat-flutter-project/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:chitchat/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const App()); // 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/SQFliteTutorial
mirrored_repositories/SQFliteTutorial/lib/databsehelper.dart
import 'dart:async'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:sqlite_database_tutorial/models/User.dart'; class DatabaseHelper { static final DatabaseHelper _instance = new DatabaseHelper.internal(); factory DatabaseHelper() => _instance; final String tableUser = "userTable"; final String columnId = "id"; final String columnUsername = "username"; final String columnPassword = "password"; static Database _db; Future<Database> get db async { if (_db != null) { return _db; } _db = await initDb(); return _db; } DatabaseHelper.internal(); initDb() async { Directory directory = await getApplicationDocumentsDirectory(); String path = join(directory.path, "maindb.db"); var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate); return ourDb; } void _onCreate(Database db, int version) async { await db.execute("CREATE TABLE $tableUser($columnId INTEGER PRIMARY KEY, " "$columnUsername TEXT, $columnPassword TEXT)"); } //insertion Future<int> saveUser(User user) async { var dbClient = await db; int res = await dbClient.insert("$tableUser", user.toMap()); return res; } //get users Future<List> getAllUsers() async { var dbClient = await db; var result = await dbClient.rawQuery("SELECT * FROM $tableUser"); return result.toList(); } Future<int> getCount() async { var dbClient = await db; return Sqflite.firstIntValue( await dbClient.rawQuery("SELECT COUNT (*) FROM $tableUser")); } //get single user Future<User> getUser(int id) async { var dbClient = await db; var result = await dbClient .rawQuery("SELECT * FROM $tableUser WHERE $columnId = $id"); if (result.length == 0) { return null; } return new User.fromMap(result.first); } //delete user Future<int> deleteUser(int id) async { var dbClient = await db; return await dbClient .delete(tableUser, where: "$columnId = ?", whereArgs: [id]); } //update user Future<int> updateUser(User user) async { var dbClient = await db; return await dbClient.update(tableUser, user.toMap(), where: "$columnId = ?", whereArgs: [user.id]); } //close db Future close() async { var dbClient = await db; return dbClient.close(); } }
0
mirrored_repositories/SQFliteTutorial
mirrored_repositories/SQFliteTutorial/lib/main.dart
import 'package:flutter/material.dart'; import 'package:sqlite_database_tutorial/databsehelper.dart'; import 'package:sqlite_database_tutorial/models/User.dart'; List _users; void main() async { var db = new DatabaseHelper(); //add user // int savedUser = await db.saveUser(new User("kkkkk", "lol")); // print("User saved: $savedUser"); int count = await db.getCount(); print("Count: $count"); //get user User user = await db.getUser(3); print("Got user: ${user.username}"); //delete user // int delete = await db.deleteUser(2); // print("Deleted user: $delete"); _users = await db.getAllUsers(); for (int i = 0; i < _users.length; i++) { User user = User.map(_users[i]); print("Username: ${user.username}"); } runApp(new MaterialApp( title: "SQLite Tutorial", home: new Home(), )); } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text("SQLite Tutorial"), centerTitle: true, backgroundColor: Colors.red), body: new ListView.builder( itemCount: _users.length, itemBuilder: (_, int position) { // _ => means we are using _users context return Card( color: Colors.white, elevation: 2.0, child: new ListTile( leading: new CircleAvatar( backgroundColor: Colors.purple, child: new Text( "${User.fromMap(_users[position]).username.substring(0, 1)}", style: TextStyle(color: Colors.white)), ), title: new Text("User: ${User.fromMap(_users[position]).username}"), subtitle: new Text("Id: ${User.fromMap(_users[position]).id}"), onTap: () => debugPrint("${User.fromMap(_users[position]).password}"), ), ); }, ), ); } }
0
mirrored_repositories/SQFliteTutorial/lib
mirrored_repositories/SQFliteTutorial/lib/models/User.dart
class User { String _username; String _password; int _id; User(this._username, this._password); User.map(dynamic obj) { this._username = obj['username']; this._password = obj['password']; this._id = obj['id']; } String get username => _username; String get password => _password; int get id => _id; Map<String, dynamic> toMap() { var map = new Map<String, dynamic>(); map["username"] = _username; map["password"] = _password; if (_id != null) { map["id"] = _id; } return map; } User.fromMap(Map<String, dynamic> map) { this._username = map["username"]; this._password = map["password"]; this._id = map["id"]; } }
0
mirrored_repositories/vpec
mirrored_repositories/vpec/lib/splash.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:quick_actions/quick_actions.dart'; import 'screens/bottom_bar/bottom_bar_logic.dart'; import 'screens/login/login_screen.dart'; import 'utils/firebase_auth.dart'; import 'utils/hive_helper.dart'; import 'utils/theme_helper.dart'; class SplashScreen extends StatefulWidget { final Widget child; const SplashScreen({Key? key, required this.child}) : super(key: key); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { late FirebaseAppAuth appAuth; @override void initState() { appAuth = Provider.of<FirebaseAppAuth>(context, listen: false); _initApp(); super.initState(); } Future<void> _initApp() async { //make all our date in russian await initializeDateFormatting('ru'); Intl.defaultLocale = 'ru'; const QuickActions quickActions = QuickActions(); if (appAuth.accountInfo.isLoggedIn) { // if app running on Android or iOS, make QuickActions if (defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS) { quickActions.initialize((shortcutType) { switch (shortcutType) { case 'action_news': context.read<BottomBarLogic>().setIndex(0); break; case 'action_announcements': context.read<BottomBarLogic>().setIndex(1); break; case 'action_schedule': context.read<BottomBarLogic>().setIndex(2); break; case 'action_map': context.read<BottomBarLogic>().setIndex(3); break; } FirebaseAnalytics.instance.logEvent(name: 'quick_action_used', parameters: { 'shortcut_type': shortcutType, }); }); quickActions.setShortcutItems(<ShortcutItem>[ const ShortcutItem( type: 'action_news', localizedTitle: 'События', icon: 'ic_news', ), const ShortcutItem( type: 'action_announcements', localizedTitle: 'Объявления', icon: 'ic_alerts', ), const ShortcutItem( type: 'action_schedule', localizedTitle: 'Расписание занятий', icon: 'ic_timetable', ), const ShortcutItem( type: 'action_map', localizedTitle: 'Карта кабинетов', icon: 'ic_maps', ), ]); } // open bottom bar index by setting "launch on start" if (HiveHelper.getValue('launchOnStart') != null) { int givenIndex = HiveHelper.getValue('launchOnStart'); context.read<BottomBarLogic>().setIndex(givenIndex); } FlutterLocalNotificationsPlugin() .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.requestPermission(); } else { quickActions.clearShortcutItems(); } FirebaseAnalytics.instance.logAppOpen(); } @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return appAuth.accountInfo.isLoggedIn ? widget.child : const LoginScreen(); } }
0
mirrored_repositories/vpec
mirrored_repositories/vpec/lib/main.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:fluro/fluro.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:provider/provider.dart'; import 'package:url_strategy/url_strategy.dart'; import '/utils/utils.dart'; import 'utils/firebase_auth.dart'; import 'utils/hive_helper.dart'; import 'utils/notifications/firebase_messaging.dart'; import 'utils/notifications/local_notifications.dart'; import 'utils/routes/routes.dart'; import 'utils/theme/theme.dart'; import 'utils/theme_helper.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); setPathUrlStrategy(); // remove # from url path await AndroidSdkVersion.getAndSave(); useHttpOverrides(); await HiveHelper.initHive(); await Firebase.initializeApp(); await LocalNotifications.initializeNotifications(); AppFirebaseMessaging.startListening(); ThemeHelper.doInitialChrome(); runApp(MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => FirebaseAppAuth()), ChangeNotifierProvider( create: (_) => ThemeNotifier( ThemeHelper.isDarkMode ? ThemeMode.dark : ThemeMode.light, ), ), ], child: const VPECApp(), )); } class VPECApp extends StatefulWidget { const VPECApp({Key? key}) : super(key: key); @override State<VPECApp> createState() => _VPECAppState(); } class _VPECAppState extends State<VPECApp> { final router = FluroRouter(); @override void initState() { Routes.defineRoutes(router); Routes.router = router; Provider.of<FirebaseAppAuth>(context, listen: false).startListening(); final window = WidgetsBinding.instance.window; window.onPlatformBrightnessChanged = () { // This callback gets invoked every time brightness changes setState(() { context.read<ThemeNotifier>().changeTheme( ThemeHelper.isDarkMode ? ThemeMode.dark : ThemeMode.light, ); }); }; super.initState(); } @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: const [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('ru', 'RU'), Locale('en', 'US'), ], theme: themeData(), darkTheme: darkThemeData(), themeMode: context.watch<ThemeNotifier>().themeMode, initialRoute: '/', onGenerateRoute: Routes.router.generator, debugShowCheckedModeBanner: false, navigatorObservers: <NavigatorObserver>[ FirebaseAnalyticsObserver( analytics: FirebaseAnalytics.instance, ), ], ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/md2_tab_indicator.dart
import 'package:flutter/material.dart'; class MD2TabIndicator extends Decoration { final Color indicatorColor; /// Custom decoration for active tab indicator. /// /// For intended look, the TabBar height should be 48 (default) const MD2TabIndicator(this.indicatorColor); @override BoxPainter createBoxPainter([VoidCallback? onChanged]) { return _MD2Painter(this, onChanged!); } } class _MD2Painter extends BoxPainter { final MD2TabIndicator indicator; _MD2Painter(this.indicator, VoidCallback onChanged) : super(onChanged); @override void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { Rect rect = Offset(offset.dx, (configuration.size!.height - 48)) & Size(configuration.size!.width, 4); final Paint paint = Paint(); paint.color = indicator.indicatorColor; paint.style = PaintingStyle.fill; canvas.drawRRect( RRect.fromRectAndCorners( rect, bottomRight: const Radius.circular(4), bottomLeft: const Radius.circular(4), ), paint, ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/system_bar_cover.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../utils/theme/theme.dart'; import '../utils/theme_helper.dart'; /// Used to cover content under system status bar with semi-transparent fill. /// /// Used as [appBar] in [Scaffold]. /// Requires height of status bar - /// usually [MediaQuery.of(context).padding.top]. /// Also requires [extendBodyBehindAppBar] in [Scaffold] to be set to true. class StatusBarCover extends StatelessWidget implements PreferredSizeWidget { const StatusBarCover({Key? key, required this.height}) : super(key: key); final double height; @override Widget build(BuildContext context) { return SizedBox( height: height, child: ColoredBox( color: context.palette.backgroundSurface.withOpacity(0.8), ), ); } @override Size get preferredSize => Size.fromHeight(height); } /// Used to cover content under system navigation bar with semi-transparent fill. /// /// Used as [bottomNavigationBar] in [Scaffold]. /// Requires height of system navigation bar - /// usually [MediaQuery.of(context).padding.bottom]. /// Also requires [extendBody] in [Scaffold] to be set to true. class SystemNavBarCover extends StatelessWidget { const SystemNavBarCover({Key? key, required this.height}) : super(key: key); final double height; @override Widget build(BuildContext context) { return AnnotatedRegion<SystemUiOverlayStyle>( value: ThemeHelper.overlayStyleHelper(context.palette.backgroundSurface), child: Padding( // ensures that cover is rendered - otherwise AnnotatedRegion will break padding: const EdgeInsets.only(top: 1.0), child: SizedBox( height: height, child: ColoredBox( color: context.palette.backgroundSurface.withOpacity(0.8), ), ), ), ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/snow_widget.dart
// Snow by https://github.com/windwp/ // Repo: https://github.com/windwp/flutter-snow-effect // Modified by ShyroTeam import 'dart:math'; import 'package:flutter/material.dart'; class SnowWidget extends StatefulWidget { final int? totalSnow; final double? speed; final bool? isRunning; final Color? snowColor; const SnowWidget({ Key? key, this.totalSnow, this.speed, this.isRunning, this.snowColor, }) : super(key: key); @override State<SnowWidget> createState() => _SnowWidgetState(); } class _SnowWidgetState extends State<SnowWidget> with SingleTickerProviderStateMixin { late Random _rnd; AnimationController? controller; Animation? animation; List<Snow>? _snows; double angle = 0; double W = 0; double H = 0; @override void initState() { super.initState(); init(); } void init() { _rnd = Random(); if (controller == null) { controller = AnimationController( lowerBound: 0, upperBound: 1, vsync: this, duration: const Duration(milliseconds: 20000), ); controller!.addListener(() { if (mounted) { setState(() { update(); }); } }); } if (!widget.isRunning!) { controller!.stop(); } else { controller!.repeat(); } } @override dispose() { controller!.dispose(); super.dispose(); } void _createSnow() { _snows = []; for (var i = 0; i < widget.totalSnow!; i++) { _snows!.add(Snow( x: _rnd.nextDouble() * W, y: _rnd.nextDouble() * H, r: _rnd.nextDouble() * 4 + 1, d: _rnd.nextDouble() * widget.speed!, )); } } void update() { angle += 0.01; if (_snows == null || widget.totalSnow != _snows!.length) { _createSnow(); } for (var i = 0; i < widget.totalSnow!; i++) { var snow = _snows![i]; //We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards //Every particle has its own density which can be used to make the downward movement different for each flake //Lets make it more random by adding in the radius snow.y = snow.y! + (cos(angle + snow.d!) + 1 + snow.r! / 2) * widget.speed!; snow.x = snow.x! + sin(angle) * 2 * widget.speed!; if (snow.x! > W + 5 || snow.x! < -5 || snow.y! > H) { if (i % 3 > 0) { //66.67% of the flakes _snows![i] = Snow(x: _rnd.nextDouble() * W, y: -10, r: snow.r, d: snow.d); } else { //If the flake is exiting from the right if (sin(angle) > 0) { //Enter from the left _snows![i] = Snow(x: -5, y: _rnd.nextDouble() * H, r: snow.r, d: snow.d); } else { //Enter from the right _snows![i] = Snow(x: W + 5, y: _rnd.nextDouble() * H, r: snow.r, d: snow.d); } } } } } @override Widget build(BuildContext context) { if (widget.isRunning! && !controller!.isAnimating) { controller!.repeat(); } else if (!widget.isRunning! && controller!.isAnimating) { controller!.stop(); } return LayoutBuilder( builder: (context, constraints) { if (_snows == null) { W = constraints.maxWidth; H = constraints.maxHeight; } return CustomPaint( willChange: widget.isRunning!, painter: SnowPainter( // progress: controller.value, isRunning: widget.isRunning, snows: _snows, snowColor: widget.snowColor, ), size: Size.infinite, ); }, ); } } class Snow { double? x; double? y; double? r; //radius double? d; //density Snow({this.x, this.y, this.r, this.d}); } class SnowPainter extends CustomPainter { List<Snow>? snows; bool? isRunning; Color? snowColor; SnowPainter({this.isRunning, this.snows, this.snowColor}); @override void paint(Canvas canvas, Size size) { if (snows == null || !isRunning!) return; //draw circle final Paint paint = Paint() ..color = snowColor! ..strokeCap = StrokeCap.round ..strokeWidth = 10.0; for (var i = 0; i < snows!.length; i++) { var snow = snows![i]; canvas.drawCircle(Offset(snow.x!, snow.y!), snow.r!, paint); } } @override bool shouldRepaint(SnowPainter oldDelegate) => isRunning!; }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/confirm_delete_dialog.dart
import 'package:flutter/material.dart'; class DeleteDialogUI extends StatelessWidget { final void Function() onDelete; const DeleteDialogUI({Key? key, required this.onDelete}) : super(key: key); @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: OutlinedButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), const SizedBox(width: 10), Expanded( child: OutlinedButton( onPressed: () { Navigator.pop(context); onDelete(); }, child: const Text('Удалить'), ), ), ], ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/snackbars.dart
import 'package:flutter/material.dart'; import '../utils/theme/theme.dart'; void showSnackBar( BuildContext context, { required String text, SnackBarBehavior behavior = SnackBarBehavior.floating, Duration duration = const Duration(milliseconds: 4000), }) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( backgroundColor: context.palette.levelTwoSurface, behavior: behavior, duration: duration, content: Text(text, style: Theme.of(context).textTheme.subtitle2), )); }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/interactive_widget.dart
import 'package:flutter/material.dart'; class InteractiveWidget extends StatefulWidget { const InteractiveWidget({ Key? key, required this.child, this.onInteractionUpdate, }) : super(key: key); final Widget child; final Function(double)? onInteractionUpdate; @override State<InteractiveWidget> createState() => _InteractiveWidgetState(); } class _InteractiveWidgetState extends State<InteractiveWidget> with TickerProviderStateMixin { final transformationController = TransformationController(); late AnimationController _zoomAnimationController; late AnimationController _zoomOutAnimationController; bool _zoomed = false; final Offset _dragPosition = const Offset(0.0, 0.0); void transformListener() { final scale = transformationController.value.row0.r; if (scale > 1 && !_zoomed) { setState(() => _zoomed = true); _zoomOutAnimationController.reset(); } else if (scale <= 1 && _zoomed) { setState(() => _zoomed = false); _zoomAnimationController.reset(); } } @override void initState() { transformationController.addListener(transformListener); _zoomAnimationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 200), ); _zoomOutAnimationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 200), ); super.initState(); } @override void dispose() { transformationController.removeListener(transformListener); super.dispose(); } void animateZoom({ required Matrix4 end, required AnimationController animationController, }) { final mapAnimation = Matrix4Tween( begin: transformationController.value, end: end, ).animate(animationController); void animationListener() { transformationController.value = mapAnimation.value; if (transformationController.value == end) { mapAnimation.removeListener(animationListener); } } mapAnimation.addListener(animationListener); animationController.forward(); } void doubleTapDownHandler(TapDownDetails details) { if (_zoomed) { final defaultMatrix = Matrix4.diagonal3Values(1, 1, 1); animateZoom( animationController: _zoomOutAnimationController, end: defaultMatrix, ); } else { final x = -details.localPosition.dx; final y = -details.localPosition.dy; const scaleMultiplier = 2.0; final zoomedMatrix = Matrix4( // a0 a1 a2 a3 scaleMultiplier, 0.0, 0.0, 0, // a0 a1 a2 a3 0.0, scaleMultiplier, 0.0, 0, // a0 a1 a2 a3 0.0, 0.0, 1.0, 0.0, // a0 a1 a2 a3 x, y, 0.0, 1.0, ); animateZoom( animationController: _zoomAnimationController, end: zoomedMatrix, ); } } /// Required for `onDoubleTapDown` to work void onDoubleTap() {} //ignore: no-empty-block @override Widget build(BuildContext context) { return Center( child: Stack( children: [ Positioned( left: _dragPosition.dx, top: _dragPosition.dy, bottom: -_dragPosition.dy, right: -_dragPosition.dx, child: GestureDetector( onDoubleTapDown: doubleTapDownHandler, onDoubleTap: onDoubleTap, child: InteractiveViewer( onInteractionUpdate: (details) { if (widget.onInteractionUpdate != null) { double correctScaleValue = transformationController.value.getMaxScaleOnAxis(); widget.onInteractionUpdate!(correctScaleValue); } }, minScale: 0.8, maxScale: 8.0, transformationController: transformationController, child: widget.child, ), ), ), ], ), ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/styled_widgets.dart
import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; /// create ListTile where subtitle value getting from Hive. /// /// [subtitleKey] - Hive key to get value /// /// [defaultValue] - If key have no value, show this text class HivedListTile extends StatelessWidget { final String title, subtitleKey, defaultValue; final void Function()? onTap; final Icon? icon; const HivedListTile({ Key? key, required this.title, required this.subtitleKey, required this.defaultValue, this.onTap, this.icon, }) : super(key: key); @override Widget build(BuildContext context) { return StyledListTile( icon: icon, title: title, subtitleWidget: ValueListenableBuilder( valueListenable: Hive.box('settings').listenable(keys: [subtitleKey]), builder: (context, Box box, child) { return Text( box.get(subtitleKey, defaultValue: defaultValue), style: Theme.of(context).textTheme.subtitle1, ); }, ), onTap: onTap, ); } } /// Just create normal ListTile with styled text class StyledListTile extends StatelessWidget { final Widget? trailing, icon, subtitleWidget; final String? title, subtitle; final void Function()? onTap; const StyledListTile({ Key? key, this.trailing, this.icon, this.title, this.subtitle, this.onTap, this.subtitleWidget, }) : super(key: key); @override Widget build(BuildContext context) { return ListTile( horizontalTitleGap: 8, dense: true, contentPadding: const EdgeInsets.symmetric(vertical: 6, horizontal: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), trailing: trailing, leading: icon == null ? null : SizedBox(height: double.infinity, child: icon), title: Text( title ?? '', style: Theme.of(context).textTheme.headline3, ), subtitle: subtitleWidget ?? Text( subtitle ?? '', style: Theme.of(context).textTheme.subtitle1, ), onTap: onTap, ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/loading_indicator.dart
import 'package:flutter/material.dart'; class LoadingIndicator extends StatelessWidget { const LoadingIndicator({ Key? key, this.delayedAppears = true, this.appearsDuration = const Duration(milliseconds: 200), }) : super(key: key); /// `true` by default. /// /// When [true] [LoadingIndicator] will appear after [appearsDuration] time. /// By default appear time is `Duration(milliseconds: 200)` final bool delayedAppears; /// After this time [LoadingIndicator] will appear. /// By default this value is `Duration(milliseconds: 200)` final Duration appearsDuration; @override Widget build(BuildContext context) { if (delayedAppears) return appearsIndicator; return usualIndicator; } Widget get usualIndicator { return const Center( child: CircularProgressIndicator(), ); } Widget get appearsIndicator { return FutureBuilder<bool>( initialData: false, future: awaitMoment(), builder: (BuildContext context, AsyncSnapshot<bool> snapshot) { if (snapshot.data!) return usualIndicator; return const SizedBox(); }, ); } Future<bool> awaitMoment() async { await Future.delayed(appearsDuration); return true; } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/widgets/markdown_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import '/models/document_model.dart'; import '/screens/view_document/view_document_logic.dart'; import '/utils/utils.dart'; import '../utils/theme/theme.dart'; /// Create markdown with branded colors and text style class MarkdownWidget extends StatelessWidget { const MarkdownWidget({ Key? key, required this.data, this.shrinkWrap = false, this.onTapLink, }) : super(key: key); /// MD data to display, example: /// /// `# Hello World` final String data; final bool shrinkWrap; /// `String text, String? href, String title` /// /// Called when user click on link final void Function(String, String?, String)? onTapLink; @override Widget build(BuildContext context) { return GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: Markdown( shrinkWrap: shrinkWrap, selectable: true, data: data, onTapLink: onTapLink ?? (text, href, title) { if (href != null) { if (ViewDocumentLogic.isThisURLSupported(href)) { Navigator.pushNamed( context, '/view_document', arguments: DocumentModel( title: text, subtitle: '', url: href, ), ); } else { openUrl(href); } } }, styleSheet: MarkdownStyleSheet( h1: const TextStyle( fontFamily: 'Montserrat', fontSize: 48, fontWeight: FontWeight.w400, letterSpacing: -0.5, ), h2: const TextStyle( fontFamily: 'Montserrat', fontSize: 38, fontWeight: FontWeight.w400, ), h3: TextStyle( color: context.palette.highEmphasis, fontFamily: 'Montserrat', fontSize: 32, fontWeight: FontWeight.w400, letterSpacing: 0.25, ), h4: const TextStyle( fontFamily: 'Montserrat', fontSize: 28, fontWeight: FontWeight.w500, ), h5: const TextStyle( fontFamily: 'Montserrat', fontSize: 24, fontWeight: FontWeight.w500, letterSpacing: 0.15, ), h6: const TextStyle( fontFamily: 'Montserrat', fontSize: 20, fontWeight: FontWeight.w600, letterSpacing: 0.2, ), p: TextStyle( color: context.palette.highEmphasis, fontFamily: 'Roboto', fontSize: 16, fontWeight: FontWeight.w400, letterSpacing: 0.5, ), ), ), ); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/account_info.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'account_info.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$AccountInfo { bool get isLoggedIn => throw _privateConstructorUsedError; String? get email => throw _privateConstructorUsedError; String? get uid => throw _privateConstructorUsedError; String? get name => throw _privateConstructorUsedError; AccountType get level => throw _privateConstructorUsedError; @JsonKey(ignore: true) $AccountInfoCopyWith<AccountInfo> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $AccountInfoCopyWith<$Res> { factory $AccountInfoCopyWith( AccountInfo value, $Res Function(AccountInfo) then) = _$AccountInfoCopyWithImpl<$Res, AccountInfo>; @useResult $Res call( {bool isLoggedIn, String? email, String? uid, String? name, AccountType level}); } /// @nodoc class _$AccountInfoCopyWithImpl<$Res, $Val extends AccountInfo> implements $AccountInfoCopyWith<$Res> { _$AccountInfoCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? isLoggedIn = null, Object? email = freezed, Object? uid = freezed, Object? name = freezed, Object? level = null, }) { return _then(_value.copyWith( isLoggedIn: null == isLoggedIn ? _value.isLoggedIn : isLoggedIn // ignore: cast_nullable_to_non_nullable as bool, email: freezed == email ? _value.email : email // ignore: cast_nullable_to_non_nullable as String?, uid: freezed == uid ? _value.uid : uid // ignore: cast_nullable_to_non_nullable as String?, name: freezed == name ? _value.name : name // ignore: cast_nullable_to_non_nullable as String?, level: null == level ? _value.level : level // ignore: cast_nullable_to_non_nullable as AccountType, ) as $Val); } } /// @nodoc abstract class _$$_AccountInfoCopyWith<$Res> implements $AccountInfoCopyWith<$Res> { factory _$$_AccountInfoCopyWith( _$_AccountInfo value, $Res Function(_$_AccountInfo) then) = __$$_AccountInfoCopyWithImpl<$Res>; @override @useResult $Res call( {bool isLoggedIn, String? email, String? uid, String? name, AccountType level}); } /// @nodoc class __$$_AccountInfoCopyWithImpl<$Res> extends _$AccountInfoCopyWithImpl<$Res, _$_AccountInfo> implements _$$_AccountInfoCopyWith<$Res> { __$$_AccountInfoCopyWithImpl( _$_AccountInfo _value, $Res Function(_$_AccountInfo) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? isLoggedIn = null, Object? email = freezed, Object? uid = freezed, Object? name = freezed, Object? level = null, }) { return _then(_$_AccountInfo( isLoggedIn: null == isLoggedIn ? _value.isLoggedIn : isLoggedIn // ignore: cast_nullable_to_non_nullable as bool, email: freezed == email ? _value.email : email // ignore: cast_nullable_to_non_nullable as String?, uid: freezed == uid ? _value.uid : uid // ignore: cast_nullable_to_non_nullable as String?, name: freezed == name ? _value.name : name // ignore: cast_nullable_to_non_nullable as String?, level: null == level ? _value.level : level // ignore: cast_nullable_to_non_nullable as AccountType, )); } } /// @nodoc class _$_AccountInfo implements _AccountInfo { const _$_AccountInfo( {required this.isLoggedIn, this.email, this.uid, this.name, required this.level}); @override final bool isLoggedIn; @override final String? email; @override final String? uid; @override final String? name; @override final AccountType level; @override String toString() { return 'AccountInfo(isLoggedIn: $isLoggedIn, email: $email, uid: $uid, name: $name, level: $level)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_AccountInfo && (identical(other.isLoggedIn, isLoggedIn) || other.isLoggedIn == isLoggedIn) && (identical(other.email, email) || other.email == email) && (identical(other.uid, uid) || other.uid == uid) && (identical(other.name, name) || other.name == name) && (identical(other.level, level) || other.level == level)); } @override int get hashCode => Object.hash(runtimeType, isLoggedIn, email, uid, name, level); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_AccountInfoCopyWith<_$_AccountInfo> get copyWith => __$$_AccountInfoCopyWithImpl<_$_AccountInfo>(this, _$identity); } abstract class _AccountInfo implements AccountInfo { const factory _AccountInfo( {required final bool isLoggedIn, final String? email, final String? uid, final String? name, required final AccountType level}) = _$_AccountInfo; @override bool get isLoggedIn; @override String? get email; @override String? get uid; @override String? get name; @override AccountType get level; @override @JsonKey(ignore: true) _$$_AccountInfoCopyWith<_$_AccountInfo> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/admin_model.dart
class AdminModel { final String? name; final String? contact; final String? cabinet; final String? post; const AdminModel({ this.name, this.contact, this.cabinet, this.post, }); AdminModel.fromMap(Map<String, dynamic> data, String id) : this( name: data['name'], contact: data['contact'], cabinet: data['cabinet'], post: data['post'], ); }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/account_info.dart
import 'package:freezed_annotation/freezed_annotation.dart'; import '../utils/firebase_auth.dart'; part 'account_info.freezed.dart'; @freezed class AccountInfo with _$AccountInfo { const factory AccountInfo({ required bool isLoggedIn, String? email, String? uid, String? name, required AccountType level, }) = _AccountInfo; }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/full_schedule.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'full_schedule.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$FullSchedule { List<String?> get timers => throw _privateConstructorUsedError; String get groups => throw _privateConstructorUsedError; Map<String, dynamic> get schedule => throw _privateConstructorUsedError; Map<String, dynamic> get timetable => throw _privateConstructorUsedError; Map<String, dynamic> get shortLessonNames => throw _privateConstructorUsedError; Map<String, dynamic> get fullLessonNames => throw _privateConstructorUsedError; Map<String, dynamic> get teachers => throw _privateConstructorUsedError; @JsonKey(ignore: true) $FullScheduleCopyWith<FullSchedule> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $FullScheduleCopyWith<$Res> { factory $FullScheduleCopyWith( FullSchedule value, $Res Function(FullSchedule) then) = _$FullScheduleCopyWithImpl<$Res, FullSchedule>; @useResult $Res call( {List<String?> timers, String groups, Map<String, dynamic> schedule, Map<String, dynamic> timetable, Map<String, dynamic> shortLessonNames, Map<String, dynamic> fullLessonNames, Map<String, dynamic> teachers}); } /// @nodoc class _$FullScheduleCopyWithImpl<$Res, $Val extends FullSchedule> implements $FullScheduleCopyWith<$Res> { _$FullScheduleCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? timers = null, Object? groups = null, Object? schedule = null, Object? timetable = null, Object? shortLessonNames = null, Object? fullLessonNames = null, Object? teachers = null, }) { return _then(_value.copyWith( timers: null == timers ? _value.timers : timers // ignore: cast_nullable_to_non_nullable as List<String?>, groups: null == groups ? _value.groups : groups // ignore: cast_nullable_to_non_nullable as String, schedule: null == schedule ? _value.schedule : schedule // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, timetable: null == timetable ? _value.timetable : timetable // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, shortLessonNames: null == shortLessonNames ? _value.shortLessonNames : shortLessonNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, fullLessonNames: null == fullLessonNames ? _value.fullLessonNames : fullLessonNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, teachers: null == teachers ? _value.teachers : teachers // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, ) as $Val); } } /// @nodoc abstract class _$$_FullScheduleCopyWith<$Res> implements $FullScheduleCopyWith<$Res> { factory _$$_FullScheduleCopyWith( _$_FullSchedule value, $Res Function(_$_FullSchedule) then) = __$$_FullScheduleCopyWithImpl<$Res>; @override @useResult $Res call( {List<String?> timers, String groups, Map<String, dynamic> schedule, Map<String, dynamic> timetable, Map<String, dynamic> shortLessonNames, Map<String, dynamic> fullLessonNames, Map<String, dynamic> teachers}); } /// @nodoc class __$$_FullScheduleCopyWithImpl<$Res> extends _$FullScheduleCopyWithImpl<$Res, _$_FullSchedule> implements _$$_FullScheduleCopyWith<$Res> { __$$_FullScheduleCopyWithImpl( _$_FullSchedule _value, $Res Function(_$_FullSchedule) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? timers = null, Object? groups = null, Object? schedule = null, Object? timetable = null, Object? shortLessonNames = null, Object? fullLessonNames = null, Object? teachers = null, }) { return _then(_$_FullSchedule( timers: null == timers ? _value._timers : timers // ignore: cast_nullable_to_non_nullable as List<String?>, groups: null == groups ? _value.groups : groups // ignore: cast_nullable_to_non_nullable as String, schedule: null == schedule ? _value._schedule : schedule // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, timetable: null == timetable ? _value._timetable : timetable // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, shortLessonNames: null == shortLessonNames ? _value._shortLessonNames : shortLessonNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, fullLessonNames: null == fullLessonNames ? _value._fullLessonNames : fullLessonNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, teachers: null == teachers ? _value._teachers : teachers // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, )); } } /// @nodoc class _$_FullSchedule implements _FullSchedule { const _$_FullSchedule( {final List<String?> timers = const [], required this.groups, required final Map<String, dynamic> schedule, required final Map<String, dynamic> timetable, required final Map<String, dynamic> shortLessonNames, required final Map<String, dynamic> fullLessonNames, required final Map<String, dynamic> teachers}) : _timers = timers, _schedule = schedule, _timetable = timetable, _shortLessonNames = shortLessonNames, _fullLessonNames = fullLessonNames, _teachers = teachers; final List<String?> _timers; @override @JsonKey() List<String?> get timers { // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_timers); } @override final String groups; final Map<String, dynamic> _schedule; @override Map<String, dynamic> get schedule { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_schedule); } final Map<String, dynamic> _timetable; @override Map<String, dynamic> get timetable { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_timetable); } final Map<String, dynamic> _shortLessonNames; @override Map<String, dynamic> get shortLessonNames { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_shortLessonNames); } final Map<String, dynamic> _fullLessonNames; @override Map<String, dynamic> get fullLessonNames { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_fullLessonNames); } final Map<String, dynamic> _teachers; @override Map<String, dynamic> get teachers { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_teachers); } @override String toString() { return 'FullSchedule(timers: $timers, groups: $groups, schedule: $schedule, timetable: $timetable, shortLessonNames: $shortLessonNames, fullLessonNames: $fullLessonNames, teachers: $teachers)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_FullSchedule && const DeepCollectionEquality().equals(other._timers, _timers) && (identical(other.groups, groups) || other.groups == groups) && const DeepCollectionEquality().equals(other._schedule, _schedule) && const DeepCollectionEquality() .equals(other._timetable, _timetable) && const DeepCollectionEquality() .equals(other._shortLessonNames, _shortLessonNames) && const DeepCollectionEquality() .equals(other._fullLessonNames, _fullLessonNames) && const DeepCollectionEquality().equals(other._teachers, _teachers)); } @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(_timers), groups, const DeepCollectionEquality().hash(_schedule), const DeepCollectionEquality().hash(_timetable), const DeepCollectionEquality().hash(_shortLessonNames), const DeepCollectionEquality().hash(_fullLessonNames), const DeepCollectionEquality().hash(_teachers)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_FullScheduleCopyWith<_$_FullSchedule> get copyWith => __$$_FullScheduleCopyWithImpl<_$_FullSchedule>(this, _$identity); } abstract class _FullSchedule implements FullSchedule { const factory _FullSchedule( {final List<String?> timers, required final String groups, required final Map<String, dynamic> schedule, required final Map<String, dynamic> timetable, required final Map<String, dynamic> shortLessonNames, required final Map<String, dynamic> fullLessonNames, required final Map<String, dynamic> teachers}) = _$_FullSchedule; @override List<String?> get timers; @override String get groups; @override Map<String, dynamic> get schedule; @override Map<String, dynamic> get timetable; @override Map<String, dynamic> get shortLessonNames; @override Map<String, dynamic> get fullLessonNames; @override Map<String, dynamic> get teachers; @override @JsonKey(ignore: true) _$$_FullScheduleCopyWith<_$_FullSchedule> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/full_schedule.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'full_schedule.freezed.dart'; @freezed class FullSchedule with _$FullSchedule { const factory FullSchedule({ @Default([]) List<String?> timers, required String groups, required Map<String, dynamic> schedule, required Map<String, dynamic> timetable, required Map<String, dynamic> shortLessonNames, required Map<String, dynamic> fullLessonNames, required Map<String, dynamic> teachers, }) = _FullSchedule; }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/document_model.dart
// this model used in menu_ui class DocumentModel { final String title; final String subtitle; final String url; DocumentModel({ required this.title, required this.subtitle, required this.url, }); DocumentModel.fromMap(Map<String, dynamic> data, String id) : this( title: data['title'], subtitle: data['subtitle'], url: data['url'], ); }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/time_model.dart
// this model used in TimeTable class TimeModel { final String? startLesson; final String? endLesson; final String? pause; final String? name; final String? id; const TimeModel({ this.startLesson, this.endLesson, this.pause, this.name, this.id, }); TimeModel.fromMap(Map<String, dynamic> data, String id) : this( name: data['name'], startLesson: data['start'], endLesson: data['end'], pause: data['pause'], id: id, ); Map<String, dynamic> toMap(int docID) { return { 'name': name, 'start': startLesson, 'end': endLesson, 'pause': pause, 'order': docID, }; } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/teacher_model.dart
class TeacherModel { final String? familyName; final String? firstName; final String? secondaryName; final String? fullName; final String? cabinet; final String? lesson; final String? id; const TeacherModel({ this.familyName, this.firstName, this.secondaryName, this.fullName, this.cabinet, this.lesson, this.id, }); TeacherModel.fromMap(Map<String, dynamic> data, String id) : this( familyName: data['familyName'], firstName: data['firstName'], secondaryName: data['secondaryName'], fullName: "${data['familyName']} ${data['firstName']} ${data['secondaryName']}", cabinet: data['cabinet'], lesson: data['lesson'], id: id, ); Map<String, dynamic> toMap(int docID) { return { 'familyName': familyName, 'firstName': firstName, 'secondaryName': secondaryName, 'cabinet': cabinet, 'lesson': lesson, 'order': docID, }; } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/models/announcement_model.dart
// this model used for AnnouncementsScreen import '../utils/firebase_auth.dart'; class AnnouncementModel { final String author; final String content; final String pubDate; final String title; final String docId; final AccountType accessLevel; final String? photoUrl; const AnnouncementModel({ required this.author, required this.content, required this.pubDate, required this.title, required this.docId, required this.accessLevel, this.photoUrl, }); AnnouncementModel.fromMap(Map<String, dynamic> data, String id) : this( pubDate: data['date'], author: data['author'], content: data['content_body'], title: data['content_title'], accessLevel: parseAccountType(data['visibility']), photoUrl: data['photo'], docId: id, ); static AccountType parseAccountType(String data) { switch (data) { case 'students': return AccountType.student; case 'teachers': return AccountType.teacher; case 'parents': return AccountType.parent; case 'admins': return AccountType.admin; default: return AccountType.entrant; } } }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/group_definition.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'group_definition.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_GroupDefinition _$$_GroupDefinitionFromJson(Map<String, dynamic> json) { $checkKeys( json, requiredKeys: const ['definition'], disallowNullValues: const ['definition'], ); return _$_GroupDefinition( groupDefinitionMap: json['definition'] as Map<String, dynamic>, ); } Map<String, dynamic> _$$_GroupDefinitionToJson(_$_GroupDefinition instance) => <String, dynamic>{ 'definition': instance.groupDefinitionMap, };
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/schedule_item.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'schedule_item.freezed.dart'; @freezed class ScheduleItemModel with _$ScheduleItemModel { const factory ScheduleItemModel({ required int lessonNumber, required String lessonBeginning, required String lessonEnding, required String lessonName, required String pauseAfterLesson, String? timer, required Map<String, dynamic> teachers, required Map<String, dynamic> lessonsShortNames, required Map<String, dynamic> lessonsFullNames, }) = _ScheduleItemModel; }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/group_list.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'group_list.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); GroupList _$GroupListFromJson(Map<String, dynamic> json) { return _GroupList.fromJson(json); } /// @nodoc mixin _$GroupList { @JsonKey(name: 'groupList', required: true, disallowNullValue: true) List<String> get groupList => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $GroupListCopyWith<GroupList> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $GroupListCopyWith<$Res> { factory $GroupListCopyWith(GroupList value, $Res Function(GroupList) then) = _$GroupListCopyWithImpl<$Res, GroupList>; @useResult $Res call( {@JsonKey(name: 'groupList', required: true, disallowNullValue: true) List<String> groupList}); } /// @nodoc class _$GroupListCopyWithImpl<$Res, $Val extends GroupList> implements $GroupListCopyWith<$Res> { _$GroupListCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? groupList = null, }) { return _then(_value.copyWith( groupList: null == groupList ? _value.groupList : groupList // ignore: cast_nullable_to_non_nullable as List<String>, ) as $Val); } } /// @nodoc abstract class _$$_GroupListCopyWith<$Res> implements $GroupListCopyWith<$Res> { factory _$$_GroupListCopyWith( _$_GroupList value, $Res Function(_$_GroupList) then) = __$$_GroupListCopyWithImpl<$Res>; @override @useResult $Res call( {@JsonKey(name: 'groupList', required: true, disallowNullValue: true) List<String> groupList}); } /// @nodoc class __$$_GroupListCopyWithImpl<$Res> extends _$GroupListCopyWithImpl<$Res, _$_GroupList> implements _$$_GroupListCopyWith<$Res> { __$$_GroupListCopyWithImpl( _$_GroupList _value, $Res Function(_$_GroupList) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? groupList = null, }) { return _then(_$_GroupList( groupList: null == groupList ? _value._groupList : groupList // ignore: cast_nullable_to_non_nullable as List<String>, )); } } /// @nodoc @JsonSerializable() class _$_GroupList implements _GroupList { const _$_GroupList( {@JsonKey(name: 'groupList', required: true, disallowNullValue: true) required final List<String> groupList}) : _groupList = groupList; factory _$_GroupList.fromJson(Map<String, dynamic> json) => _$$_GroupListFromJson(json); final List<String> _groupList; @override @JsonKey(name: 'groupList', required: true, disallowNullValue: true) List<String> get groupList { // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_groupList); } @override String toString() { return 'GroupList(groupList: $groupList)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_GroupList && const DeepCollectionEquality() .equals(other._groupList, _groupList)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_groupList)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_GroupListCopyWith<_$_GroupList> get copyWith => __$$_GroupListCopyWithImpl<_$_GroupList>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_GroupListToJson( this, ); } } abstract class _GroupList implements GroupList { const factory _GroupList( {@JsonKey(name: 'groupList', required: true, disallowNullValue: true) required final List<String> groupList}) = _$_GroupList; factory _GroupList.fromJson(Map<String, dynamic> json) = _$_GroupList.fromJson; @override @JsonKey(name: 'groupList', required: true, disallowNullValue: true) List<String> get groupList; @override @JsonKey(ignore: true) _$$_GroupListCopyWith<_$_GroupList> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/schedule_item.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'schedule_item.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$ScheduleItemModel { int get lessonNumber => throw _privateConstructorUsedError; String get lessonBeginning => throw _privateConstructorUsedError; String get lessonEnding => throw _privateConstructorUsedError; String get lessonName => throw _privateConstructorUsedError; String get pauseAfterLesson => throw _privateConstructorUsedError; String? get timer => throw _privateConstructorUsedError; Map<String, dynamic> get teachers => throw _privateConstructorUsedError; Map<String, dynamic> get lessonsShortNames => throw _privateConstructorUsedError; Map<String, dynamic> get lessonsFullNames => throw _privateConstructorUsedError; @JsonKey(ignore: true) $ScheduleItemModelCopyWith<ScheduleItemModel> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ScheduleItemModelCopyWith<$Res> { factory $ScheduleItemModelCopyWith( ScheduleItemModel value, $Res Function(ScheduleItemModel) then) = _$ScheduleItemModelCopyWithImpl<$Res, ScheduleItemModel>; @useResult $Res call( {int lessonNumber, String lessonBeginning, String lessonEnding, String lessonName, String pauseAfterLesson, String? timer, Map<String, dynamic> teachers, Map<String, dynamic> lessonsShortNames, Map<String, dynamic> lessonsFullNames}); } /// @nodoc class _$ScheduleItemModelCopyWithImpl<$Res, $Val extends ScheduleItemModel> implements $ScheduleItemModelCopyWith<$Res> { _$ScheduleItemModelCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? lessonNumber = null, Object? lessonBeginning = null, Object? lessonEnding = null, Object? lessonName = null, Object? pauseAfterLesson = null, Object? timer = freezed, Object? teachers = null, Object? lessonsShortNames = null, Object? lessonsFullNames = null, }) { return _then(_value.copyWith( lessonNumber: null == lessonNumber ? _value.lessonNumber : lessonNumber // ignore: cast_nullable_to_non_nullable as int, lessonBeginning: null == lessonBeginning ? _value.lessonBeginning : lessonBeginning // ignore: cast_nullable_to_non_nullable as String, lessonEnding: null == lessonEnding ? _value.lessonEnding : lessonEnding // ignore: cast_nullable_to_non_nullable as String, lessonName: null == lessonName ? _value.lessonName : lessonName // ignore: cast_nullable_to_non_nullable as String, pauseAfterLesson: null == pauseAfterLesson ? _value.pauseAfterLesson : pauseAfterLesson // ignore: cast_nullable_to_non_nullable as String, timer: freezed == timer ? _value.timer : timer // ignore: cast_nullable_to_non_nullable as String?, teachers: null == teachers ? _value.teachers : teachers // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, lessonsShortNames: null == lessonsShortNames ? _value.lessonsShortNames : lessonsShortNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, lessonsFullNames: null == lessonsFullNames ? _value.lessonsFullNames : lessonsFullNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, ) as $Val); } } /// @nodoc abstract class _$$_ScheduleItemModelCopyWith<$Res> implements $ScheduleItemModelCopyWith<$Res> { factory _$$_ScheduleItemModelCopyWith(_$_ScheduleItemModel value, $Res Function(_$_ScheduleItemModel) then) = __$$_ScheduleItemModelCopyWithImpl<$Res>; @override @useResult $Res call( {int lessonNumber, String lessonBeginning, String lessonEnding, String lessonName, String pauseAfterLesson, String? timer, Map<String, dynamic> teachers, Map<String, dynamic> lessonsShortNames, Map<String, dynamic> lessonsFullNames}); } /// @nodoc class __$$_ScheduleItemModelCopyWithImpl<$Res> extends _$ScheduleItemModelCopyWithImpl<$Res, _$_ScheduleItemModel> implements _$$_ScheduleItemModelCopyWith<$Res> { __$$_ScheduleItemModelCopyWithImpl( _$_ScheduleItemModel _value, $Res Function(_$_ScheduleItemModel) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? lessonNumber = null, Object? lessonBeginning = null, Object? lessonEnding = null, Object? lessonName = null, Object? pauseAfterLesson = null, Object? timer = freezed, Object? teachers = null, Object? lessonsShortNames = null, Object? lessonsFullNames = null, }) { return _then(_$_ScheduleItemModel( lessonNumber: null == lessonNumber ? _value.lessonNumber : lessonNumber // ignore: cast_nullable_to_non_nullable as int, lessonBeginning: null == lessonBeginning ? _value.lessonBeginning : lessonBeginning // ignore: cast_nullable_to_non_nullable as String, lessonEnding: null == lessonEnding ? _value.lessonEnding : lessonEnding // ignore: cast_nullable_to_non_nullable as String, lessonName: null == lessonName ? _value.lessonName : lessonName // ignore: cast_nullable_to_non_nullable as String, pauseAfterLesson: null == pauseAfterLesson ? _value.pauseAfterLesson : pauseAfterLesson // ignore: cast_nullable_to_non_nullable as String, timer: freezed == timer ? _value.timer : timer // ignore: cast_nullable_to_non_nullable as String?, teachers: null == teachers ? _value._teachers : teachers // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, lessonsShortNames: null == lessonsShortNames ? _value._lessonsShortNames : lessonsShortNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, lessonsFullNames: null == lessonsFullNames ? _value._lessonsFullNames : lessonsFullNames // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, )); } } /// @nodoc class _$_ScheduleItemModel implements _ScheduleItemModel { const _$_ScheduleItemModel( {required this.lessonNumber, required this.lessonBeginning, required this.lessonEnding, required this.lessonName, required this.pauseAfterLesson, this.timer, required final Map<String, dynamic> teachers, required final Map<String, dynamic> lessonsShortNames, required final Map<String, dynamic> lessonsFullNames}) : _teachers = teachers, _lessonsShortNames = lessonsShortNames, _lessonsFullNames = lessonsFullNames; @override final int lessonNumber; @override final String lessonBeginning; @override final String lessonEnding; @override final String lessonName; @override final String pauseAfterLesson; @override final String? timer; final Map<String, dynamic> _teachers; @override Map<String, dynamic> get teachers { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_teachers); } final Map<String, dynamic> _lessonsShortNames; @override Map<String, dynamic> get lessonsShortNames { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_lessonsShortNames); } final Map<String, dynamic> _lessonsFullNames; @override Map<String, dynamic> get lessonsFullNames { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_lessonsFullNames); } @override String toString() { return 'ScheduleItemModel(lessonNumber: $lessonNumber, lessonBeginning: $lessonBeginning, lessonEnding: $lessonEnding, lessonName: $lessonName, pauseAfterLesson: $pauseAfterLesson, timer: $timer, teachers: $teachers, lessonsShortNames: $lessonsShortNames, lessonsFullNames: $lessonsFullNames)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ScheduleItemModel && (identical(other.lessonNumber, lessonNumber) || other.lessonNumber == lessonNumber) && (identical(other.lessonBeginning, lessonBeginning) || other.lessonBeginning == lessonBeginning) && (identical(other.lessonEnding, lessonEnding) || other.lessonEnding == lessonEnding) && (identical(other.lessonName, lessonName) || other.lessonName == lessonName) && (identical(other.pauseAfterLesson, pauseAfterLesson) || other.pauseAfterLesson == pauseAfterLesson) && (identical(other.timer, timer) || other.timer == timer) && const DeepCollectionEquality().equals(other._teachers, _teachers) && const DeepCollectionEquality() .equals(other._lessonsShortNames, _lessonsShortNames) && const DeepCollectionEquality() .equals(other._lessonsFullNames, _lessonsFullNames)); } @override int get hashCode => Object.hash( runtimeType, lessonNumber, lessonBeginning, lessonEnding, lessonName, pauseAfterLesson, timer, const DeepCollectionEquality().hash(_teachers), const DeepCollectionEquality().hash(_lessonsShortNames), const DeepCollectionEquality().hash(_lessonsFullNames)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_ScheduleItemModelCopyWith<_$_ScheduleItemModel> get copyWith => __$$_ScheduleItemModelCopyWithImpl<_$_ScheduleItemModel>( this, _$identity); } abstract class _ScheduleItemModel implements ScheduleItemModel { const factory _ScheduleItemModel( {required final int lessonNumber, required final String lessonBeginning, required final String lessonEnding, required final String lessonName, required final String pauseAfterLesson, final String? timer, required final Map<String, dynamic> teachers, required final Map<String, dynamic> lessonsShortNames, required final Map<String, dynamic> lessonsFullNames}) = _$_ScheduleItemModel; @override int get lessonNumber; @override String get lessonBeginning; @override String get lessonEnding; @override String get lessonName; @override String get pauseAfterLesson; @override String? get timer; @override Map<String, dynamic> get teachers; @override Map<String, dynamic> get lessonsShortNames; @override Map<String, dynamic> get lessonsFullNames; @override @JsonKey(ignore: true) _$$_ScheduleItemModelCopyWith<_$_ScheduleItemModel> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/schedule.dart
// ignore_for_file: invalid_annotation_target import 'package:freezed_annotation/freezed_annotation.dart'; part 'schedule.freezed.dart'; part 'schedule.g.dart'; @freezed class Schedule with _$Schedule { const factory Schedule({ @JsonKey(name: 'schedule', required: true, disallowNullValue: true) required Map<String, dynamic> scheduleMap, }) = _Schedule; /// Generate Class from Map<String, dynamic> factory Schedule.fromJson(Map<String, dynamic> json) => _$ScheduleFromJson(json); }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/group_definition.dart
// ignore_for_file: invalid_annotation_target import 'package:freezed_annotation/freezed_annotation.dart'; part 'group_definition.freezed.dart'; part 'group_definition.g.dart'; @freezed class GroupDefinition with _$GroupDefinition { const factory GroupDefinition({ @JsonKey(name: 'definition', required: true, disallowNullValue: true) required Map<String, dynamic> groupDefinitionMap, }) = _GroupDefinition; /// Generate Class from Map<String, dynamic> factory GroupDefinition.fromJson(Map<String, dynamic> json) => _$GroupDefinitionFromJson(json); }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/schedule.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'schedule.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_Schedule _$$_ScheduleFromJson(Map<String, dynamic> json) { $checkKeys( json, requiredKeys: const ['schedule'], disallowNullValues: const ['schedule'], ); return _$_Schedule( scheduleMap: json['schedule'] as Map<String, dynamic>, ); } Map<String, dynamic> _$$_ScheduleToJson(_$_Schedule instance) => <String, dynamic>{ 'schedule': instance.scheduleMap, };
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/timetable.dart
// ignore_for_file: invalid_annotation_target import 'package:freezed_annotation/freezed_annotation.dart'; part 'timetable.freezed.dart'; part 'timetable.g.dart'; @freezed class Timetable with _$Timetable { const factory Timetable({ @JsonKey(name: 'timetable', required: true, disallowNullValue: true) required Map<String, dynamic> timetableMap, }) = _Timetable; /// Generate Class from Map<String, dynamic> factory Timetable.fromJson(Map<String, dynamic> json) => _$TimetableFromJson(json); }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/group_list.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'group_list.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_GroupList _$$_GroupListFromJson(Map<String, dynamic> json) { $checkKeys( json, requiredKeys: const ['groupList'], disallowNullValues: const ['groupList'], ); return _$_GroupList( groupList: (json['groupList'] as List<dynamic>).map((e) => e as String).toList(), ); } Map<String, dynamic> _$$_GroupListToJson(_$_GroupList instance) => <String, dynamic>{ 'groupList': instance.groupList, };
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/group_definition.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'group_definition.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); GroupDefinition _$GroupDefinitionFromJson(Map<String, dynamic> json) { return _GroupDefinition.fromJson(json); } /// @nodoc mixin _$GroupDefinition { @JsonKey(name: 'definition', required: true, disallowNullValue: true) Map<String, dynamic> get groupDefinitionMap => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $GroupDefinitionCopyWith<GroupDefinition> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $GroupDefinitionCopyWith<$Res> { factory $GroupDefinitionCopyWith( GroupDefinition value, $Res Function(GroupDefinition) then) = _$GroupDefinitionCopyWithImpl<$Res, GroupDefinition>; @useResult $Res call( {@JsonKey(name: 'definition', required: true, disallowNullValue: true) Map<String, dynamic> groupDefinitionMap}); } /// @nodoc class _$GroupDefinitionCopyWithImpl<$Res, $Val extends GroupDefinition> implements $GroupDefinitionCopyWith<$Res> { _$GroupDefinitionCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? groupDefinitionMap = null, }) { return _then(_value.copyWith( groupDefinitionMap: null == groupDefinitionMap ? _value.groupDefinitionMap : groupDefinitionMap // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, ) as $Val); } } /// @nodoc abstract class _$$_GroupDefinitionCopyWith<$Res> implements $GroupDefinitionCopyWith<$Res> { factory _$$_GroupDefinitionCopyWith( _$_GroupDefinition value, $Res Function(_$_GroupDefinition) then) = __$$_GroupDefinitionCopyWithImpl<$Res>; @override @useResult $Res call( {@JsonKey(name: 'definition', required: true, disallowNullValue: true) Map<String, dynamic> groupDefinitionMap}); } /// @nodoc class __$$_GroupDefinitionCopyWithImpl<$Res> extends _$GroupDefinitionCopyWithImpl<$Res, _$_GroupDefinition> implements _$$_GroupDefinitionCopyWith<$Res> { __$$_GroupDefinitionCopyWithImpl( _$_GroupDefinition _value, $Res Function(_$_GroupDefinition) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? groupDefinitionMap = null, }) { return _then(_$_GroupDefinition( groupDefinitionMap: null == groupDefinitionMap ? _value._groupDefinitionMap : groupDefinitionMap // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, )); } } /// @nodoc @JsonSerializable() class _$_GroupDefinition implements _GroupDefinition { const _$_GroupDefinition( {@JsonKey(name: 'definition', required: true, disallowNullValue: true) required final Map<String, dynamic> groupDefinitionMap}) : _groupDefinitionMap = groupDefinitionMap; factory _$_GroupDefinition.fromJson(Map<String, dynamic> json) => _$$_GroupDefinitionFromJson(json); final Map<String, dynamic> _groupDefinitionMap; @override @JsonKey(name: 'definition', required: true, disallowNullValue: true) Map<String, dynamic> get groupDefinitionMap { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_groupDefinitionMap); } @override String toString() { return 'GroupDefinition(groupDefinitionMap: $groupDefinitionMap)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_GroupDefinition && const DeepCollectionEquality() .equals(other._groupDefinitionMap, _groupDefinitionMap)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(_groupDefinitionMap)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_GroupDefinitionCopyWith<_$_GroupDefinition> get copyWith => __$$_GroupDefinitionCopyWithImpl<_$_GroupDefinition>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_GroupDefinitionToJson( this, ); } } abstract class _GroupDefinition implements GroupDefinition { const factory _GroupDefinition( {@JsonKey(name: 'definition', required: true, disallowNullValue: true) required final Map<String, dynamic> groupDefinitionMap}) = _$_GroupDefinition; factory _GroupDefinition.fromJson(Map<String, dynamic> json) = _$_GroupDefinition.fromJson; @override @JsonKey(name: 'definition', required: true, disallowNullValue: true) Map<String, dynamic> get groupDefinitionMap; @override @JsonKey(ignore: true) _$$_GroupDefinitionCopyWith<_$_GroupDefinition> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/schedule.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'schedule.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); Schedule _$ScheduleFromJson(Map<String, dynamic> json) { return _Schedule.fromJson(json); } /// @nodoc mixin _$Schedule { @JsonKey(name: 'schedule', required: true, disallowNullValue: true) Map<String, dynamic> get scheduleMap => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $ScheduleCopyWith<Schedule> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ScheduleCopyWith<$Res> { factory $ScheduleCopyWith(Schedule value, $Res Function(Schedule) then) = _$ScheduleCopyWithImpl<$Res, Schedule>; @useResult $Res call( {@JsonKey(name: 'schedule', required: true, disallowNullValue: true) Map<String, dynamic> scheduleMap}); } /// @nodoc class _$ScheduleCopyWithImpl<$Res, $Val extends Schedule> implements $ScheduleCopyWith<$Res> { _$ScheduleCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? scheduleMap = null, }) { return _then(_value.copyWith( scheduleMap: null == scheduleMap ? _value.scheduleMap : scheduleMap // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, ) as $Val); } } /// @nodoc abstract class _$$_ScheduleCopyWith<$Res> implements $ScheduleCopyWith<$Res> { factory _$$_ScheduleCopyWith( _$_Schedule value, $Res Function(_$_Schedule) then) = __$$_ScheduleCopyWithImpl<$Res>; @override @useResult $Res call( {@JsonKey(name: 'schedule', required: true, disallowNullValue: true) Map<String, dynamic> scheduleMap}); } /// @nodoc class __$$_ScheduleCopyWithImpl<$Res> extends _$ScheduleCopyWithImpl<$Res, _$_Schedule> implements _$$_ScheduleCopyWith<$Res> { __$$_ScheduleCopyWithImpl( _$_Schedule _value, $Res Function(_$_Schedule) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? scheduleMap = null, }) { return _then(_$_Schedule( scheduleMap: null == scheduleMap ? _value._scheduleMap : scheduleMap // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, )); } } /// @nodoc @JsonSerializable() class _$_Schedule implements _Schedule { const _$_Schedule( {@JsonKey(name: 'schedule', required: true, disallowNullValue: true) required final Map<String, dynamic> scheduleMap}) : _scheduleMap = scheduleMap; factory _$_Schedule.fromJson(Map<String, dynamic> json) => _$$_ScheduleFromJson(json); final Map<String, dynamic> _scheduleMap; @override @JsonKey(name: 'schedule', required: true, disallowNullValue: true) Map<String, dynamic> get scheduleMap { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_scheduleMap); } @override String toString() { return 'Schedule(scheduleMap: $scheduleMap)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_Schedule && const DeepCollectionEquality() .equals(other._scheduleMap, _scheduleMap)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(_scheduleMap)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_ScheduleCopyWith<_$_Schedule> get copyWith => __$$_ScheduleCopyWithImpl<_$_Schedule>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_ScheduleToJson( this, ); } } abstract class _Schedule implements Schedule { const factory _Schedule( {@JsonKey(name: 'schedule', required: true, disallowNullValue: true) required final Map<String, dynamic> scheduleMap}) = _$_Schedule; factory _Schedule.fromJson(Map<String, dynamic> json) = _$_Schedule.fromJson; @override @JsonKey(name: 'schedule', required: true, disallowNullValue: true) Map<String, dynamic> get scheduleMap; @override @JsonKey(ignore: true) _$$_ScheduleCopyWith<_$_Schedule> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/timetable.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'timetable.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_Timetable _$$_TimetableFromJson(Map<String, dynamic> json) { $checkKeys( json, requiredKeys: const ['timetable'], disallowNullValues: const ['timetable'], ); return _$_Timetable( timetableMap: json['timetable'] as Map<String, dynamic>, ); } Map<String, dynamic> _$$_TimetableToJson(_$_Timetable instance) => <String, dynamic>{ 'timetable': instance.timetableMap, };
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/timetable.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'timetable.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); Timetable _$TimetableFromJson(Map<String, dynamic> json) { return _Timetable.fromJson(json); } /// @nodoc mixin _$Timetable { @JsonKey(name: 'timetable', required: true, disallowNullValue: true) Map<String, dynamic> get timetableMap => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $TimetableCopyWith<Timetable> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $TimetableCopyWith<$Res> { factory $TimetableCopyWith(Timetable value, $Res Function(Timetable) then) = _$TimetableCopyWithImpl<$Res, Timetable>; @useResult $Res call( {@JsonKey(name: 'timetable', required: true, disallowNullValue: true) Map<String, dynamic> timetableMap}); } /// @nodoc class _$TimetableCopyWithImpl<$Res, $Val extends Timetable> implements $TimetableCopyWith<$Res> { _$TimetableCopyWithImpl(this._value, this._then); // ignore: unused_field final $Val _value; // ignore: unused_field final $Res Function($Val) _then; @pragma('vm:prefer-inline') @override $Res call({ Object? timetableMap = null, }) { return _then(_value.copyWith( timetableMap: null == timetableMap ? _value.timetableMap : timetableMap // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, ) as $Val); } } /// @nodoc abstract class _$$_TimetableCopyWith<$Res> implements $TimetableCopyWith<$Res> { factory _$$_TimetableCopyWith( _$_Timetable value, $Res Function(_$_Timetable) then) = __$$_TimetableCopyWithImpl<$Res>; @override @useResult $Res call( {@JsonKey(name: 'timetable', required: true, disallowNullValue: true) Map<String, dynamic> timetableMap}); } /// @nodoc class __$$_TimetableCopyWithImpl<$Res> extends _$TimetableCopyWithImpl<$Res, _$_Timetable> implements _$$_TimetableCopyWith<$Res> { __$$_TimetableCopyWithImpl( _$_Timetable _value, $Res Function(_$_Timetable) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? timetableMap = null, }) { return _then(_$_Timetable( timetableMap: null == timetableMap ? _value._timetableMap : timetableMap // ignore: cast_nullable_to_non_nullable as Map<String, dynamic>, )); } } /// @nodoc @JsonSerializable() class _$_Timetable implements _Timetable { const _$_Timetable( {@JsonKey(name: 'timetable', required: true, disallowNullValue: true) required final Map<String, dynamic> timetableMap}) : _timetableMap = timetableMap; factory _$_Timetable.fromJson(Map<String, dynamic> json) => _$$_TimetableFromJson(json); final Map<String, dynamic> _timetableMap; @override @JsonKey(name: 'timetable', required: true, disallowNullValue: true) Map<String, dynamic> get timetableMap { // ignore: implicit_dynamic_type return EqualUnmodifiableMapView(_timetableMap); } @override String toString() { return 'Timetable(timetableMap: $timetableMap)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_Timetable && const DeepCollectionEquality() .equals(other._timetableMap, _timetableMap)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(_timetableMap)); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') _$$_TimetableCopyWith<_$_Timetable> get copyWith => __$$_TimetableCopyWithImpl<_$_Timetable>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_TimetableToJson( this, ); } } abstract class _Timetable implements Timetable { const factory _Timetable( {@JsonKey(name: 'timetable', required: true, disallowNullValue: true) required final Map<String, dynamic> timetableMap}) = _$_Timetable; factory _Timetable.fromJson(Map<String, dynamic> json) = _$_Timetable.fromJson; @override @JsonKey(name: 'timetable', required: true, disallowNullValue: true) Map<String, dynamic> get timetableMap; @override @JsonKey(ignore: true) _$$_TimetableCopyWith<_$_Timetable> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/vpec/lib/models
mirrored_repositories/vpec/lib/models/schedule/group_list.dart
// ignore_for_file: invalid_annotation_target import 'package:freezed_annotation/freezed_annotation.dart'; part 'group_list.freezed.dart'; part 'group_list.g.dart'; @freezed class GroupList with _$GroupList { const factory GroupList({ @JsonKey( name: 'groupList', required: true, disallowNullValue: true, ) required List<String> groupList, }) = _GroupList; /// Generate Class from Map<String, dynamic> factory GroupList.fromJson(Map<String, dynamic> json) => _$GroupListFromJson(json); }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/utils/holiday_helper.dart
class HolidayHelper { static bool get isNewYear { var date = DateTime.now(); return date.month == 1 || date.month == 12; } // add more holidays if need... }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/utils/theme_helper.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:hive/hive.dart'; import 'utils.dart'; class ThemeHelper { /// return true, if system or user-chosen theme is dark static bool get isDarkMode { // get system theme var brightness = SchedulerBinding.instance.window.platformBrightness; bool isDarkMode = brightness == Brightness.dark; // get user-chosen theme Box settings = Hive.box('settings'); if (settings.get('theme') != null) { settings.get('theme') == 'Тёмная тема' ? isDarkMode = true : isDarkMode = false; } return isDarkMode; } static void doInitialChrome() { SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( systemNavigationBarContrastEnforced: false, systemStatusBarContrastEnforced: false, statusBarColor: Colors.transparent, systemNavigationBarColor: Colors.transparent, )); } static SystemUiOverlayStyle overlayStyleHelper(Color legacyColor) { if (AndroidSdkVersion.version < 29) { // less than Android 10 return SystemUiOverlayStyle(systemNavigationBarColor: legacyColor); } return const SystemUiOverlayStyle(); } /// Color StatusBar and SystemNavigationBar icons to current theme brightness static void colorSystemChrome({ ColoringMode mode = ColoringMode.byCurrentTheme, }) { Brightness brightness; switch (mode) { case ColoringMode.byCurrentTheme: brightness = isDarkMode ? Brightness.light : Brightness.dark; break; case ColoringMode.lightIcons: brightness = Brightness.light; break; case ColoringMode.darkIcons: brightness = Brightness.dark; break; } SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarIconBrightness: brightness, systemNavigationBarIconBrightness: brightness, ), ); } } /// This class store current [ThemeMode] class ThemeNotifier with ChangeNotifier { ThemeMode themeMode; ThemeNotifier(this.themeMode); void changeTheme(ThemeMode mode) { FirebaseAnalytics.instance.logEvent(name: 'theme_changed', parameters: { 'theme_mode_used': mode, }); themeMode = mode; notifyListeners(); } } /// Coloring mode for status bar and system navigation icons enum ColoringMode { /// Color system chrome based on current app theme byCurrentTheme, /// Color system chrome with light icons lightIcons, /// Color system chrome with dark icons darkIcons }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/utils/hive_helper.dart
import 'package:hive_flutter/hive_flutter.dart'; class HiveHelper { static dynamic getValue(String key) { Box settings = Hive.box('settings'); return settings.get(key); } static void saveValue({required String key, required dynamic value}) { Box settings = Hive.box('settings'); settings.put(key, value); } static void removeValue(String key) { Box settings = Hive.box('settings'); settings.delete(key); } static Future<void> initHive() async { await Hive.initFlutter(); await Hive.openBox('settings'); } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/utils/icons.dart
/// Flutter icons VpecIconPack /// Copyright (C) 2021 by original authors @ fluttericon.com, fontello.com /// This font was generated by FlutterIcon.com, which is derived from Fontello. /// /// To use this font, place it in your fonts/ directory and include the /// following in your pubspec.yaml /// /// flutter: /// fonts: /// - family: VpecIconPack /// fonts: /// - asset: fonts/VpecIconPack.ttf /// /// /// // ignore_for_file: constant_identifier_names import 'package:flutter/widgets.dart'; class VpecIconPack { VpecIconPack._(); static const _kFontFam = 'VpecIconPack'; static const String? _kFontPkg = null; static const IconData parents = IconData(0xe800, fontFamily: _kFontFam, fontPackage: _kFontPkg); static const IconData account_cog_outline = IconData(0xe801, fontFamily: _kFontFam, fontPackage: _kFontPkg); static const IconData battery_saver_line = IconData(0xe802, fontFamily: _kFontFam, fontPackage: _kFontPkg); static const IconData telegram = IconData(0xe803, fontFamily: _kFontFam, fontPackage: _kFontPkg); static const IconData vk = IconData(0xe804, fontFamily: _kFontFam, fontPackage: _kFontPkg); static const IconData news_outline = IconData(0xe805, fontFamily: _kFontFam, fontPackage: _kFontPkg); static const IconData news = IconData(0xe806, fontFamily: _kFontFam, fontPackage: _kFontPkg); }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/utils/utils.dart
import 'dart:async'; import 'dart:io'; import 'dart:math'; import 'package:device_info/device_info.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; import 'package:url_launcher/url_launcher.dart'; import 'theme/theme.dart'; import 'theme_helper.dart'; /// Open in browser given [url] Future<void> openUrl(String url) async { Uri uri = Uri.parse(url); if (await canLaunchUrl(uri)) { await launchUrl( uri, mode: LaunchMode.externalApplication, ); } else { throw "Can't launch url: $url"; } } /// Share any file from given [url]. /// /// If [url] is null, then nothing will do Future<void> shareFile(String? url) async { if (url != null) { FirebaseAnalytics.instance.logShare(contentType: 'schedule', itemId: url, method: 'system_dialog'); // download file from given url HttpClientRequest request = await HttpClient().getUrl(Uri.parse(url)); HttpClientResponse response = await request.close(); Uint8List bytes = await consolidateHttpClientResponseBytes(response); // get temp directory, write and share file final Directory tempDir = await getTemporaryDirectory(); final File file = await File('${tempDir.path}/${url.split('/').last}').create(); await file.writeAsBytes(bytes); if (response.statusCode == 200) { await Share.shareXFiles([XFile(file.path)]); await file.delete(); } else { await file.delete(); } } } /// Show modal sheet with rounded corners. /// /// Use [child] with [title] if you want use styled layout. /// /// Or use [customLayout] if you need something other. //ignore: long-parameter-list Future<T?> showRoundedModalSheet<T>({ required BuildContext context, String? title, bool isDismissible = true, bool enableDrag = true, Widget? child, Widget? customLayout, }) async { ThemeHelper.colorSystemChrome(mode: ColoringMode.lightIcons); T? toReturn = await showModalBottomSheet<T>( context: context, isDismissible: isDismissible, isScrollControlled: true, enableDrag: enableDrag, backgroundColor: Colors.transparent, builder: (context) => AnnotatedRegion<SystemUiOverlayStyle>( value: ThemeHelper.overlayStyleHelper( Color.alphaBlend(Colors.black54, context.palette.backgroundSurface), ), child: customLayout ?? Container( padding: const EdgeInsets.only( top: 10, bottom: 15, left: 15, right: 15, ), decoration: BoxDecoration( color: context.palette.levelTwoSurface, borderRadius: BorderRadius.circular(20), border: Border.all( color: context.palette.outsideBorderColor, ), ), margin: EdgeInsets.only( top: 10, left: 10, right: 10, bottom: [ MediaQuery.of(context).viewInsets.bottom, MediaQuery.of(context).viewPadding.bottom, ].reduce(max) + 10, ), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ isDismissible ? Column( children: [ SizedBox( width: 70, height: 5, child: DecoratedBox( decoration: ShapeDecoration( shape: const StadiumBorder(), color: context.palette.lowEmphasis, ), ), ), const SizedBox(height: 10), ], ) : const SizedBox(height: 5), Center( child: title != null ? Text( title, style: Theme.of(context).textTheme.headline4, textAlign: TextAlign.center, ) : ErrorWidget('You need implement [title] if you want ' 'use styled layout, or [customLayout] if you need' ' your own layout'), ), const SizedBox(height: 15), child ?? ErrorWidget('You need implement [child] if you want ' 'use styled layout, or [customLayout] if you need your ' 'own layout'), ], ), ), ), ); ThemeHelper.colorSystemChrome(); return toReturn; } class LowAndroidHttpOverrides extends HttpOverrides { @override HttpClient createHttpClient(SecurityContext? context) { return super.createHttpClient(context) ..badCertificateCallback = (X509Certificate cert, String host, int port) => true; } } /// Method that fixes /// "`CERTIFICATE_VERIFY_FAILED: certificate has expired`" bug, /// which appears on Android 7.0 and lower void useHttpOverrides() { if (AndroidSdkVersion.version <= 24) { HttpOverrides.global = LowAndroidHttpOverrides(); } } class AndroidSdkVersion { static int version = 0; static Future<void> getAndSave() async { if (Platform.isAndroid) { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; version = androidInfo.version.sdkInt; } } }
0
mirrored_repositories/vpec/lib
mirrored_repositories/vpec/lib/utils/firebase_auth.dart
import 'dart:async'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import '../models/account_info.dart'; import 'hive_helper.dart'; /// Types of access level. enum AccountType { /// Have access to view all announcements and edit mode. admin, /// can see announcements for students student, /// can see announcements for parents parent, /// can see announcements for teachers teacher, /// can't see anything except info about college entrant, } /// This class contains all information about account in [accountInfo]. /// [accountInfo] will be updated only after [startListening] function /// was called. If listening no more needed, call [cancelListener]. /// /// Should be used with ChangeNotifierProvider. class FirebaseAppAuth extends ChangeNotifier { AccountInfo accountInfo = AccountInfo( isLoggedIn: HiveHelper.getValue('isLoggedIn') ?? false, level: AccountType.entrant, ); late StreamSubscription<User?> authListener; /// Start listening for user auth state changes. /// Call [cancelListener] to stop it. void startListening() { authListener = FirebaseAuth.instance.authStateChanges().listen((User? user) { if (user?.email == null) { // user sign-out accountInfo = accountInfo.copyWith( isLoggedIn: false, level: AccountType.entrant, ); HiveHelper.removeValue('isLoggedIn'); notifyListeners(); } else { // user sign-in accountInfo = accountInfo.copyWith( isLoggedIn: true, email: user!.email, uid: user.uid, name: HiveHelper.getValue('username'), level: AccountDetails.getAccountLevel, ); HiveHelper.saveValue(key: 'isLoggedIn', value: true); notifyListeners(); } }); } /// Cancel listening for user auth state changes. Future<void> cancelListener() async { await authListener.cancel(); } } /// This class used for storing and changing admin editor mode in-app. /// Use [isInEditorMode] to get current status of editor mode. /// /// Should be used with ChangeNotifierProvider. class AccountEditorMode extends ChangeNotifier { bool isEditorModeActive = HiveHelper.getValue('isEditMode') ?? false; bool get isInEditorMode => AccountDetails.isAdmin && isEditorModeActive; /// Call this to on or off admin editor mode void toggleEditorMode() { isEditorModeActive = !isEditorModeActive; HiveHelper.saveValue(key: 'isEditMode', value: isEditorModeActive); notifyListeners(); } } /// This class contains a functions for getting user's app-specific data class AccountDetails { static bool get isAdmin => getAccountLevel == AccountType.admin; /// Call to get [AccountType] of current user. /// If user didn't sign-in, returns [AccountType.entrant] static AccountType get getAccountLevel { FirebaseAuth auth = FirebaseAuth.instance; if (auth.currentUser != null) { switch (auth.currentUser!.email) { case '[email protected]': return AccountType.admin; case '[email protected]': return AccountType.parent; case '[email protected]': return AccountType.teacher; case '[email protected]': return AccountType.student; default: throw 'Email of this account is not supported:\n${auth.currentUser!.email}'; } } else { return AccountType.entrant; } } /// Call this function to find out /// if the user has access to the required [AccountType]. static bool hasAccessToLevel(AccountType requestedType) { // get user account type and compare with requested type // admins always has access to something, // students, teachers and parents has access only for their account type. switch (getAccountLevel) { case AccountType.admin: return true; case AccountType.student: return requestedType == AccountType.student; case AccountType.teacher: return requestedType == AccountType.teacher; case AccountType.entrant: return requestedType == AccountType.entrant; case AccountType.parent: return requestedType == AccountType.parent; default: return false; } } /// Low level access account is account for students or entrant @Deprecated('Accounts no more uses different type of access levels') static bool get isAccountLowLevelAccess => getAccountLevel == AccountType.student || getAccountLevel == AccountType.entrant ? true : false; }
0
mirrored_repositories/vpec/lib/utils
mirrored_repositories/vpec/lib/utils/routes/routes.dart
import 'package:fluro/fluro.dart'; import 'routes_handlers.dart'; class Routes { static late FluroRouter router; static String homeScreen = '/'; static String settingsScreen = '/settings'; static String viewDocumentScreen = '/view_document'; static String cabinetsScreen = '/cabinets'; static String administrationScreen = '/administration'; static String teachersScreen = '/teacher'; static String aboutAppScreen = '/about'; static String jobQuizScreen = '/job_quiz'; static String documentsScreen = '/documents'; static String loginByURLScreen = '/loginByURL/:login/:password'; static String fullScheduleScreen = '/full_schedule'; static String scannerScreen = '/loginByScan'; static void defineRoutes(FluroRouter router) { // router.notFoundHandler use for 404 page router.notFoundHandler = homeScreenHandler; router.define( homeScreen, handler: homeScreenHandler, transitionType: TransitionType.cupertino, ); router.define( settingsScreen, handler: settingsScreenHandler, transitionType: TransitionType.cupertino, ); router.define( viewDocumentScreen, handler: viewDocumentScreenHandler, transitionType: TransitionType.cupertino, ); router.define( cabinetsScreen, handler: cabinetsScreenHandler, transitionType: TransitionType.cupertino, ); router.define( administrationScreen, handler: administrationScreenHandler, transitionType: TransitionType.cupertino, ); router.define( teachersScreen, handler: teachersScreenHandler, transitionType: TransitionType.cupertino, ); router.define( aboutAppScreen, handler: aboutAppScreenHandler, transitionType: TransitionType.cupertino, ); router.define( jobQuizScreen, handler: jobQuizScreenHandler, transitionType: TransitionType.cupertino, ); router.define( documentsScreen, handler: documentsScreenHandler, transitionType: TransitionType.cupertino, ); router.define( loginByURLScreen, handler: loginByURLHandler, transitionType: TransitionType.cupertino, ); router.define( fullScheduleScreen, handler: fullScheduleScreenHandler, transitionType: TransitionType.cupertino, ); router.define( scannerScreen, handler: scannerScreenHandler, transitionType: TransitionType.cupertino, ); } }
0
mirrored_repositories/vpec/lib/utils
mirrored_repositories/vpec/lib/utils/routes/routes_handlers.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:fluro/fluro.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/screens/scanner/scanner_screen.dart'; import '/screens/about_app/about_app_screen.dart'; import '/screens/bottom_bar/bottom_bar_logic.dart'; import '/screens/bottom_bar/bottom_bar_screen.dart'; import '/screens/cabinets_map/cabinets_map_screen.dart'; import '/screens/documents/documents_screen.dart'; import '/screens/job_quiz/job_quiz_screen.dart'; import '/screens/settings/settings_screen.dart'; import '/screens/teachers/teachers_logic.dart'; import '/screens/teachers/teachers_screen.dart'; import '/screens/view_document/view_document_screen.dart'; import '/splash.dart'; import '/screens/admins/admins_screen.dart'; import '/screens/lessons_schedule/lessons_schedule_screen.dart'; import 'routes.dart'; Handler homeScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> params) { return ChangeNotifierProvider( create: (_) => BottomBarLogic(), child: const SplashScreen(child: BottomBarScreen()), ); }, ); Handler settingsScreenHandler = Handler(handlerFunc: (context, Map<String, List<String>> params) { return const SettingsScreen(); }); Handler viewDocumentScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return const DocumentViewScreen(); }, ); Handler cabinetsScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return const CabinetsMapScreen(); }, ); Handler administrationScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return AdminScreen(); }, ); Handler teachersScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return ChangeNotifierProvider( create: (_) => TeachersLogic(), child: const TeacherScreen(), ); }, ); Handler aboutAppScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return const AboutAppScreen(); }, ); Handler jobQuizScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return const JobQuizScreen(); }, ); Handler documentsScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> parameters) { return const DocumentsScreen(); }, ); Handler loginByURLHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> params) { String? email = params['login']!.first; String? password = params['password']!.first; makeLogin(email, password).then((_) { Navigator.pushNamedAndRemoveUntil( context!, Routes.homeScreen, (route) => false, ); }); return null; }, ); Future<void> makeLogin(String? email, String? password) async { if (email != null && password != null) { await FirebaseAuth.instance.signOut(); await FirebaseAuth.instance .signInWithEmailAndPassword(email: email, password: password); } } Handler fullScheduleScreenHandler = Handler( handlerFunc: (BuildContext? context, Map<String, List<String>> params) => const FullLessonsScheduleScreen(), ); Handler scannerScreenHandler = Handler(handlerFunc: (context, Map<String, List<String>> params) { return const ScannerScreen(); });
0
mirrored_repositories/vpec/lib/utils
mirrored_repositories/vpec/lib/utils/notifications/firebase_messaging.dart
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'local_notifications.dart'; class AppFirebaseMessaging { static FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance; static void startListening() { getToken(); FirebaseMessaging.onMessage.listen((message) { sendNotification(message); }); } static void sendNotification(RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; // local notification to show to users using the created channel. if (notification != null && android != null) { LocalNotifications.flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( LocalNotifications.serverChannel.id, LocalNotifications.serverChannel.name, channelDescription: LocalNotifications.serverChannel.description, icon: '@drawable/ic_notification', shortcutId: 'action_schedule', ), ), ); } } static Future<String> getToken() async { return await firebaseMessaging.getToken() ?? 'N/A'; } }
0
mirrored_repositories/vpec/lib/utils
mirrored_repositories/vpec/lib/utils/notifications/local_notifications.dart
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; class LocalNotifications { static const AndroidNotificationChannel serverChannel = AndroidNotificationChannel( 'firebase_server_channel', // id 'Уведомления с сервера', // title importance: Importance.max, ); static final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); static Future<void> initializeNotifications() async { await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(serverChannel); } }
0
mirrored_repositories/vpec/lib/utils
mirrored_repositories/vpec/lib/utils/theme/color_palette.dart
part of 'theme.dart'; @immutable class ColorPalette extends ThemeExtension<ColorPalette> { const ColorPalette({ required this.accentColor, required this.highEmphasis, required this.mediumEmphasis, required this.lowEmphasis, required this.outsideBorderColor, required this.backgroundSurface, required this.levelOneSurface, required this.levelTwoSurface, required this.levelThreeSurface, }); final Color accentColor; final Color highEmphasis; final Color mediumEmphasis; final Color lowEmphasis; final Color outsideBorderColor; final Color backgroundSurface; final Color levelOneSurface; final Color levelTwoSurface; final Color levelThreeSurface; @override ThemeExtension<ColorPalette> copyWith({ Color? accentColor, Color? highEmphasis, Color? mediumEmphasis, Color? lowEmphasis, Color? outsideBorderColor, Color? backgroundSurface, Color? levelOneSurface, Color? levelTwoSurface, Color? levelThreeSurface, }) { return ColorPalette( accentColor: accentColor ?? this.accentColor, highEmphasis: highEmphasis ?? this.highEmphasis, mediumEmphasis: mediumEmphasis ?? this.mediumEmphasis, lowEmphasis: lowEmphasis ?? this.lowEmphasis, outsideBorderColor: outsideBorderColor ?? this.outsideBorderColor, backgroundSurface: backgroundSurface ?? this.backgroundSurface, levelOneSurface: levelOneSurface ?? this.levelOneSurface, levelTwoSurface: levelTwoSurface ?? this.levelTwoSurface, levelThreeSurface: levelThreeSurface ?? this.levelThreeSurface, ); } @override ThemeExtension<ColorPalette> lerp( ThemeExtension<ColorPalette>? other, double t, ) { if (other is! ColorPalette) return this; return ColorPalette( accentColor: Color.lerp(accentColor, other.accentColor, t)!, highEmphasis: Color.lerp(highEmphasis, other.highEmphasis, t)!, mediumEmphasis: Color.lerp(mediumEmphasis, other.mediumEmphasis, t)!, lowEmphasis: Color.lerp(lowEmphasis, other.lowEmphasis, t)!, outsideBorderColor: Color.lerp(outsideBorderColor, other.outsideBorderColor, t)!, backgroundSurface: Color.lerp(backgroundSurface, other.backgroundSurface, t)!, levelOneSurface: Color.lerp(levelOneSurface, other.levelOneSurface, t)!, levelTwoSurface: Color.lerp(levelTwoSurface, other.levelTwoSurface, t)!, levelThreeSurface: Color.lerp(levelThreeSurface, other.levelThreeSurface, t)!, ); } } extension ColorPaletteOnBuildContextExt on BuildContext { /// Get [ColorPalette] of [context] ColorPalette get palette => Theme.of(this).extension<ColorPalette>()!; }
0
mirrored_repositories/vpec/lib/utils
mirrored_repositories/vpec/lib/utils/theme/theme.dart
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../widgets/md2_tab_indicator.dart'; part 'color_palette.dart'; const FontWeight thin = FontWeight.w100; const FontWeight extraLight = FontWeight.w200; const FontWeight light = FontWeight.w300; const FontWeight regular = FontWeight.w400; const FontWeight medium = FontWeight.w500; const FontWeight semiBold = FontWeight.w600; const FontWeight bold = FontWeight.w700; const FontWeight extraBold = FontWeight.w800; const FontWeight black = FontWeight.w900; ThemeData themeData() { //light theme const accentColor = Color(0xFF133676); const highEmphasis = Color.fromRGBO(0, 0, 0, 0.87); const mediumEmphasis = Color.fromRGBO(0, 0, 0, 0.60); const lowEmphasis = Color.fromRGBO(0, 0, 0, 0.38); const outsideBorderColor = Color.fromRGBO(0, 0, 0, 0.12); const surfaceIncrement = Color.fromRGBO(255, 255, 255, 0.40); const backgroundSurface = Color(0xFFE8E8E8); final levelOneSurface = Color.alphaBlend(surfaceIncrement, backgroundSurface); final levelTwoSurface = Color.alphaBlend(surfaceIncrement, levelOneSurface); final levelThreeSurface = Color.alphaBlend(surfaceIncrement, levelTwoSurface); return ThemeData( extensions: [ ColorPalette( accentColor: accentColor, highEmphasis: highEmphasis, mediumEmphasis: mediumEmphasis, lowEmphasis: lowEmphasis, outsideBorderColor: outsideBorderColor, backgroundSurface: backgroundSurface, levelOneSurface: levelOneSurface, levelTwoSurface: levelTwoSurface, levelThreeSurface: levelThreeSurface, ), ], navigationBarTheme: NavigationBarThemeData( backgroundColor: Colors.transparent, height: 65, indicatorColor: accentColor, labelTextStyle: MaterialStateProperty.all(const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 12, color: accentColor, overflow: TextOverflow.ellipsis, )), iconTheme: MaterialStateProperty.resolveWith((states) => IconThemeData( color: states.contains(MaterialState.selected) ? levelTwoSurface : highEmphasis, )), labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected, ), tabBarTheme: const TabBarTheme( labelColor: accentColor, unselectedLabelColor: mediumEmphasis, indicator: MD2TabIndicator(accentColor), indicatorSize: TabBarIndicatorSize.label, ), appBarTheme: AppBarTheme( elevation: 0, shape: const Border( bottom: BorderSide( color: outsideBorderColor, width: 1.0, strokeAlign: StrokeAlign.inside, ), ), backgroundColor: levelTwoSurface, foregroundColor: highEmphasis, systemOverlayStyle: const SystemUiOverlayStyle(), ), cardTheme: CardTheme( elevation: 0, margin: EdgeInsets.zero, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), side: const BorderSide( color: outsideBorderColor, width: 1.0, strokeAlign: StrokeAlign.inside, ), ), ), pageTransitionsTheme: const PageTransitionsTheme(builders: { TargetPlatform.android: CupertinoPageTransitionsBuilder(), TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), }), brightness: Brightness.light, textSelectionTheme: TextSelectionThemeData( selectionColor: accentColor.withOpacity(0.5), selectionHandleColor: accentColor, ), primaryColor: levelTwoSurface, cardColor: levelOneSurface, splashColor: accentColor.withOpacity(0.2), highlightColor: accentColor.withOpacity(0.15), focusColor: accentColor.withOpacity(0.2), splashFactory: InkRipple.splashFactory, colorScheme: ColorScheme( primary: accentColor, secondary: accentColor, surface: levelTwoSurface, background: accentColor, error: Colors.red, onPrimary: backgroundSurface, onSecondary: backgroundSurface, onSurface: highEmphasis, onBackground: highEmphasis, onError: backgroundSurface, brightness: Brightness.light, ), dialogBackgroundColor: levelOneSurface, textTheme: const TextTheme( subtitle1: TextStyle(fontSize: 15, color: mediumEmphasis, fontWeight: medium), bodyText1: TextStyle(color: highEmphasis, fontSize: 16, fontWeight: regular), headline3: TextStyle( //News Card Title color: highEmphasis, fontSize: 16, fontFamily: 'Montserrat', fontWeight: medium, ), headline4: TextStyle( //Alert Card Title color: highEmphasis, fontSize: 17, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline5: TextStyle( //used in time schedule for any time color: highEmphasis, fontSize: 36, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline6: TextStyle( //used in time schedule for any other color: highEmphasis, fontSize: 18, fontFamily: 'Montserrat', fontWeight: semiBold, ), ), iconTheme: const IconThemeData( size: 24.0, ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), textStyle: const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 15, ), shape: const StadiumBorder(), foregroundColor: accentColor, ), ), outlinedButtonTheme: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20), textStyle: const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 15, ), shape: const StadiumBorder(), side: const BorderSide( width: 1.5, color: accentColor, ), ), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20), textStyle: const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 15, ), shape: const StadiumBorder(), backgroundColor: accentColor, foregroundColor: backgroundSurface, ), ), inputDecorationTheme: const InputDecorationTheme( alignLabelWithHint: true, errorStyle: TextStyle( color: Colors.red, fontFamily: 'Montserrat', fontWeight: semiBold, ), helperStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), labelStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), hintStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20)), ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), ), scaffoldBackgroundColor: backgroundSurface, floatingActionButtonTheme: FloatingActionButtonThemeData( elevation: 0, backgroundColor: levelThreeSurface, foregroundColor: accentColor, shape: const CircleBorder(side: BorderSide(color: outsideBorderColor)), ), bottomNavigationBarTheme: BottomNavigationBarThemeData( selectedItemColor: accentColor, unselectedItemColor: mediumEmphasis, backgroundColor: levelTwoSurface, ), bottomSheetTheme: BottomSheetThemeData(backgroundColor: levelOneSurface), ); } ThemeData darkThemeData() { //dark theme const accentColor = Color(0xFF7B9DDB); const highEmphasis = Color.fromRGBO(255, 255, 255, 0.87); const mediumEmphasis = Color.fromRGBO(255, 255, 255, 0.60); const lowEmphasis = Color.fromRGBO(255, 255, 255, 0.38); const outsideBorderColor = Color.fromRGBO(255, 255, 255, 0.05); const surfaceIncrement = Color.fromRGBO(255, 255, 255, 0.04); const backgroundSurface = Color(0xFF121212); final levelOneSurface = Color.alphaBlend(surfaceIncrement, backgroundSurface); final levelTwoSurface = Color.alphaBlend(surfaceIncrement, levelOneSurface); final levelThreeSurface = Color.alphaBlend(surfaceIncrement, levelTwoSurface); return ThemeData.dark().copyWith( extensions: [ ColorPalette( accentColor: accentColor, highEmphasis: highEmphasis, mediumEmphasis: mediumEmphasis, lowEmphasis: lowEmphasis, outsideBorderColor: outsideBorderColor, backgroundSurface: backgroundSurface, levelOneSurface: levelOneSurface, levelTwoSurface: levelTwoSurface, levelThreeSurface: levelThreeSurface, ), ], navigationBarTheme: NavigationBarThemeData( backgroundColor: Colors.transparent, height: 65, indicatorColor: accentColor, labelTextStyle: MaterialStateProperty.all(const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 12, color: accentColor, overflow: TextOverflow.ellipsis, )), iconTheme: MaterialStateProperty.resolveWith((states) => IconThemeData( color: states.contains(MaterialState.selected) ? levelTwoSurface : highEmphasis, )), labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected, ), tabBarTheme: const TabBarTheme( labelColor: accentColor, unselectedLabelColor: mediumEmphasis, indicator: MD2TabIndicator(accentColor), indicatorSize: TabBarIndicatorSize.label, ), appBarTheme: AppBarTheme( elevation: 0, shape: const Border( bottom: BorderSide( color: outsideBorderColor, width: 1.0, strokeAlign: StrokeAlign.inside, ), ), backgroundColor: levelTwoSurface, foregroundColor: highEmphasis, systemOverlayStyle: const SystemUiOverlayStyle(), ), cardTheme: CardTheme( elevation: 0, margin: EdgeInsets.zero, clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), side: const BorderSide( color: outsideBorderColor, width: 1.0, strokeAlign: StrokeAlign.inside, ), ), ), pageTransitionsTheme: const PageTransitionsTheme(builders: { TargetPlatform.android: CupertinoPageTransitionsBuilder(), TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), }), brightness: Brightness.dark, textSelectionTheme: TextSelectionThemeData( selectionColor: accentColor.withOpacity(0.5), selectionHandleColor: accentColor, ), primaryColor: levelTwoSurface, cardColor: levelOneSurface, splashColor: accentColor.withOpacity(0.2), highlightColor: accentColor.withOpacity(0.15), focusColor: accentColor.withOpacity(0.2), splashFactory: InkRipple.splashFactory, colorScheme: ColorScheme( primary: accentColor, secondary: accentColor, surface: levelTwoSurface, background: backgroundSurface, error: Colors.redAccent, onPrimary: backgroundSurface, onSecondary: backgroundSurface, onSurface: highEmphasis, onBackground: highEmphasis, onError: backgroundSurface, brightness: Brightness.dark, ), dialogBackgroundColor: levelOneSurface, textTheme: const TextTheme( subtitle1: TextStyle(fontSize: 15, color: mediumEmphasis, fontWeight: medium), bodyText1: TextStyle(color: highEmphasis, fontSize: 16, fontWeight: regular), headline3: TextStyle( //News Card Title color: highEmphasis, fontSize: 16, fontFamily: 'Montserrat', fontWeight: medium, ), headline4: TextStyle( //Alert Card Title color: highEmphasis, fontSize: 17, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline5: TextStyle( //used in time schedule for any time color: highEmphasis, fontSize: 36, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline6: TextStyle( //used in time schedule for any other color: highEmphasis, fontSize: 18, fontFamily: 'Montserrat', fontWeight: semiBold, ), ), iconTheme: const IconThemeData( size: 24.0, ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 12), textStyle: const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 15, ), shape: const StadiumBorder(), foregroundColor: accentColor, ), ), outlinedButtonTheme: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20), textStyle: const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 15, ), shape: const StadiumBorder(), side: const BorderSide( width: 1.5, color: accentColor, ), ), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20), textStyle: const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 15, ), shape: const StadiumBorder(), backgroundColor: accentColor, foregroundColor: backgroundSurface, ), ), inputDecorationTheme: const InputDecorationTheme( alignLabelWithHint: true, errorStyle: TextStyle( color: Colors.redAccent, fontFamily: 'Montserrat', fontWeight: semiBold, ), helperStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), labelStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), hintStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20)), ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.redAccent, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.redAccent, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), ), scaffoldBackgroundColor: backgroundSurface, floatingActionButtonTheme: FloatingActionButtonThemeData( elevation: 0, backgroundColor: levelThreeSurface, foregroundColor: accentColor, shape: const CircleBorder(side: BorderSide(color: outsideBorderColor)), ), bottomNavigationBarTheme: BottomNavigationBarThemeData( selectedItemColor: accentColor, unselectedItemColor: mediumEmphasis, backgroundColor: levelTwoSurface, ), bottomSheetTheme: BottomSheetThemeData(backgroundColor: levelOneSurface), ); }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/announcements/announcement_card.dart
import 'dart:math'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:flutter_linkify/flutter_linkify.dart'; import 'package:provider/provider.dart'; import 'package:zoom_pinch_overlay/zoom_pinch_overlay.dart'; import '/models/announcement_model.dart'; import '/models/document_model.dart'; import '/screens/view_document/view_document_logic.dart'; import '/utils/utils.dart'; import '../../utils/firebase_auth.dart'; class AnnouncementImage extends StatelessWidget { const AnnouncementImage({ Key? key, required this.imageUrl, }) : super(key: key); final String imageUrl; @override Widget build(BuildContext context) { return ZoomOverlay( twoTouchOnly: true, child: CachedNetworkImage(imageUrl: imageUrl), ); } } class AnnouncementCard extends StatelessWidget { final AnnouncementModel announcement; const AnnouncementCard({Key? key, required this.announcement}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Card( child: GestureDetector( onDoubleTap: () => editAnnouncement(context), child: Column( children: [ if (announcement.photoUrl != null) Container( margin: const EdgeInsets.all(1.0), clipBehavior: Clip.antiAlias, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), ), child: AnnouncementImage(imageUrl: announcement.photoUrl!), ), Padding( padding: const EdgeInsets.symmetric(vertical: 10.0), child: ListTile( title: Text( announcement.title, style: Theme.of(context).textTheme.headline4, ), subtitle: Padding( padding: const EdgeInsets.only(top: 6), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SelectableLinkify( text: announcement.content, style: Theme.of(context).textTheme.bodyText1, options: const LinkifyOptions(humanize: true), onOpen: (link) { FirebaseAnalytics.instance.logEvent(name: 'announcements_link_opened', parameters: { 'url': link.url, 'url_text' : link.text, }); if (ViewDocumentLogic.isThisURLSupported( link.url, )) { Navigator.pushNamed( context, '/view_document', arguments: DocumentModel( title: link.text, subtitle: '', url: link.url, ), ); } else { openUrl(link.url); } }, ), Padding( padding: const EdgeInsets.only(top: 6), child: Text( '${announcement.author} • ${announcement.pubDate}', style: Theme.of(context).textTheme.subtitle1, ), ), ], ), ), ), ), ], ), ), ), ); } void editAnnouncement(BuildContext context) { TextEditingController titleController = TextEditingController(); TextEditingController contentController = TextEditingController(); if (context.read<FirebaseAppAuth>().accountInfo.level == AccountType.admin) { titleController.text = announcement.title; contentController.text = announcement.content; showRoundedModalSheet( context: context, title: 'Редактировать объявление', child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFormField( controller: titleController, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline4, decoration: const InputDecoration(labelText: 'Введите заголовок'), ), const SizedBox(height: 10), ConstrainedBox( constraints: const BoxConstraints(minHeight: 200, maxHeight: 200), child: TextFormField( controller: contentController, keyboardType: TextInputType.multiline, maxLines: null, minLines: 10, textAlign: TextAlign.start, style: Theme.of(context).textTheme.bodyText1, decoration: const InputDecoration(labelText: 'Введите сообщение'), ), ), const SizedBox(height: 10), SizedBox( width: double.infinity, child: ElevatedButton( child: const Text('Отредактировать'), onPressed: () => updateAnnouncement( context, announcement.docId, titleController.text, contentController.text, ), ), ), const SizedBox(height: 10), Row( children: <Widget>[ Expanded( child: TextButton( onPressed: () => confirmDelete(context), child: const Text('Удалить'), ), ), const SizedBox(width: 10), Expanded( child: OutlinedButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), ], ), ], ), ); } } void updateAnnouncement( BuildContext context, String docId, String titleText, String contentText, ) { CollectionReference alerts = FirebaseFirestore.instance.collection(collectionPath()); alerts .doc(docId) .update({'content_title': titleText, 'content_body': contentText}); Navigator.pop(context); } void confirmDelete(BuildContext context) { Navigator.pop(context); showModalBottomSheet( context: context, isScrollControlled: true, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20), ), ), builder: (context) => Container( padding: MediaQuery.of(context).viewInsets, margin: EdgeInsets.only( top: 15, left: 15, right: 15, bottom: [ MediaQuery.of(context).viewInsets.bottom, MediaQuery.of(context).viewPadding.bottom, ].reduce(max) + 15, ), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( 'Удалить объявление?', style: Theme.of(context).textTheme.headline4, ), const SizedBox(height: 10), Row( children: [ Expanded( child: OutlinedButton( onPressed: () => Navigator.pop(context), child: const Text('Отмена'), ), ), const SizedBox(width: 10), Expanded( child: OutlinedButton( onPressed: () => deleteAnnouncement(context), child: const Text('Удалить'), ), ), ], ), ], ), ), ); } void deleteAnnouncement(BuildContext context) { CollectionReference alerts = FirebaseFirestore.instance.collection(collectionPath()); if (announcement.photoUrl != null) { FirebaseStorage storage = FirebaseStorage.instance; storage.ref('Announcements/${announcement.docId}').delete(); } alerts.doc(announcement.docId).delete(); Navigator.pop(context); } String collectionPath() { switch (announcement.accessLevel) { case AccountType.parent: return 'announcements_parents'; case AccountType.teacher: return 'announcements_teachers'; case AccountType.student: return 'announcements_students'; case AccountType.admin: return 'announcements_admins'; default: return 'announcements_all'; } } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/announcements/announcements_ui.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import '/models/announcement_model.dart'; import '/utils/icons.dart'; import '/widgets/loading_indicator.dart'; import '../../utils/theme/theme.dart'; import 'announcement_card.dart'; /// ListView with data from Firestore class AnnouncementsList extends StatefulWidget { final String collectionPath; const AnnouncementsList({ Key? key, required this.collectionPath, }) : super(key: key); @override State<AnnouncementsList> createState() => _AnnouncementsListState(); } class _AnnouncementsListState extends State<AnnouncementsList> { final ScrollController semicircleController = ScrollController(); late Stream<QuerySnapshot<Map<String, dynamic>>> stream; @override void initState() { stream = FirebaseFirestore.instance .collection(widget.collectionPath) .orderBy('id', descending: true) .snapshots(); super.initState(); } @override Widget build(BuildContext context) { return Column( children: <Widget>[ Expanded( child: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( stream: stream, builder: ( BuildContext context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot, ) { if (snapshot.hasError) { return Center( child: Padding( padding: const EdgeInsets.all(4.0), child: Text( 'Произошла ошибка при получении данных\n${snapshot.error}', style: Theme.of(context).textTheme.bodyText1, textAlign: TextAlign.center, ), ), ); } if (!snapshot.hasData) return const LoadingIndicator(); return Align( alignment: Alignment.topCenter, child: Scrollbar( interactive: true, controller: semicircleController, child: SingleChildScrollView( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 5, ), child: ListView.builder( physics: const NeverScrollableScrollPhysics(), controller: semicircleController, shrinkWrap: true, itemCount: snapshot.data!.docs.length, itemBuilder: (context, index) { return AnnouncementCard( announcement: AnnouncementModel.fromMap( snapshot.data!.docs[index].data(), snapshot.data!.docs[index].id, ), ); }, ), ), ), ); }, ), ), ], ); } } class AnnouncementsTabBar extends StatefulWidget { const AnnouncementsTabBar({ Key? key, }) : super(key: key); @override State<AnnouncementsTabBar> createState() => _AnnouncementsTabBarState(); } class _AnnouncementsTabBarState extends State<AnnouncementsTabBar> { @override Widget build(BuildContext context) { return DecoratedBox( decoration: BoxDecoration( color: context.palette.levelTwoSurface, border: Border( top: BorderSide(color: context.palette.outsideBorderColor), ), ), child: TabBar( padding: const EdgeInsets.symmetric(horizontal: 24), isScrollable: true, tabs: [ Tab( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Icon( Icons.group_outlined, size: 24, ), Padding( padding: EdgeInsets.only(left: 8.0), child: Text( 'Студентам', style: TextStyle(fontSize: 15), ), ), ], ), ), Tab( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Icon( VpecIconPack.parents, size: 24, ), Padding( padding: EdgeInsets.only(left: 8.0), child: Text( 'Родителям', style: TextStyle(fontSize: 15), ), ), ], ), ), Tab( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Icon( Icons.school_outlined, size: 24, ), Padding( padding: EdgeInsets.only(left: 8.0), child: Text( 'Преподавателям', style: TextStyle(fontSize: 15), ), ), ], ), ), Tab( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const <Widget>[ Icon( VpecIconPack.account_cog_outline, size: 24, ), Padding( padding: EdgeInsets.only(left: 8.0), child: Text( 'Администрации', style: TextStyle(fontSize: 15), ), ), ], ), ), ], ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/announcements/announcements_screen.dart
import 'package:animations/animations.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '../../utils/firebase_auth.dart'; import '../../utils/theme/theme.dart'; import '../../utils/theme_helper.dart'; import '../../widgets/system_bar_cover.dart'; import 'announcements_ui.dart'; import 'editor/editor_screen.dart'; class AnnouncementsScreen extends StatefulWidget { const AnnouncementsScreen({Key? key}) : super(key: key); @override State<AnnouncementsScreen> createState() => _AnnouncementsScreenState(); } class _AnnouncementsScreenState extends State<AnnouncementsScreen> { List<Widget> get tabBarChildren { switch (AccountDetails.getAccountLevel) { case AccountType.admin: return [ const AnnouncementsList(collectionPath: 'announcements_students'), const AnnouncementsList(collectionPath: 'announcements_parents'), const AnnouncementsList(collectionPath: 'announcements_teachers'), const AnnouncementsList(collectionPath: 'announcements_admins'), ]; case AccountType.student: return [ const AnnouncementsList(collectionPath: 'announcements_students'), ]; case AccountType.parent: return [ const AnnouncementsList(collectionPath: 'announcements_parents'), ]; case AccountType.teacher: return [ const AnnouncementsList(collectionPath: 'announcements_teachers'), ]; default: return [ const AnnouncementsList(collectionPath: 'announcements_students'), ]; } } @override void initState() { FirebaseAnalytics.instance.setCurrentScreen(screenName: 'announcements_screen'); super.initState(); } @override Widget build(BuildContext context) { return DefaultTabController( length: tabBarChildren.length, child: Scaffold( extendBodyBehindAppBar: true, appBar: StatusBarCover( height: MediaQuery.of(context).padding.top, ), body: TabBarView( physics: const NeverScrollableScrollPhysics(), children: tabBarChildren, ), floatingActionButton: AccountDetails.isAdmin ? const AnimatedFAB() : null, bottomNavigationBar: AccountDetails.isAdmin ? const AnnouncementsTabBar() : null, ), ); } } class AnimatedFAB extends StatelessWidget { const AnimatedFAB({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return OpenContainer( transitionDuration: const Duration(milliseconds: 600), transitionType: ContainerTransitionType.fadeThrough, closedElevation: 0, closedShape: CircleBorder( side: BorderSide(color: context.palette.outsideBorderColor), ), closedColor: context.palette.levelThreeSurface, middleColor: context.palette.backgroundSurface, openElevation: 0, openColor: context.palette.backgroundSurface, onClosed: (n) { Future.delayed(const Duration(milliseconds: 100)).then( (value) => ThemeHelper.colorSystemChrome( mode: ColoringMode.byCurrentTheme, ), ); }, closedBuilder: (context, action) { return FloatingActionButton( backgroundColor: Colors.transparent, shape: const CircleBorder(), onPressed: action, child: const Icon(Icons.rate_review_outlined), ); }, openBuilder: (context, action) { return const AnnouncementEditor(); }, ); } }
0
mirrored_repositories/vpec/lib/screens/announcements
mirrored_repositories/vpec/lib/screens/announcements/editor/editor_logic.dart
import 'dart:async'; import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:file_picker/file_picker.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../../../models/announcement_model.dart'; import '../../../utils/firebase_auth.dart'; import '../../../utils/hive_helper.dart'; class EditorLogic extends ChangeNotifier { /// Shows, should publish button be active or disabled. bool publishButtonActive = false; /// Stores user typed text for title and body TextEditingController announcementTitleController = TextEditingController(); TextEditingController announcementBodyController = TextEditingController(); /// Stores url for uploaded image. Can be null, if image is not uploaded String? photoUrl; /// Shows current progress image uploading. Can be null, /// if nothing is uploading double? photoUploadProgress; /// Used as document ID for Firestore document. Also used for photo name. int docID = DateTime.now().millisecondsSinceEpoch; /// List of publish privacy Map<String, bool> publishFor = { 'students': false, 'parents': false, 'teachers': false, 'admins': false, }; /// Use for update values from checkboxes in [publishFor] void updateCheckbox(final String changeFor, final bool newValue) { publishFor.update(changeFor, (_) => newValue); checkAndUpdatePublishButtonActiveStatus(); } /// Checks for user selected privacy for creating article, and if nothing /// was selected, then disables button. void checkAndUpdatePublishButtonActiveStatus() { bool publishCategoryWasSelected = false; bool titleAndBodyWasEntered = announcementTitleController.text.trim().isNotEmpty && announcementBodyController.text.trim().isNotEmpty; // checks whether the user has selected a category or not publishFor.forEach((key, value) { if (value) publishCategoryWasSelected = true; }); bool isUsernameWasAdded = HiveHelper.getValue('username') != null && HiveHelper.getValue('username') != ''; publishButtonActive = publishCategoryWasSelected && titleAndBodyWasEntered && isUsernameWasAdded; notifyListeners(); } /// Converts user typed data to [AnnouncementModel] and send it to /// upload for every user selected category. Future<void> publishAnnouncement() async { DateFormat formatter = DateFormat('HH:mm, d MMM yyyy'); String pubDate = formatter.format(DateTime.now()); final AnnouncementModel article = AnnouncementModel( author: HiveHelper.getValue('username'), content: announcementBodyController.text.trim(), pubDate: pubDate, title: announcementTitleController.text.trim(), docId: docID.toString(), photoUrl: photoUrl, accessLevel: AccountType.admin, // ignore this field ); publishFor.forEach((key, value) async { if (value) { await _uploadArticle(key, article); publishButtonActive = false; } }); } /// Uploads to the Firestore, depending on what the value of the [publishFor] /// is equal to. /// /// Can throw an Exception, if unknown type was received. Future<void> _uploadArticle( String publishFor, AnnouncementModel article, ) async { String collectionPath() { switch (publishFor) { case 'parents': return 'announcements_parents'; case 'students': return 'announcements_students'; case 'teachers': return 'announcements_teachers'; case 'admins': return 'announcements_admins'; default: throw Exception('Unknown account type'); } } CollectionReference announcements = FirebaseFirestore.instance.collection(collectionPath()); await announcements.doc(article.docId).set({ 'author': article.author, 'content_title': article.title, 'content_body': article.content, 'date': article.pubDate, 'photo': article.photoUrl, 'id': article.docId, 'visibility': publishFor, }); } /// Opens image picker and listening for picked photo. If photo was picked, /// uploads it to Firebase Storage and stores photo link. Future<void> pickImage() async { final FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.image, allowMultiple: false, ); if (result == null) return; final File image = File(result.files.first.path!); final firebaseStorage = FirebaseStorage.instance.ref('Announcements/$docID').putFile(image); late StreamSubscription uploadingStreamsub; uploadingStreamsub = firebaseStorage.snapshotEvents.listen((event) async { photoUploadProgress = event.bytesTransferred.toDouble() / event.totalBytes.toDouble(); notifyListeners(); if (event.state == TaskState.success) { photoUrl = await event.ref.getDownloadURL(); notifyListeners(); uploadingStreamsub.cancel(); } }); } /// Deletes uploaded image to Firebase Storage, if something was uploaded. /// It is used if the user uploaded a photo and closed the editor. void cleanUp() { if (photoUrl == null) return; FirebaseStorage storage = FirebaseStorage.instance; storage.ref('Announcements/$docID').delete(); } }
0
mirrored_repositories/vpec/lib/screens/announcements
mirrored_repositories/vpec/lib/screens/announcements/editor/editor_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../../utils/hive_helper.dart'; import '../../../utils/theme/theme.dart'; import '../../../utils/theme_helper.dart'; import '../../settings/settings_logic.dart'; import 'editor_logic.dart'; import 'editor_ui.dart'; class AnnouncementEditor extends StatefulWidget { const AnnouncementEditor({Key? key}) : super(key: key); @override State<AnnouncementEditor> createState() => _AnnouncementEditorState(); } class _AnnouncementEditorState extends State<AnnouncementEditor> { @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) { if (HiveHelper.getValue('username') == null || HiveHelper.getValue('username') == '') { ScaffoldMessenger.of(context).showSnackBar(SnackBar( backgroundColor: context.palette.levelTwoSurface, behavior: SnackBarBehavior.floating, duration: const Duration(minutes: 1), action: SnackBarAction( label: 'Указать имя', onPressed: () => SettingsLogic.changeName(context), ), content: Text( 'Для того, чтобы отправить объявление, необходимо указать имя', style: Theme.of(context).textTheme.subtitle2, ), )); } }); } @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return ChangeNotifierProvider<EditorLogic>( create: (_) => EditorLogic(), child: SafeArea( child: Scaffold( body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( children: const [ Padding( padding: EdgeInsets.symmetric(vertical: 15.0), child: EditorHeader(), ), EditorUI(), SizedBox(height: 20), VisibilityPicker(), SizedBox(height: 10), DialogButtons(), ], ), ), ), ), ), ); } }
0
mirrored_repositories/vpec/lib/screens/announcements
mirrored_repositories/vpec/lib/screens/announcements/editor/editor_ui.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:provider/provider.dart'; import '../../../utils/theme/theme.dart'; import '../../settings/settings_logic.dart'; import 'editor_logic.dart'; class EditorHeader extends StatelessWidget { const EditorHeader({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, child: Text( 'Новое объявление', style: Theme.of(context).textTheme.headline6, textAlign: TextAlign.center, ), ); } } class ImagePreview extends StatelessWidget { const ImagePreview({Key? key, required this.imagePath}) : super(key: key); final String imagePath; @override Widget build(BuildContext context) { return Container( clipBehavior: Clip.antiAlias, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), ), child: CachedNetworkImage(imageUrl: imagePath), ); } } class UploadAttachmentButton extends StatelessWidget { const UploadAttachmentButton({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<EditorLogic>( builder: (context, logic, _) { return DecoratedBox( decoration: BoxDecoration( color: context.palette.levelTwoSurface, borderRadius: BorderRadius.circular(20), border: Border.all( color: context.palette.outsideBorderColor, ), ), child: Material( type: MaterialType.transparency, borderRadius: BorderRadius.circular(20), child: InkWell( borderRadius: BorderRadius.circular(20), onTap: logic.pickImage, child: SizedBox( height: 50, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( children: [ Icon( Icons.attachment_outlined, color: context.palette.accentColor, ), const SizedBox(width: 10), Text( 'Прикрепить картинку', style: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 16, color: context.palette.accentColor, ), ), ], ), if (logic.photoUploadProgress != null) LinearProgressIndicator( value: logic.photoUploadProgress, ), ], ), ), ), ), ), ); }, ); } } class TitleEditorField extends StatefulWidget { const TitleEditorField({Key? key}) : super(key: key); @override State<TitleEditorField> createState() => _TitleEditorFieldState(); } class _TitleEditorFieldState extends State<TitleEditorField> { bool _isEmpty = true; late FocusNode _focusNode; bool _isFocused = false; @override void initState() { _focusNode = FocusNode(); _focusNode.addListener(_onFocusChange); super.initState(); } void _onFocusChange() { setState(() => _isFocused = _focusNode.hasPrimaryFocus); } @override Widget build(BuildContext context) { return Row( children: [ AnimatedContainer( curve: Curves.easeOut, foregroundDecoration: BoxDecoration( color: _isEmpty ? null : context.palette.levelOneSurface, ), decoration: const BoxDecoration(), clipBehavior: Clip.hardEdge, alignment: Alignment.centerLeft, height: 24, width: _isEmpty ? 34 : 0, duration: const Duration(milliseconds: 300), child: Icon( Icons.edit_outlined, color: _isFocused ? context.palette.accentColor : context.palette.mediumEmphasis, ), ), Flexible( child: TextField( minLines: 1, maxLines: 3, controller: context.read<EditorLogic>().announcementTitleController, focusNode: _focusNode, onChanged: (text) { context .read<EditorLogic>() .checkAndUpdatePublishButtonActiveStatus(); setState(() { _isEmpty = text.isEmpty; }); }, textInputAction: TextInputAction.next, keyboardType: TextInputType.text, style: Theme.of(context).textTheme.headline4, decoration: const InputDecoration( isCollapsed: true, contentPadding: EdgeInsets.symmetric(vertical: 8), hintText: 'Введите заголовок..', border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, ), ), ), ], ); } } class BodyEditorField extends StatefulWidget { const BodyEditorField({Key? key}) : super(key: key); @override State<BodyEditorField> createState() => _BodyEditorFieldState(); } class _BodyEditorFieldState extends State<BodyEditorField> { bool _isEmpty = true; late FocusNode _focusNode; bool _isFocused = false; @override void initState() { _focusNode = FocusNode(); _focusNode.addListener(_onFocusChange); super.initState(); } void _onFocusChange() { setState(() => _isFocused = _focusNode.hasPrimaryFocus); } @override Widget build(BuildContext context) { TextEditingController controller = context.read<EditorLogic>().announcementBodyController; return Row( children: [ AnimatedContainer( curve: Curves.easeOut, foregroundDecoration: BoxDecoration( color: _isEmpty ? null : context.palette.levelOneSurface, ), decoration: const BoxDecoration(), clipBehavior: Clip.hardEdge, alignment: Alignment.centerLeft, height: 24, width: _isEmpty ? 34 : 0, duration: const Duration(milliseconds: 300), child: Icon( Icons.edit_outlined, color: _isFocused ? context.palette.accentColor : context.palette.mediumEmphasis, ), ), Flexible( child: TextField( maxLines: null, controller: controller, focusNode: _focusNode, onChanged: (text) { context .read<EditorLogic>() .checkAndUpdatePublishButtonActiveStatus(); setState(() { _isEmpty = text.isEmpty; }); }, textInputAction: TextInputAction.newline, keyboardType: TextInputType.multiline, style: Theme.of(context).textTheme.bodyText1, decoration: InputDecoration( isCollapsed: true, contentPadding: const EdgeInsets.symmetric(vertical: 8), hintText: 'Введите сообщение..', hintStyle: Theme.of(context) .textTheme .bodyText1! .copyWith(color: context.palette.mediumEmphasis), border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, ), ), ), ], ); } } class AuthorName extends StatelessWidget { const AuthorName({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Align( alignment: Alignment.centerRight, child: GestureDetector( onTap: () async { await SettingsLogic.changeName(context); context.read<EditorLogic>().checkAndUpdatePublishButtonActiveStatus(); }, child: Padding( padding: const EdgeInsets.only(top: 7, right: 15.0, bottom: 13), child: ValueListenableBuilder( valueListenable: Hive.box('settings').listenable(keys: ['username']), builder: (context, Box box, child) { final String userName = box.get( 'username', defaultValue: 'Имя не указано', ); final String field = userName.isEmpty ? 'Нажмите, чтобы задать имя' : userName; return Row( mainAxisSize: MainAxisSize.min, children: [ Text( field, style: Theme.of(context).textTheme.subtitle1!.copyWith( color: userName.isEmpty ? context.palette.highEmphasis : context.palette.mediumEmphasis, ), ), const SizedBox(width: 5), Icon( Icons.edit_outlined, color: userName.isEmpty ? context.palette.highEmphasis : context.palette.mediumEmphasis, ), ], ); }, ), ), ), ); } } class EditorUI extends StatelessWidget { const EditorUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<EditorLogic>( builder: (context, logic, _) { return DecoratedBox( decoration: BoxDecoration( color: context.palette.levelOneSurface, borderRadius: BorderRadius.circular(20), border: Border.all(color: context.palette.outsideBorderColor), ), child: SizedBox( width: double.infinity, child: Column( children: [ logic.photoUrl == null ? const UploadAttachmentButton() : ImagePreview(imagePath: logic.photoUrl!), Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Column( children: const [ SizedBox(height: 8), TitleEditorField(), BodyEditorField(), ], ), ), const AuthorName(), ], ), ), ); }, ); } } class VisibilityPicker extends StatelessWidget { const VisibilityPicker({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<EditorLogic>( builder: (context, logic, _) { return Column( children: [ Text( 'Выберите видимость:', style: Theme.of(context).textTheme.headline6, textAlign: TextAlign.center, ), const SizedBox(height: 10), CheckboxListTile( dense: true, contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, checkColor: context.palette.backgroundSurface, activeColor: context.palette.accentColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), controlAffinity: ListTileControlAffinity.leading, value: logic.publishFor['students'], title: Text( 'Студентам', style: Theme.of(context).textTheme.headline3!.copyWith( fontWeight: FontWeight.w600, ), ), onChanged: (value) { logic.updateCheckbox('students', value ?? false); }, ), CheckboxListTile( dense: true, contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, checkColor: context.palette.backgroundSurface, activeColor: context.palette.accentColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), controlAffinity: ListTileControlAffinity.leading, value: logic.publishFor['parents'], title: Text( 'Родителям', style: Theme.of(context).textTheme.headline3!.copyWith( fontWeight: FontWeight.w600, ), ), onChanged: (value) { logic.updateCheckbox('parents', value ?? false); }, ), CheckboxListTile( dense: true, contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, checkColor: context.palette.backgroundSurface, activeColor: context.palette.accentColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), controlAffinity: ListTileControlAffinity.leading, value: logic.publishFor['teachers'], title: Text( 'Преподавателям', style: Theme.of(context).textTheme.headline3!.copyWith( fontWeight: FontWeight.w600, ), ), onChanged: (value) { logic.updateCheckbox('teachers', value ?? false); }, ), CheckboxListTile( dense: true, contentPadding: EdgeInsets.zero, visualDensity: VisualDensity.compact, checkColor: context.palette.backgroundSurface, activeColor: context.palette.accentColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), controlAffinity: ListTileControlAffinity.leading, value: logic.publishFor['admins'], title: Text( 'Администрации', style: Theme.of(context).textTheme.headline3!.copyWith( fontWeight: FontWeight.w600, ), ), onChanged: (value) { logic.updateCheckbox('admins', value ?? false); }, ), ], ); }, ); } } class DialogButtons extends StatelessWidget { const DialogButtons({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: TextButton( onPressed: () { context.read<EditorLogic>().cleanUp(); Navigator.pop(context); }, child: const Text('Закрыть'), ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( onPressed: context.watch<EditorLogic>().publishButtonActive ? () async { await context.read<EditorLogic>().publishAnnouncement(); Navigator.pop(context); } : null, child: const Text('Опубликовать'), ), ), ], ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/documents/documents_ui.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '/models/document_model.dart'; import '/widgets/loading_indicator.dart'; import '/widgets/styled_widgets.dart'; class DocumentsList extends StatelessWidget { const DocumentsList({Key? key}) : super(key: key); @override Widget build(BuildContext context) { Stream<QuerySnapshot<Map<String, dynamic>>> stream = FirebaseFirestore.instance.collection('documents').snapshots(); return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( stream: stream, builder: ( BuildContext context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot, ) { if (!snapshot.hasData) return const LoadingIndicator(); return ListView( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, children: snapshot.data!.docs.map((document) { return DocumentCard( document: DocumentModel.fromMap(document.data(), document.id), ); }).toList(), ); }, ); } } class DocumentCard extends StatelessWidget { final DocumentModel document; const DocumentCard({Key? key, required this.document}) : super(key: key); @override Widget build(BuildContext context) { return StyledListTile( title: document.title, subtitle: document.subtitle, onTap: () { FirebaseAnalytics.instance.logEvent(name: 'document_opened', parameters: { 'url': document.url, 'title': document.title, }); Navigator.pushNamed( context, '/view_document', arguments: document, ); }, ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/documents/documents_screen.dart
import 'package:flutter/material.dart'; import '/utils/theme_helper.dart'; import '../../widgets/system_bar_cover.dart'; import 'documents_ui.dart'; class DocumentsScreen extends StatelessWidget { const DocumentsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Scaffold( extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), appBar: AppBar( title: const Text('Документы'), ), body: SingleChildScrollView( padding: const EdgeInsets.all(10), child: Column( children: const <Widget>[ DocumentsList(), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/schedule/schedule_ui.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:r_dotted_line_border/r_dotted_line_border.dart'; import '../../models/full_schedule.dart'; import '../../models/schedule/schedule_item.dart'; import '../../utils/hive_helper.dart'; import '../../utils/routes/routes.dart'; import '../../utils/theme/theme.dart'; import '../../utils/theme_helper.dart'; import '../settings/settings_logic.dart'; import 'schedule_item_logic.dart'; import 'schedule_logic.dart'; class ScheduleItem extends StatelessWidget { const ScheduleItem({Key? key, required this.model}) : super(key: key); final ScheduleItemModel model; Color getItemColor(BuildContext context) { if (model.lessonName.isEmpty) { return context.palette.lowEmphasis; } return model.timer == null || model.timer!.isEmpty ? context.palette.mediumEmphasis : context.palette.highEmphasis; } @override Widget build(BuildContext context) { return Consumer<ScheduleItemLogic>( builder: (context, logic, _) { return GestureDetector( onTap: model.lessonName.isEmpty ? null : () => logic.toggleAdditionalInfo( names: model.teachers, lessonName: model.lessonName, lessonFullNames: model.lessonsFullNames, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.only(left: 10.0, top: 9.0, bottom: 15.0), decoration: BoxDecoration( border: Border( left: BorderSide( color: getItemColor(context), width: 3, ), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FittedBox( fit: BoxFit.scaleDown, child: Text( '${model.lessonBeginning} - ${model.lessonEnding}', style: TextStyle( color: getItemColor(context), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 36.0, letterSpacing: 0.15, ), ), ), Text( model.lessonName != '' ? '${model.lessonNumber} пара - ${model.lessonName}' : '${model.lessonNumber} пара', style: TextStyle( color: getItemColor(context), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 18.0, letterSpacing: 0.15, ), ), if (model.timer != null && model.timer! != '') Padding( padding: const EdgeInsets.only(top: 6), child: Text( model.timer!, style: TextStyle( color: getItemColor(context), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 18.0, letterSpacing: 0.15, ), ), ), AdditionalInfo( open: logic.open, info: logic.infoWidget, ), ], ), ), if (model.pauseAfterLesson != '') Container( padding: const EdgeInsets.only(left: 10, top: 9.5, bottom: 9), decoration: BoxDecoration( border: RDottedLineBorder( // Меняй этой значение, чтобы дэши попали в расстояние нормально dottedLength: 3.5, dottedSpace: 3, left: BorderSide(width: 3, color: getItemColor(context)), ), ), child: Text( model.pauseAfterLesson, style: TextStyle( color: getItemColor(context), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 18.0, letterSpacing: 0.15, ), ), ), ], ), ); }, ); } } class AdditionalInfo extends StatefulWidget { const AdditionalInfo({ Key? key, required this.open, required this.info, }) : super(key: key); final bool open; final Widget info; @override State<AdditionalInfo> createState() => _AdditionalInfoState(); } class _AdditionalInfoState extends State<AdditionalInfo> { @override Widget build(BuildContext context) { return AnimatedSize( curve: Curves.ease, duration: const Duration(milliseconds: 250), child: widget.info, ); } } class SchedulePanel extends StatelessWidget { const SchedulePanel({ Key? key, required this.fullSchedule, }) : super(key: key); final FullSchedule fullSchedule; @override Widget build(BuildContext context) { List<Widget> schedulePanel = List<Widget>.generate(fullSchedule.timetable.length, (index) { String lessonNum = index.toString(); String lessonEnding = fullSchedule.timetable[lessonNum].split('-').last; String nextLessonBeginning() { String? time = fullSchedule.timetable[(index + 1).toString()]; if (time == null) return lessonEnding; return time.split('-').first; } String lessonName() { String name = ScheduleTime.replaceLessonName( shortLessonName: fullSchedule.schedule[lessonNum].toString(), lessonShortNames: fullSchedule.shortLessonNames, lessonFullNames: fullSchedule.fullLessonNames, ); if (name == '0') name = ''; // if (name.isNotEmpty) name = '- $name'; return name; } bool shouldGiveTimers = fullSchedule.timers.isNotEmpty; return ChangeNotifierProvider<ScheduleItemLogic>( create: (_) => ScheduleItemLogic(), child: ScheduleItem( model: ScheduleItemModel( timer: shouldGiveTimers ? fullSchedule.timers[index] : null, lessonNumber: index, teachers: fullSchedule.teachers, lessonsFullNames: fullSchedule.fullLessonNames, lessonsShortNames: fullSchedule.shortLessonNames, lessonBeginning: fullSchedule.timetable[lessonNum].split('-').first, lessonEnding: fullSchedule.timetable[lessonNum].split('-').last, lessonName: lessonName(), pauseAfterLesson: ScheduleTime.calculatePauseAfterLesson( lessonEnding, nextLessonBeginning(), ), ), ), ); }); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: schedulePanel, ); } } class FABPanel extends StatelessWidget { const FABPanel({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ FloatingActionButton( mini: true, tooltip: 'Полное расписание', heroTag: null, onPressed: () async { await Navigator.pushNamed(context, Routes.fullScheduleScreen); ThemeHelper.colorSystemChrome(); }, child: const Icon(Icons.fullscreen_outlined), ), const SizedBox( height: 8, ), FloatingActionButton( tooltip: 'Расписание на завтра/сегодня', heroTag: null, onPressed: () => context.read<ScheduleLogic>().toggleShowingLesson(), child: Icon(context.watch<ScheduleLogic>().showingForToday ? Icons.arrow_forward_ios_outlined : Icons.arrow_back_ios_outlined), ), ], ); } } class AdditionalInfoPanelWidget extends StatelessWidget { const AdditionalInfoPanelWidget({ Key? key, required this.names, required this.notes, required this.lessonName, }) : super(key: key); final String names; final String? notes; final String lessonName; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 0.0), child: Column( children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 12.0), child: Row( children: [ Icon( Icons.badge_outlined, color: context.palette.highEmphasis, ), const SizedBox( width: 10, ), Expanded( child: Text( names, style: Theme.of(context).textTheme.headline6, ), ), ], ), ), SizedBox( height: 160, child: TextField( controller: TextEditingController(text: notes), decoration: const InputDecoration( labelText: 'Заметки', helperText: 'Хранятся только на данном устройстве', ), maxLines: 6, style: Theme.of(context).textTheme.bodyText1, onChanged: (text) { HiveHelper.saveValue(key: 'note_$lessonName', value: text); }, ), ), ], ), ); } } class ScheduleErrorLoadingUI extends StatelessWidget { const ScheduleErrorLoadingUI({ Key? key, required this.errorText, }) : super(key: key); final String? errorText; @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(top: MediaQuery.of(context).size.height / 4), child: Column( children: [ Text( errorText ?? 'Произошла ошибка при загрузке расписания', style: const TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.w400, fontSize: 18.0, letterSpacing: 0.15, ), textAlign: TextAlign.center, ), if (errorText == 'Не выбрана группа для показа расписания') OutlinedButton( onPressed: () async { await SettingsLogic.chooseGroup(context); context.read<ScheduleLogic>().loadSchedule(); }, child: const Text('Выбрать группу'), ), ], ), ); } } class ChosenGroupBadge extends StatelessWidget { const ChosenGroupBadge({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () async { await SettingsLogic.chooseGroup(context); context.read<ScheduleLogic>().loadSchedule(); }, child: Padding( padding: const EdgeInsets.only(left: 10, top: 9.5, bottom: 9), child: Row( children: [ Flexible( child: Text( 'Для группы ${HiveHelper.getValue('chosenGroup')}', style: TextStyle( color: context.palette.lowEmphasis, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 18.0, letterSpacing: 0.15, ), ), ), Padding( padding: const EdgeInsets.only(left: 8), child: Icon( Icons.edit_outlined, color: context.palette.lowEmphasis, ), ), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/schedule/schedule_logic.dart
import 'dart:async'; import 'dart:convert'; import 'package:duration/duration.dart'; import 'package:duration/locale.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; import '../../models/full_schedule.dart'; import '../../models/schedule/group_definition.dart'; import '../../models/schedule/schedule.dart'; import '../../models/schedule/timetable.dart'; import '../../utils/hive_helper.dart'; import 'schedule_screen.dart'; class ScheduleLogic extends ChangeNotifier { /// Contains all the information about the schedule /// (timetable, schedule, shortLessonNames, fullLessonNames, teachers) FullSchedule? fullSchedule; /// Indicates whether schedule is being shown for today or not bool showingForToday = true; /// String of the format "d-M-yyyy", which shows the currently selected date String showingData = DateFormat('d-M-yyyy').format(DateTime.now()); /// Indicates active lesson int activeLessonIndex = 0; /// Indicates whether an error occurred during data processing or not bool hasError = false; /// Used for textual notification of errors to the user in [ScheduleScreen] String? errorText; /// Used for automatically update timetable /// /// call [startTimersUpdating] to start updating. Timer? _timer; /// Used for time counting bool _needPrintTimer = true; Duration _smallestUntilStartDuration = const Duration(days: 2); /// Convert [showingData] to human readability text at russian, e.g /// /// 27 января 2021 String get printCurrentDate { DateTime parsed = DateFormat('d-M-yyyy', 'ru').parse(showingData); DateFormat formatter = DateFormat('d MMMM yyyy'); return formatter.format(parsed); } // Accepts date and converts to schedule URL String _makeUrl(String date) => 'https://energocollege.ru/vec_assistant/' '%D0%A0%D0%B0%D1%81%D0%BF%D0%B8%D1%81%D0%B0%D0%BD%D0%B8%D0%B5/' '$date.json'; /// Switch schedule display to today or tomorrow Future<void> toggleShowingLesson() async { showingForToday = !showingForToday; notifyListeners(); await loadSchedule(); FirebaseAnalytics.instance.logEvent(name: 'schedule_toggled', parameters: { 'today_schedule' : showingForToday, }); } /// Gets required date and parses schedule /// /// Returns [true] if parse was successful Future<bool> loadSchedule() async { DateTime date = DateTime.now(); DateFormat formatter = DateFormat('d-M-yyyy'); int plusDays = 0; int today = date.weekday; bool isWeekend = false; switch (today) { case DateTime.friday: plusDays = 3; break; case DateTime.saturday: plusDays = 2; isWeekend = true; break; case DateTime.sunday: plusDays = 1; isWeekend = true; break; default: plusDays = 1; break; } if (!showingForToday || isWeekend) { date = date.add(Duration(days: plusDays)); if (isWeekend) showingForToday = false; } showingData = formatter.format(date); await _getActualData(_makeUrl(showingData)); return fullSchedule != null; } /// Show DatePicker dialog for schedule, if user pick one of the days, /// then load picked schedule Future<void> chooseData(BuildContext context) async { final DateTime? picked = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2018, 8), lastDate: DateTime.now().add(const Duration(days: 30)), ); if (picked != null) { DateFormat formatter = DateFormat('d-M-yyyy'); showingData = formatter.format(picked); await _getActualData(_makeUrl(showingData)); FirebaseAnalytics.instance.logEvent(name: 'schedule_date_chosen', parameters: { 'date': showingData, }); } } /// Parse full schedule from given [url] Future<void> _getActualData(String url) async { // clear old data fullSchedule = null; late String scheduleData; try { var file = await DefaultCacheManager().getSingleFile(url); scheduleData = utf8.decode(await file.readAsBytes()); hasError = false; } catch (e) { http.Response response = await http.get(Uri.parse(url)).timeout(const Duration(seconds: 90)); if (response.statusCode == 200) { DefaultCacheManager().putFile(url, response.bodyBytes); hasError = false; scheduleData = response.body; } else { hasError = true; errorText = getErrorTextByStatusCode(response.statusCode); } } if (!hasError) { String group = await HiveHelper.getValue('chosenGroup') ?? ''; if (group.isNotEmpty) { fullSchedule = FullSchedule( timetable: _getTimetable(scheduleData, group), schedule: _getSchedule(scheduleData, group), shortLessonNames: _getGroupDefinition(scheduleData, '${group}_short'), fullLessonNames: _getGroupDefinition(scheduleData, '${group}_full'), teachers: _getGroupDefinition(scheduleData, '${group}_teacher'), groups: group, ); // get timers for this schedule getTimers(); } else { hasError = true; errorText = 'Не выбрана группа для показа расписания'; } } notifyListeners(); } /// Parse [Timetable] from [data] for this [group] Map<String, dynamic> _getTimetable(String data, String group) { return Timetable.fromJson(json.decode(data)).timetableMap[group]; } /// Parse [Schedule] from [data] for this [group] Map<String, dynamic> _getSchedule(String data, String group) { return Schedule.fromJson(json.decode(data)).scheduleMap[group]; } /// Parse [GroupDefinition] from [data] for this [group] Map<String, dynamic> _getGroupDefinition(String data, String group) { return GroupDefinition.fromJson(json.decode(data)) .groupDefinitionMap[group]; } /// Sets new active lesson with given [index]. void setActiveLesson(int index) { activeLessonIndex = index; notifyListeners(); } /// Converts basic status codes into text errors that are /// understandable to the user String? getErrorTextByStatusCode(int statusCode) { switch (statusCode) { case 404: // Not found return 'Расписание занятий на данный день не найдено.\n\n' 'Если уверены, что расписание занятий доступно, ' 'попробуйте открыть полное расписание'; case 408: // Request Timeout return 'Похоже, что нет ответа от сервера\n\n' 'Проверьте подключение к сети'; default: // Any other code return null; } } /// Gets or updates timers for actual [fullSchedule] /// /// Timer - is a string format 'До конца: 28 минут' void getTimers() { if (fullSchedule != null) { DateTime now = DateTime.now(); List<String?> timers = fullSchedule!.timers; // immutable list List<String?> newTimers = []; // mutable list newTimers.addAll(timers); fullSchedule!.timetable.forEach((key, value) { // parse time for current lesson // raw time in string String beginning = value.split('-').first; String ending = value.split('-').last; // String time converted to DateTime DateTime lessonBeginning = DateFormat('HH:mm').parse(beginning); DateTime lessonEnding = DateFormat('HH:mm').parse(ending); // DateTime time converted to Duration Duration nowDuration = Duration(hours: now.hour, minutes: now.minute, seconds: now.second); Duration startDuration = Duration( hours: lessonBeginning.hour, minutes: lessonBeginning.minute, ); Duration endDuration = Duration(hours: lessonEnding.hour, minutes: lessonEnding.minute); if (nowDuration >= startDuration && nowDuration < endDuration) { _needPrintTimer = false; setActiveLesson(int.parse(key)); newTimers.insert( int.parse(key), 'До конца: ${_getTime(endDuration - nowDuration)}', ); fullSchedule = fullSchedule!.copyWith( timers: newTimers, ); if (endDuration - nowDuration <= const Duration(seconds: 1)) { _smallestUntilStartDuration = const Duration(days: 2); _needPrintTimer = true; } } else { if (nowDuration < startDuration && _needPrintTimer && startDuration - nowDuration <= _smallestUntilStartDuration) { _smallestUntilStartDuration = startDuration - nowDuration; newTimers.insert( int.parse(key), 'До начала: ${_getTime(startDuration - nowDuration)}', ); fullSchedule = fullSchedule!.copyWith( timers: newTimers, ); } else { newTimers.insert(int.parse(key), ''); } } }); notifyListeners(); } } /// Convert [duration] to human readability text at russian, e.g /// /// 34 минуты String _getTime(Duration duration) { return prettyDuration( Duration(minutes: duration.inMinutes + 1), locale: const RussianDurationLanguage(), ); } /// Start automatically updating timers for actual timetable void startTimersUpdating() { _timer = Timer.periodic( const Duration(seconds: 1), (timer) => getTimers(), ); } /// Stop automatically updating timers for actual timetable void cancelTimersUpdating() { if (_timer != null) _timer!.cancel(); } } class ScheduleTime { /// Calculates a pause based on two parameters: /// /// [lessonEnding] - end time of current lesson /// /// [nextLessonBeginning] - beginning time of next lesson /// /// **All strings must be 'HH:mm' format** static String calculatePauseAfterLesson( String lessonEnding, String nextLessonBeginning, ) { DateTime dateLessonEnding = DateFormat('HH:mm').parse(lessonEnding); DateTime dateNextLessonBeginning = DateFormat('HH:mm').parse(nextLessonBeginning); String pause = prettyDuration( dateNextLessonBeginning.difference(dateLessonEnding), locale: DurationLocale.fromLanguageCode('ru')!, ); pause = pause.replaceAll('0 секунд', ''); if (pause.isNotEmpty) pause = 'Перемена: $pause'; return pause; } /// Replaces the short name of the lesson with the full name of the lesson. /// /// Short names should be provided in [lessonShortNames]. /// /// Full names should be provided in [lessonFullNames]. /// /// [shortLessonName] is a name of the lesson to replace. /// /// /// /// The order of the names in [lessonShortNames] and [lessonFullNames] /// should be the same. static String replaceLessonName({ required String shortLessonName, required Map<String, dynamic> lessonShortNames, required Map<String, dynamic> lessonFullNames, }) { // если пары перечислены через "/", например "матем/физ", то разбиваем // пары и ищем их полные названия if (shortLessonName.contains('/')) { List<String> lessons = shortLessonName.split('/'); String visibleName = 'Разделение: '; var f = lessons[0].trim(); var s = lessons[1].trim(); var firstLesson = lessonShortNames.containsValue(f) ? lessonFullNames[ lessonShortNames.keys.firstWhere((k) => lessonShortNames[k] == f)] : f; var secondLesson = lessonShortNames.containsValue(s) ? lessonFullNames[ lessonShortNames.keys.firstWhere((k) => lessonShortNames[k] == s)] : s; visibleName += ('\n① $firstLesson\n② $secondLesson'); return visibleName; } // если пара для одной подгруппы, то убираем "(1)", ищем полное название // пары и отображаем текст по новому if (shortLessonName.contains('(1)') || shortLessonName.contains('(2)')) { var trimmedShortName = shortLessonName.substring( 0, shortLessonName.length - 3, ); var trimmedNumber = shortLessonName.substring( shortLessonName.length - 2, shortLessonName.length - 1, ); var textGroupNumber = trimmedNumber == '1' ? 'Для первой подгруппы' : 'Для второй подгруппы'; trimmedNumber = trimmedNumber == '1' ? '①' : '②'; var trimmedFullName = lessonShortNames.containsValue(trimmedShortName) ? lessonFullNames[lessonShortNames.keys .firstWhere((k) => lessonShortNames[k] == trimmedShortName)] : trimmedShortName; return '$textGroupNumber:\n$trimmedNumber $trimmedFullName'; } // если пара для обеих подгрупп "пм.Х.Х(1.2)" if (shortLessonName.contains('(1,2)')) { var trimmedShortName = shortLessonName.substring( 0, shortLessonName.length - 5, ); var trimmedFullName = lessonShortNames.containsValue(trimmedShortName) ? lessonFullNames[lessonShortNames.keys .firstWhere((k) => lessonShortNames[k] == trimmedShortName)] : trimmedShortName; return 'Для обеих подгрупп:\n① ② $trimmedFullName'; } return lessonShortNames.containsValue(shortLessonName) ? lessonFullNames[lessonShortNames.keys .firstWhere((k) => lessonShortNames[k] == shortLessonName)] : shortLessonName; } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/schedule/schedule_screen.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:r_dotted_line_border/r_dotted_line_border.dart'; import '../../utils/holiday_helper.dart'; import '../../utils/theme/theme.dart'; import '../../utils/theme_helper.dart'; import '../../widgets/snow_widget.dart'; import '../../widgets/system_bar_cover.dart'; import 'schedule_logic.dart'; import 'schedule_ui.dart'; class ScheduleScreen extends StatelessWidget { const ScheduleScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => ScheduleLogic(), builder: (_, __) => const ScheduleScreenUI(), ); } } class ScheduleScreenUI extends StatefulWidget { const ScheduleScreenUI({Key? key}) : super(key: key); @override State<ScheduleScreenUI> createState() => _ScheduleScreenUIState(); } class _ScheduleScreenUIState extends State<ScheduleScreenUI> { @override void initState() { context.read<ScheduleLogic>().loadSchedule(); context.read<ScheduleLogic>().startTimersUpdating(); FirebaseAnalytics.instance.setCurrentScreen(screenName: 'schedule_screen'); super.initState(); } @override void deactivate() { context.read<ScheduleLogic>().cancelTimersUpdating(); super.deactivate(); } @override Widget build(BuildContext context) { return Consumer<ScheduleLogic>( builder: (context, logic, child) { return Scaffold( extendBodyBehindAppBar: true, appBar: StatusBarCover( height: MediaQuery.of(context).padding.top, ), body: SafeArea( top: false, child: Stack( children: [ if (HolidayHelper.isNewYear) SnowWidget( isRunning: true, totalSnow: 20, speed: 0.4, snowColor: ThemeHelper.isDarkMode ? Colors.white : const Color(0xFFD6D6D6), ), ListView( padding: const EdgeInsets.only( top: 60, left: 30, right: 30, ), children: [ const Text( 'Расписание на', style: TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 18.0, letterSpacing: 0.15, ), ), // SizedBox(height: 6), InkWell( onTap: () => logic.chooseData(context), child: Row( children: [ Expanded( child: FittedBox( alignment: Alignment.centerLeft, fit: BoxFit.scaleDown, child: Text( logic.printCurrentDate, style: const TextStyle( fontFamily: 'Montserrat', fontWeight: FontWeight.w600, fontSize: 36.0, letterSpacing: 0.15, ), ), ), ), const SizedBox(width: 5), const FloatingActionButton( mini: true, onPressed: null, child: Icon(Icons.edit_calendar_outlined), ), ], ), ), const SizedBox(height: 15), logic.fullSchedule == null ? logic.hasError ? ScheduleErrorLoadingUI(errorText: logic.errorText) : Center( child: LinearProgressIndicator( color: context.palette.highEmphasis, backgroundColor: context.palette.backgroundSurface, ), ) : Column( children: [ SchedulePanel(fullSchedule: logic.fullSchedule!), Container( width: double.infinity, decoration: BoxDecoration( border: RDottedLineBorder( // Меняй этой значение, чтобы дэши попали в расстояние нормально dottedLength: 3.5, dottedSpace: 3, left: BorderSide( width: 3, color: context.palette.lowEmphasis, ), ), ), child: Column( children: const [ ChosenGroupBadge(), SizedBox(height: 130), // Отступ после расписания, чтобы FAB не перекрывал контент // Пунктир вместо отступа, чтобы не создавать вид обрыва ], ), ), ], ), ], ), ], ), ), floatingActionButton: const FABPanel(), ); }, ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/schedule/schedule_item_logic.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import '../../utils/hive_helper.dart'; import 'schedule_ui.dart'; class ScheduleItemLogic extends ChangeNotifier { /// Indicates whether widget is opened or closed bool open = false; /// The widget, used in [AdditionalInfo] as child for AnimatedSize Widget infoWidget = const SizedBox( width: double.infinity, ); /// Used for open or close additional info for item in [SchedulePanel] void toggleAdditionalInfo({ required Map<String, dynamic> names, required Map<String, dynamic> lessonFullNames, required String lessonName, }) { open = !open; infoWidget = open ? AdditionalInfoPanelWidget( key: const ValueKey('additional_info'), names: findTeacher( teachers: names, fullLessonName: lessonName, lessonFullNames: lessonFullNames, ), notes: HiveHelper.getValue('note_${unifyKeyMatching(lessonName)}'), lessonName: unifyKeyMatching(lessonName), ) : const SizedBox(key: ValueKey('empty_space'), width: double.infinity); FirebaseAnalytics.instance.logEvent(name: 'schedule_additional_info', parameters: { 'lesson_name': unifyKeyMatching(lessonName), 'teacher': findTeacher( teachers: names, fullLessonName: lessonName, lessonFullNames: lessonFullNames, ), }); notifyListeners(); } /// Used for unify lessons keys for similar names, /// e.x: '[Ш] Иностранный язык' and '[П] Иностранный язык', 'Иностранный язык' /// is the same lesson. String unifyKeyMatching(String name) { // list with all lessons names to find matches List<String> matchList = [ 'Иностранный язык', ]; for (String element in matchList) { if (name.contains(element)) return element; } return name; } /// Finds the name of the teacher for [fullLessonName]. /// /// Full names should be provided in [lessonFullNames]. /// /// Teachers should be provided in [teachers]. /// /// [shortLessonName] is a name of the lesson to replace. /// /// /// /// The order of the items in [lessonFullNames] and [teachers] /// should be the same. static String findTeacher({ required String fullLessonName, required Map<String, dynamic> lessonFullNames, required Map<String, dynamic> teachers, }) { String toReturn = ''; // парсим первую пару из дележек if (fullLessonName.contains('①')) { int start = fullLessonName.indexOf('①') + 1; int? end = fullLessonName.lastIndexOf('②'); if (end == -1) end = null; String lesson = fullLessonName.substring(start, end).trim(); lesson = lessonFullNames.containsValue(lesson) ? teachers[lessonFullNames.keys.firstWhere((k) => lessonFullNames[k] == lesson)] : 'Нет данных о преподавателе'; toReturn = '① $lesson'; } // парсим вторую пару из дележек if (fullLessonName.contains('②')) { int start = fullLessonName.indexOf('②') + 1; String lesson = fullLessonName.substring(start).trim(); lesson = lessonFullNames.containsValue(lesson) ? teachers[lessonFullNames.keys.firstWhere((k) => lessonFullNames[k] == lesson)] : 'Нет данных о преподавателе'; toReturn = '$toReturn\n② $lesson'; } return toReturn.isEmpty ? lessonFullNames.containsValue(fullLessonName) ? teachers[lessonFullNames.keys.firstWhere((k) => lessonFullNames[k] == fullLessonName)] : 'Нет данных о преподавателе' : toReturn.trim(); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/job_quiz/job_quiz_ui.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:share_plus/share_plus.dart'; import '../../utils/theme/theme.dart'; import 'job_quiz_logic.dart'; class QuestionBlock extends StatelessWidget { const QuestionBlock({ Key? key, required this.text, }) : super(key: key); final String text; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(13.0), child: Text( text, style: Theme.of(context).textTheme.headline4, textAlign: TextAlign.center, ), ); } } class AnswersBlock extends StatefulWidget { const AnswersBlock({ Key? key, required this.firstAnswer, required this.secondAnswer, required this.thirdAnswer, required this.fourthAnswer, }) : super(key: key); final String firstAnswer, secondAnswer, thirdAnswer, fourthAnswer; @override State<AnswersBlock> createState() => _AnswersBlockState(); } class _AnswersBlockState extends State<AnswersBlock> { @override Widget build(BuildContext context) { return Column( children: [ AnswerListTile( title: widget.firstAnswer, value: 1, groupValue: context.read<JobQuizStorage>().selectedAnswer, onChanged: (newValue) { setState(() { context.read<JobQuizStorage>().setAnswer(newValue!); }); }, ), AnswerListTile( title: widget.secondAnswer, value: 2, groupValue: context.read<JobQuizStorage>().selectedAnswer, onChanged: (newValue) { setState(() { context.read<JobQuizStorage>().setAnswer(newValue!); }); }, ), AnswerListTile( title: widget.thirdAnswer, value: 3, groupValue: context.read<JobQuizStorage>().selectedAnswer, onChanged: (newValue) { setState(() { context.read<JobQuizStorage>().setAnswer(newValue!); }); }, ), AnswerListTile( title: widget.fourthAnswer, value: 4, groupValue: context.read<JobQuizStorage>().selectedAnswer, onChanged: (newValue) { setState(() { context.read<JobQuizStorage>().setAnswer(newValue!); }); }, ), ], ); } } class JobQuizFAB extends StatelessWidget { const JobQuizFAB({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final bool needShowResult = context.select((JobQuizStorage storage) => storage.showResults); return needShowResult ? Container() : FloatingActionButton.extended( label: const Text('ВЫБРАТЬ'), icon: const Icon(Icons.check_outlined), onPressed: () { if (context.read<JobQuizStorage>().selectedAnswer == 0) { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Выберите вариант ответа'), behavior: SnackBarBehavior.floating, )); } else { context.read<JobQuizStorage>().chooseAnswer(); } }, ); } } class JobQuizResults extends StatefulWidget { const JobQuizResults({Key? key}) : super(key: key); @override State<JobQuizResults> createState() => _JobQuizResultsState(); } class _JobQuizResultsState extends State<JobQuizResults> { @override void initState() { FirebaseAnalytics.instance.logEvent(name: 'job_quiz_completed'); super.initState(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 6.5, vertical: 5.5), child: Card( child: Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Wrap( children: [ ListTile( title: Text( 'Результаты теста', style: Theme.of(context).textTheme.headline4, ), subtitle: Text( context.read<JobQuizStorage>().resultText, style: Theme.of(context).textTheme.headline3, ), ), ButtonBar( children: [ IconButton( tooltip: 'Поделиться результатом', onPressed: () { FirebaseAnalytics.instance.logShare( contentType: 'job_quiz_result', itemId: context.read<JobQuizStorage>().resultText, method: 'system_dialog', ); Share.share( context.read<JobQuizStorage>().resultText, ); }, icon: Icon( Icons.share_outlined, color: context.palette.accentColor, ), ), ], ), ], ), ), ), ); } } class AnswerListTile extends StatelessWidget { final String? title; final int? value, groupValue; final void Function(int?)? onChanged; const AnswerListTile({ Key? key, this.title, this.value, this.groupValue, required this.onChanged, }) : super(key: key); @override Widget build(BuildContext context) { return RadioListTile<int?>( title: Text( title!, style: Theme.of(context).textTheme.bodyText1, ), activeColor: context.palette.accentColor, controlAffinity: ListTileControlAffinity.trailing, value: value, groupValue: groupValue, onChanged: onChanged, ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/job_quiz/job_quiz_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/utils/theme_helper.dart'; import '../../widgets/system_bar_cover.dart'; import 'job_quiz_logic.dart'; import 'job_quiz_ui.dart'; class JobQuizScreen extends StatefulWidget { const JobQuizScreen({Key? key}) : super(key: key); @override State<JobQuizScreen> createState() => _JobQuizScreenState(); } class _JobQuizScreenState extends State<JobQuizScreen> { @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return ChangeNotifierProvider( create: (_) => JobQuizStorage(), child: Scaffold( extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), appBar: AppBar(title: const Text('Проф. направленность')), body: Consumer<JobQuizStorage>( builder: (context, storage, child) { return storage.showResults ? const JobQuizResults() : Column( children: <Widget>[ QuestionBlock(text: storage.questionText), AnswersBlock( firstAnswer: storage.firstAnswer, secondAnswer: storage.secondAnswer, thirdAnswer: storage.thirdAnswer, fourthAnswer: storage.fourthAnswer, ), ], ); }, ), floatingActionButton: const JobQuizFAB(), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/job_quiz/job_quiz_logic.dart
import 'package:flutter/material.dart'; class JobQuizStorage extends ChangeNotifier { int questionNumber = 0; int greenCards = 0; int blueCards = 0; int yellowCards = 0; int purpleCards = 0; int selectedAnswer = 0; bool showResults = false; void setAnswer(int newAnswer) { selectedAnswer = newAnswer; } String get resultText { if (greenCards > blueCards && greenCards > yellowCards && greenCards > purpleCards) { return 'Вам нужно задуматься о профессии, связанной с ' 'компьютерными специальностями!'; } if (blueCards > greenCards && blueCards > yellowCards && blueCards > purpleCards) { return 'Вам нужно задуматься о профессии, связанной с ' 'электрическими сетями, станциями, системами и электроснабжением!'; } if (yellowCards > greenCards && yellowCards > blueCards && yellowCards > purpleCards) { return 'Вам нужно задуматься о профессии, связанной с ' 'гостиничным делом!'; } if (purpleCards > greenCards && purpleCards > blueCards && purpleCards > yellowCards) { return 'Вам нужно задуматься о профессии, связанной с ' 'экономикой, финансами, бухгалтерским учётом!'; } // check for duplicates numbers in variables List<int> list = [greenCards, blueCards, yellowCards, purpleCards]; List duplicates = []; bool haveDuplicates = false; for (var element in list) { if (duplicates.contains(element)) { haveDuplicates = true; } else { duplicates.add(element); } } return haveDuplicates ? 'Похоже, Вы уникальный человек! У Вас есть предрасположенность к ' 'нескольким профессиям:\n' 'Компьютерные специальности: $greenCards\n' 'Электрические специальности: $blueCards\n' 'Гостиничное дело: $yellowCards\n' 'Бух. учёт: $purpleCards' : 'Непредвиденная ошибка в обработке данных ответов\n' '$greenCards, $blueCards, $yellowCards, $purpleCards'; } String get firstAnswer { switch (questionNumber) { case 0: return 'Научные открытия'; case 1: return 'Умение решать задачи, справляться с трудностями'; case 2: return 'Внутренне устройство экспонатов'; case 3: return 'Общаюсь в узком направлении, которое мне интересно'; case 4: return 'В помещении, где много людей'; case 5: return 'Знают больше, чем я'; case 6: return 'Обслуживание техники'; case 7: return 'Подберёте быстрый и комфортный маршрут'; case 8: return 'Работать с техникой'; default: return 'Неизвестный вопрос'; } } String get secondAnswer { switch (questionNumber) { case 0: return 'Развитие производства'; case 1: return 'Ответственность, надёжность'; case 2: return 'Принцип работы экспонатов'; case 3: return 'Охотно общаюсь по интересующей меня и людей теме'; case 4: return 'В необычных условиях'; case 5: return 'Всегда верны и надёжны'; case 6: return 'Ремонт вещей, техники, жилища'; case 7: return 'Подберёте самый безопасный маршрут'; case 8: return 'Ремонтировать различные механизмы'; default: return 'Неизвестный вопрос'; } } String get thirdAnswer { switch (questionNumber) { case 0: return 'Взаимопонимание между людьми'; case 1: return 'Доброту, отзывчивость'; case 2: return 'Внешний вид экспонатов'; case 3: return 'Веду диалоги на разные темы'; case 4: return 'Во многоуровневом помещении, здании'; case 5: return 'Помогают другим, когда для этого предоставляется случай'; case 6: return 'Обустройство территории'; case 7: return 'Найдёте и забронируете место жительства, интересные экскурсии'; case 8: return 'Общаться с самыми разными людьми'; default: return 'Неизвестный вопрос'; } } String get fourthAnswer { switch (questionNumber) { case 0: return 'Стабильная экономика страны'; case 1: return 'Честность, организованность, внимание к деталям'; case 2: return 'Ценность экспонатов'; case 3: return 'Предпочитаю точность в общении'; case 4: return 'В обычном кабинете'; case 5: return 'Всегда и везде следуют правилам'; case 6: return 'Выполнение расчётов'; case 7: return 'Рассчитаете возможности своих финансов'; case 8: return 'Вести документацию, заниматься расчётами'; default: return 'Неизвестный вопрос'; } } void chooseAnswer() { questionNumber++; switch (selectedAnswer) { case 1: greenCards++; notifyListeners(); break; case 2: blueCards++; notifyListeners(); break; case 3: yellowCards++; notifyListeners(); break; case 4: purpleCards++; notifyListeners(); break; } if (questionNumber > 8) { showResults = true; } selectedAnswer = 0; } String get questionText { switch (questionNumber) { case 0: return 'По моему мнению, будущее людей определяет:'; case 1: return 'Больше всего в человеке я ценю: '; case 2: return 'Представьте, что Вы на выставке. ' 'Что Вас больше привлекает в экспонатах?'; case 3: return 'В общении с людьми обычно я: '; case 4: return 'Я предпочту работать: '; case 5: return 'Я рад(а), когда мои друзья: '; case 6: return 'Меня привлекает: '; case 7: return 'Родители подарили Вам путёвку в другую страну. Незамедлительно Вы: '; case 8: return 'Мне хотелось бы в своей профессиональной деятельности: '; case 9: return 'Подведение итогов'; default: return 'Неизвестный номер вопроса'; } } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/cabinets_map/cabinets_map_logic.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/utils/theme_helper.dart'; class CabinetsMapLogic extends ChangeNotifier { int selectedFloor = 1; int scaleFactor = 1; String nowImageUrl = ''; void setNewFloor(int newFloor) { FirebaseAnalytics.instance.logEvent(name: 'cabinets_map_floor_selected', parameters: { 'floor' : newFloor, 'dark_theme': ThemeHelper.isDarkMode, }); _setFloor(newFloor); updateImage(); } void _setFloor(int newFloor) { selectedFloor = newFloor; notifyListeners(); } void setScale(int newScale) { scaleFactor = newScale; notifyListeners(); } Future<void> updateImage() async { nowImageUrl = await getScaledImage(); notifyListeners(); } Future<String> getScaledImage() async { String fieldName = ''; switch (scaleFactor) { case 1: fieldName = 'firstScale'; break; case 2: fieldName = 'secondScale'; break; default: fieldName = 'firstScale'; break; } late String collectionPath; collectionPath = ThemeHelper.isDarkMode ? 'cabinets_map_dark' : 'cabinets_map_light'; DocumentSnapshot cabMap = await FirebaseFirestore.instance .collection(collectionPath) .doc('map_0$selectedFloor') .get(); return cabMap[fieldName].toString(); } Future<void> initializeMap(BuildContext context) async { ThemeNotifier themeNotifier = context.read<ThemeNotifier>(); nowImageUrl = await getScaledImage(); themeNotifier.addListener(() async { await updateImage(); notifyListeners(); }); notifyListeners(); } void scaleListener(double scale) { if (scale < 2.0) { if (scaleFactor != 1) { setScale(1); updateImage(); } } if (scale > 2.0) { if (scaleFactor != 2) { setScale(2); updateImage(); } } } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/cabinets_map/cabinets_map_ui.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/widgets/loading_indicator.dart'; import '../../utils/theme/theme.dart'; import '../../widgets/interactive_widget.dart'; import 'cabinets_map_logic.dart'; @immutable class CabinetsMap extends StatelessWidget { const CabinetsMap({ Key? key, required this.onScaleUpdated, }) : super(key: key); final Function(double) onScaleUpdated; @override Widget build(BuildContext context) { return InteractiveWidget( onInteractionUpdate: onScaleUpdated, child: CachedNetworkImage( imageUrl: context.watch<CabinetsMapLogic>().nowImageUrl, useOldImageOnUrlChange: true, // disable animations between old and new image fadeInDuration: const Duration(seconds: 0), fadeOutDuration: const Duration(seconds: 0), progressIndicatorBuilder: (context, _, __) { return const LoadingIndicator(); }, errorWidget: (context, url, error) => Text( "Ошибка загрузки:\n$error", style: Theme.of(context).textTheme.bodyText1, ), imageBuilder: (context, image) { return Image( image: image, ); }, ), ); } } @immutable class FloorChips extends StatelessWidget { // if make FloorChips const, then change animations won't work // ignore: prefer_const_constructors_in_immutables FloorChips({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return SingleChildScrollView( scrollDirection: Axis.horizontal, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Wrap( direction: Axis.horizontal, spacing: 6.0, children: [ ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('1 этаж'), selected: context.watch<CabinetsMapLogic>().selectedFloor == 1, labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<CabinetsMapLogic>().selectedFloor == 1 ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, onSelected: (_) => context.read<CabinetsMapLogic>().setNewFloor(1), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('2 этаж'), selected: context.watch<CabinetsMapLogic>().selectedFloor == 2, labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<CabinetsMapLogic>().selectedFloor == 2 ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, onSelected: (_) => context.read<CabinetsMapLogic>().setNewFloor(2), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('3 этаж'), selected: context.watch<CabinetsMapLogic>().selectedFloor == 3, labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<CabinetsMapLogic>().selectedFloor == 3 ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, onSelected: (_) => context.read<CabinetsMapLogic>().setNewFloor(3), ), ChoiceChip( backgroundColor: context.palette.levelTwoSurface, label: const Text('4 этаж'), selected: context.watch<CabinetsMapLogic>().selectedFloor == 4, labelStyle: TextStyle( fontSize: 14, fontFamily: 'Montserrat', fontWeight: FontWeight.w600, color: context.watch<CabinetsMapLogic>().selectedFloor == 4 ? context.palette.backgroundSurface : context.palette.highEmphasis, ), selectedColor: context.palette.accentColor, onSelected: (_) => context.read<CabinetsMapLogic>().setNewFloor(4), ), ], ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/cabinets_map/cabinets_map_screen.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/utils/theme_helper.dart'; import '/widgets/loading_indicator.dart'; import '../../utils/holiday_helper.dart'; import '../../widgets/snow_widget.dart'; import '../../widgets/system_bar_cover.dart'; import 'cabinets_map_logic.dart'; import 'cabinets_map_ui.dart'; class CabinetsMapScreen extends StatelessWidget { const CabinetsMapScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => CabinetsMapLogic(), child: const CabinetsMapScreenUI(), ); } } class CabinetsMapScreenUI extends StatefulWidget { const CabinetsMapScreenUI({Key? key}) : super(key: key); @override State<CabinetsMapScreenUI> createState() => _CabinetsMapScreenUIState(); } class _CabinetsMapScreenUIState extends State<CabinetsMapScreenUI> { @override void initState() { super.initState(); context.read<CabinetsMapLogic>().initializeMap(context); FirebaseAnalytics.instance.setCurrentScreen(screenName: 'cabinets_map_screen'); } @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Scaffold( extendBodyBehindAppBar: true, appBar: StatusBarCover( height: MediaQuery.of(context).padding.top, ), body: Stack( children: [ if (HolidayHelper.isNewYear) SnowWidget( isRunning: true, totalSnow: 20, speed: 0.4, snowColor: ThemeHelper.isDarkMode ? Colors.white : const Color(0xFFD6D6D6), ), Consumer<CabinetsMapLogic>( builder: (context, storage, child) { return storage.nowImageUrl.isEmpty ? const LoadingIndicator() : Stack( alignment: Alignment.topCenter, children: [ CabinetsMap( onScaleUpdated: (scale) => storage.scaleListener(scale), ), Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top + 10, ), child: FloorChips(), ), ], ); }, ), ], ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/news/news_ui.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:dart_rss/dart_rss.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:transparent_image/transparent_image.dart'; import '/utils/utils.dart'; import 'news_logic.dart'; @immutable class NewsListView extends StatelessWidget { const NewsListView({ Key? key, required RssFeed? feed, }) : _feed = feed, super(key: key); final RssFeed? _feed; @override Widget build(BuildContext context) { return ListView.builder( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: _feed!.items.length, itemBuilder: (BuildContext context, int index) { final item = _feed!.items[index]; String imgUrl = ''; if (item.description!.contains('src=') && item.description!.contains('alt=')) { imgUrl = item.description!.substring( item.description!.indexOf("src=") + 5, item.description!.indexOf('alt=') - 2, ); } return NewsItemCard(item: item, imgUrl: imgUrl); }, ); } } @immutable class NewsItemCard extends StatelessWidget { const NewsItemCard({ Key? key, required this.item, required this.imgUrl, }) : super(key: key); final RssItem item; final String imgUrl; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Card( child: InkWell( onTap: () => openUrl(item.link!), child: Column( children: <Widget>[ AnimatedSize( curve: Curves.fastOutSlowIn, duration: const Duration(milliseconds: 400), child: Container( margin: const EdgeInsets.all(1.0), clipBehavior: Clip.antiAlias, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), ), child: CachedNetworkImage( imageUrl: imgUrl, fit: BoxFit.fill, placeholder: (context, url) => SizedBox( height: 200, width: MediaQuery.of(context).size.width, child: Image.memory(kTransparentImage), ), errorWidget: (context, url, error) => Container(), ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 13), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( item.title!, style: Theme.of(context).textTheme.headline3, ), Padding( padding: const EdgeInsets.only(top: 6), child: Row( children: <Widget>[ const Spacer(), Text( DateFormat('d MMMM yyyy, HH:mm').format( NewsLogic.parseRfc822DateTime(item.pubDate!)!, ), style: Theme.of(context).textTheme.subtitle1, ), ], ), ), ], ), ), ], ), ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/news/news_screen.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/widgets/loading_indicator.dart'; import '../../widgets/system_bar_cover.dart'; import 'news_logic.dart'; import 'news_ui.dart'; @immutable class NewsScreenProvider extends StatelessWidget { const NewsScreenProvider({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => NewsLogic(), child: const NewsScreen(), ); } } @immutable class NewsScreen extends StatefulWidget { const NewsScreen({Key? key}) : super(key: key); @override State<NewsScreen> createState() => _NewsScreenState(); } class _NewsScreenState extends State<NewsScreen> { @override void initState() { loadFeed(); FirebaseAnalytics.instance.setCurrentScreen(screenName: 'news_screen'); super.initState(); } Future<void> loadFeed() async { await context.read<NewsLogic>().loadFeed(); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, appBar: StatusBarCover( height: MediaQuery.of(context).padding.top, ), body: Consumer<NewsLogic>( builder: (context, state, child) { if (state.rssFeed == null) return const LoadingIndicator(); return SafeArea( top: false, child: SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: NewsListView(feed: state.rssFeed), ), ); }, ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/news/news_logic.dart
import 'package:dart_rss/dart_rss.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:intl/intl.dart'; class NewsLogic extends ChangeNotifier { static const String feedUrl = 'https://energocollege.ru/rss.xml'; RssFeed? rssFeed; bool get isFeedNotEmpty { return rssFeed != null; } void updateFeed(feed) { rssFeed = feed; notifyListeners(); } Future<RssFeed?> loadFeed() async { try { final client = http.Client(); final response = await client .get(Uri.parse(feedUrl)) .timeout(const Duration(seconds: 70)); updateFeed(RssFeed.parse(response.body)); return RssFeed.parse(response.body); } catch (e) { return null; } } // this rss feed use rfc822 date format, so this is a parser for this format static DateTime? parseRfc822DateTime(String dateString) { const rfc822DatePattern = 'EEE, dd MMM yyyy HH:mm:ss Z'; try { final num length = dateString.length.clamp(0, rfc822DatePattern.length); final trimmedPattern = rfc822DatePattern.substring(0, length as int); final format = DateFormat(trimmedPattern, 'en_US'); return format.parse(dateString); } on FormatException { return null; } } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/login/login_ui.dart
import 'package:flutter/material.dart'; import '../../widgets/loading_indicator.dart'; import 'login_logic.dart'; class EntrantButton extends StatefulWidget { const EntrantButton({Key? key}) : super(key: key); @override State<EntrantButton> createState() => _EntrantButtonState(); } class _EntrantButtonState extends State<EntrantButton> { // used to display the download state bool _isLoading = false; @override Widget build(BuildContext context) { return OutlinedButton( child: _isLoading ? const SizedBox( height: 20, width: 20, child: LoadingIndicator( delayedAppears: false, ), ) : const Text( 'Я абитуриент', style: TextStyle(fontSize: 16), ), onPressed: () async { if (_isLoading) { // do nothing if already loading return; } _isLoading = true; (context as Element).markNeedsBuild(); await LoginLogic.openEntrantScreen(context); _isLoading = false; context.markNeedsBuild(); }, ); } } class CameraPermissionRequestUI extends StatelessWidget { const CameraPermissionRequestUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Text( 'Для сканирования QR кода входа необходим доступ к камере. ' 'Вы можете предоставить доступ, или ввести логин и пароль вручную:', style: Theme.of(context).textTheme.headline3, ), const SizedBox(height: 10), Column( children: [ SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () => LoginLogic.requestPermissionForScanner(context), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon(Icons.camera_alt_outlined), SizedBox(width: 8), Text( 'Предоставить доступ', style: TextStyle(fontSize: 16), ), ], ), ), ), const SizedBox(height: 10), SizedBox( width: double.infinity, child: OutlinedButton( onPressed: () => LoginLogic.openLogin(context), child: const Text('Ввести данные вручную'), ), ), ], ), ], ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/login/login_logic.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; import '/screens/settings/settings_logic.dart'; import '/utils/hive_helper.dart'; import '../../models/document_model.dart'; import '../../utils/firebase_auth.dart'; import '../../utils/theme/theme.dart'; import '../../utils/theme_helper.dart'; import '../../utils/utils.dart'; import 'login_ui.dart'; class LoginLogic extends ChangeNotifier { static Future<void> openLogin(BuildContext context) async { FirebaseAnalytics.instance.logEvent(name: 'login_manual'); await SettingsLogic.accountLogin(context); if (context.read<FirebaseAppAuth>().accountInfo.level != AccountType.entrant) { continueToApp(context); } } static Future<void> openQrScanner(BuildContext context) async { FirebaseAnalytics.instance.logEvent(name: 'login_qr_dialog'); if (await Permission.camera.isGranted) { Navigator.pushNamed(context, '/loginByScan'); } else { showRoundedModalSheet( context: context, title: 'Вход с помощью QR кода', child: const CameraPermissionRequestUI(), ); } } static Future<void> requestPermissionForScanner(BuildContext context) async { PermissionStatus requestResult = await Permission.camera.request(); if (requestResult == PermissionStatus.granted) { Navigator.pushNamed(context, '/loginByScan'); } else if (requestResult == PermissionStatus.permanentlyDenied) { openAppSettings(); } } static void continueToApp(BuildContext context) { Navigator.popAndPushNamed(context, '/'); HiveHelper.saveValue(key: 'isUserEntrant', value: false); } static Future<void> showAccountHelperDialog(BuildContext context) async { FirebaseAnalytics.instance.logEvent(name: 'login_helper_dialog'); String dialogText = 'Данные для входа предоставляются в колледже. ' 'Для быстрого входа в аккаунт можно просканировать QR код с плаката'; ThemeHelper.colorSystemChrome(mode: ColoringMode.lightIcons); await showDialog( context: context, builder: (context) { return AnnotatedRegion<SystemUiOverlayStyle>( value: ThemeHelper.overlayStyleHelper( Color.alphaBlend(Colors.black54, context.palette.backgroundSurface), ), child: AlertDialog( content: Text(dialogText), actions: [ TextButton( child: const Text('Закрыть'), onPressed: () => Navigator.pop(context), ), ], ), ); }, ); ThemeHelper.colorSystemChrome(); } /// Return URL for document, which need to display for entrant static Future<String> getEntrantUrl() async { final DocumentSnapshot entrant = await FirebaseFirestore.instance .collection('entrant') .doc('main') .get(); return entrant['url']; } static Future<void> openEntrantScreen(final BuildContext context) async { final String docURL = await getEntrantUrl(); Navigator.pushNamed( context, '/view_document', arguments: DocumentModel( title: 'Для абитуриента', subtitle: '', url: docURL, ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/login/login_screen.dart
import 'package:flutter/material.dart'; import 'package:permission_handler/permission_handler.dart'; import '/utils/theme_helper.dart'; import '../../utils/theme/theme.dart'; import '../../widgets/system_bar_cover.dart'; import 'login_logic.dart'; import 'login_ui.dart'; class LoginScreen extends StatelessWidget { const LoginScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); List<Widget> children = [ Expanded( flex: 4, child: Image( width: 0.75 * MediaQuery.of(context).size.shortestSide, height: 0.75 * MediaQuery.of(context).size.shortestSide, image: AssetImage( ThemeHelper.isDarkMode ? 'assets/splash/dark.png' : 'assets/splash/light.png', ), ), ), const SizedBox(width: 20, height: 20), Expanded( flex: 3, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Добро пожаловать', style: Theme.of(context) .textTheme .headline5! .copyWith(fontSize: 24.0), ), Padding( padding: const EdgeInsets.only(top: 10, bottom: 25), child: Text( 'Чтобы продолжить, выберите один из вариантов', style: Theme.of(context).textTheme.subtitle1!, textAlign: TextAlign.end, ), ), Wrap( alignment: WrapAlignment.end, runSpacing: 10, children: [ SizedBox( height: 54.0, width: double.infinity, child: ElevatedButton( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon(Icons.qr_code, size: 28), SizedBox(width: 8), Text( 'Войти в аккаунт', style: TextStyle(fontSize: 16), ), ], ), onPressed: () => LoginLogic.openQrScanner(context), ), ), const SizedBox( height: 46.0, width: double.infinity, child: EntrantButton(), ), GestureDetector( onTap: () => LoginLogic.showAccountHelperDialog(context), child: Padding( padding: const EdgeInsets.all(8.0), child: Text( 'Где найти данные для входа?', style: Theme.of(context).textTheme.subtitle1!.copyWith( decoration: TextDecoration.underline, ), textAlign: TextAlign.end, ), ), ), ], ), Expanded( child: Align( alignment: Alignment.bottomRight, child: IconButton( icon: Icon( Icons.settings_outlined, color: context.palette.lowEmphasis, ), tooltip: 'Открыть системные настройки', onPressed: () => openAppSettings(), ), ), ), ], ), ), ]; return Scaffold( extendBodyBehindAppBar: true, appBar: StatusBarCover( height: MediaQuery.of(context).padding.top, ), extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), body: SafeArea( minimum: const EdgeInsets.all(12.0), child: MediaQuery.of(context).size.aspectRatio > 1 ? Row(children: children) : Column(children: children), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/admins/admins_ui.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_linkify/flutter_linkify.dart'; import '/models/admin_model.dart'; import '/utils/utils.dart'; class AdminCard extends StatelessWidget { final AdminModel admin; const AdminCard({Key? key, required this.admin}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Card( child: Padding( padding: const EdgeInsets.all(14.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(bottom: 5.0), child: Text( admin.name!, style: Theme.of(context).textTheme.headline4, ), ), Padding( padding: const EdgeInsets.only(bottom: 2.0), child: Text( admin.post!, style: Theme.of(context).textTheme.bodyText1, ), ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: SelectableLinkify( text: admin.contact!, style: Theme.of(context).textTheme.subtitle1, onOpen: (value) { FirebaseAnalytics.instance.logEvent(name: 'administrator_link_opened', parameters: { 'url': value.url, }); openUrl(value.url); }, ), ), if (admin.cabinet != '') Text( "Кабинет ${admin.cabinet}", style: Theme.of(context).textTheme.subtitle1, ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/admins/admins_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import '/models/admin_model.dart'; import '/utils/theme_helper.dart'; import '/widgets/loading_indicator.dart'; import '../../widgets/system_bar_cover.dart'; import 'admins_ui.dart'; class AdminScreen extends StatelessWidget { AdminScreen({Key? key}) : super(key: key); final Stream<QuerySnapshot<Map<String, dynamic>>> stream = FirebaseFirestore.instance.collection('administration_list').snapshots(); @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Scaffold( extendBody: true, bottomNavigationBar: SystemNavBarCover( height: MediaQuery.of(context).padding.bottom, ), appBar: AppBar(title: const Text('Администрация')), body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( stream: stream, builder: ( BuildContext context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot, ) { if (!snapshot.hasData) return const LoadingIndicator(); return SingleChildScrollView( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: ListView( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, scrollDirection: Axis.vertical, children: snapshot.data!.docs.map((document) { return AdminCard( admin: AdminModel.fromMap(document.data(), document.id), ); }).toList(), ), ); }, ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/bottom_bar/bottom_bar_logic.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; class BottomBarLogic extends ChangeNotifier { int bottomBarIndex = 0; void setIndex(int value) { FirebaseAnalytics.instance.logEvent(name: 'bottom_navigation_item_selected', parameters: { 'index': value, }); bottomBarIndex = value; notifyListeners(); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/bottom_bar/bottom_bar_screen.dart
import 'package:breakpoint/breakpoint.dart'; import 'package:flutter/material.dart'; import 'bottom_bar_ui.dart'; class BottomBarScreen extends StatefulWidget { const BottomBarScreen({Key? key}) : super(key: key); @override State<BottomBarScreen> createState() => _BottomBarScreenState(); } class _BottomBarScreenState extends State<BottomBarScreen> { @override Widget build(BuildContext context) { return BreakpointBuilder(builder: (context, breakpoint) { return breakpoint.window < WindowSize.small ? const Scaffold( body: PageStorageUI(), bottomNavigationBar: BottomBarUI(), ) : const Scaffold(body: BuildTabletUI()); }); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/bottom_bar/bottom_bar_ui.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import '/utils/icons.dart'; import '../../utils/theme/theme.dart'; import '../../utils/theme_helper.dart'; import '../announcements/announcements_screen.dart'; import '../cabinets_map/cabinets_map_screen.dart'; import '../menu/menu_screen.dart'; import '../news/news_screen.dart'; import '../schedule/schedule_screen.dart'; import 'bottom_bar_logic.dart'; class PageStorageUI extends StatelessWidget { const PageStorageUI({ Key? key, }) : super(key: key); // List of screens for navigation static List<Widget> pages = const [ NewsScreenProvider(), AnnouncementsScreen(), ScheduleScreen(), CabinetsMapScreen(), MenuScreen(), ]; @override Widget build(BuildContext context) { return Consumer<BottomBarLogic>( builder: (context, storage, child) => PageStorage( bucket: PageStorageBucket(), child: pages[storage.bottomBarIndex], ), ); } } class BottomBarUI extends StatelessWidget { const BottomBarUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<BottomBarLogic>( builder: (context, storage, child) => AnnotatedRegion<SystemUiOverlayStyle>( value: ThemeHelper.overlayStyleHelper(context.palette.levelTwoSurface), child: DecoratedBox( decoration: BoxDecoration( color: context.palette.levelTwoSurface, border: Border( top: BorderSide( color: context.palette.outsideBorderColor, width: 1.0, ), ), ), child: NavigationBar( selectedIndex: storage.bottomBarIndex, onDestinationSelected: (index) { storage.setIndex(index); }, destinations: const [ NavigationDestination( icon: Icon(VpecIconPack.news_outline), selectedIcon: Icon(VpecIconPack.news), label: 'События', ), NavigationDestination( icon: Icon(Icons.notifications_outlined), selectedIcon: Icon(Icons.notifications), label: 'Объявления', ), NavigationDestination( icon: Icon(Icons.schedule_outlined), selectedIcon: Icon(Icons.watch_later), label: 'Расписание', ), NavigationDestination( icon: Icon(Icons.layers_outlined), selectedIcon: Icon(Icons.layers), label: 'Карта', ), NavigationDestination( icon: Icon(Icons.menu_outlined), selectedIcon: Icon(Icons.menu), label: 'Меню', ), ], ), ), ), ); } } class BuildTabletUI extends StatelessWidget { const BuildTabletUI({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<BottomBarLogic>( child: const Expanded( child: PageStorageUI(), ), builder: (context, storage, child) => Row( children: [ NavigationRail( groupAlignment: -0.9, selectedIndex: storage.bottomBarIndex, labelType: NavigationRailLabelType.none, onDestinationSelected: (value) => storage.setIndex(value), destinations: const [ NavigationRailDestination( icon: Icon(VpecIconPack.news_outline), selectedIcon: Icon(VpecIconPack.news), label: Text('События'), ), NavigationRailDestination( icon: Icon(Icons.notifications_outlined), selectedIcon: Icon(Icons.notifications), label: Text('Объявления'), ), NavigationRailDestination( icon: Icon(Icons.schedule_outlined), selectedIcon: Icon(Icons.watch_later), label: Text('Звонки'), ), NavigationRailDestination( icon: Icon(Icons.dashboard_outlined), selectedIcon: Icon(Icons.dashboard), label: Text('Расписание'), ), NavigationRailDestination( icon: Icon(Icons.menu_outlined), selectedIcon: Icon(Icons.menu), label: Text('Меню'), ), ], ), child!, ], ), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/lessons_schedule/lessons_schedule_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/utils/holiday_helper.dart'; import '/utils/theme_helper.dart'; import '/widgets/snow_widget.dart'; import 'lessons_schedule_logic.dart'; import 'lessons_schedule_ui.dart'; class FullLessonsScheduleScreen extends StatelessWidget { const FullLessonsScheduleScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (_) => LessonsScheduleLogic(), builder: (_, __) => const LessonsScheduleScreen(), ); } } class LessonsScheduleScreen extends StatefulWidget { const LessonsScheduleScreen({Key? key}) : super(key: key); @override State<LessonsScheduleScreen> createState() => _LessonsScheduleScreenState(); } class _LessonsScheduleScreenState extends State<LessonsScheduleScreen> with TickerProviderStateMixin { @override void initState() { context.read<LessonsScheduleLogic>().onInitState(this); super.initState(); } @override void deactivate() { context.read<LessonsScheduleLogic>().onDispose(); super.deactivate(); } @override Widget build(BuildContext context) { ThemeHelper.colorSystemChrome(); return Scaffold( appBar: AppBar( title: const Text('Полное расписание занятий'), ), body: Stack( children: [ if (HolidayHelper.isNewYear) SnowWidget( isRunning: true, totalSnow: 20, speed: 0.4, snowColor: ThemeHelper.isDarkMode ? Colors.white : const Color(0xFFD6D6D6), ), const LessonsScheduleViewer(), ], ), floatingActionButton: const FabMenu(), ); } }
0
mirrored_repositories/vpec/lib/screens
mirrored_repositories/vpec/lib/screens/lessons_schedule/lessons_schedule_ui.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '/utils/theme_helper.dart'; import '/utils/utils.dart'; import '/widgets/loading_indicator.dart'; import '../../widgets/interactive_widget.dart'; import 'lessons_schedule_logic.dart'; class LessonsScheduleViewer extends StatelessWidget { const LessonsScheduleViewer({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<LessonsScheduleLogic>( builder: (context, storage, child) => CachedNetworkImage( imageUrl: storage.imgUrl, placeholder: (context, url) => const LoadingIndicator(), errorWidget: (context, url, error) => Center( child: Padding( padding: const EdgeInsets.only(bottom: 24.0), child: Text( 'Расписание на\n${storage.parseDateFromUrl}\nне найдено', textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline3, ), ), ), imageBuilder: (context, imageProvider) { return InteractiveWidget( child: ColorFiltered( colorFilter: ThemeHelper.isDarkMode ? const ColorFilter.matrix([ //R G B A Const -0.87843, 0, 0, 0, 255, 0, -0.87843, 0, 0, 255, 0, 0, -0.87843, 0, 255, 0, 0, 0, 1, 0, ]) : const ColorFilter.matrix([ //R G B A Const 0.96078, 0, 0, 0, 0, 0, 0.96078, 0, 0, 0, 0, 0, 0.96078, 0, 0, 0, 0, 0, 1, 0, ]), child: Center( child: Image( image: imageProvider, ), ), ), ); }, ), ); } } class FabMenu extends StatelessWidget { const FabMenu({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ if (!kIsWeb) FloatingActionButton( heroTag: null, mini: true, child: const Icon(Icons.share_outlined), onPressed: () => shareFile(context.read<LessonsScheduleLogic>().imgUrl), ), Padding( padding: const EdgeInsets.only(bottom: 4), child: FloatingActionButton( heroTag: null, mini: true, child: const Icon(Icons.today_outlined), onPressed: () => context.read<LessonsScheduleLogic>().chooseDate(context), ), ), FloatingActionButton( heroTag: null, child: Icon( context.watch<LessonsScheduleLogic>().showForToday ? Icons.arrow_forward_ios_rounded : Icons.arrow_back_ios_rounded, size: 24, ), onPressed: () { LessonsScheduleLogic logic = context.read<LessonsScheduleLogic>(); // this FAB used for switch between schedule for today or tomorrow logic.showForToday = !logic.showForToday; logic.updateImgUrl(); FirebaseAnalytics.instance.logEvent(name: 'full_schedule_today_fab', parameters: { 'today': logic.showForToday, }); }, ), ], ); } }
0