repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/catcher_two_options.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // ignore_for_file: avoid_redundant_argument_values import 'package:catcher_2/catcher_2.dart'; import 'package:catcher_two_demo/src/custom_catcher_two_logger.dart'; final debugOptions = Catcher2Options( PageReportMode(), [ EmailManualHandler(['[email protected]']), ConsoleHandler(), ], localizationOptions: [ LocalizationOptions( 'en', pageReportModeTitle: 'Exception Report', pageReportModeDescription: 'Page report mode.', pageReportModeAccept: 'Accept', pageReportModeCancel: 'Cancel', ), LocalizationOptions( 'de', pageReportModeTitle: 'Ausnahmebericht', pageReportModeDescription: 'Seitenberichtsmodus', pageReportModeAccept: 'Akzeptieren', pageReportModeCancel: 'Stornieren', ), ], logger: CustomCatcherTwoLogger(), ); final releaseOptions = Catcher2Options( PageReportMode(), [ EmailManualHandler(['[email protected]']), ], localizationOptions: [ LocalizationOptions( 'en', pageReportModeTitle: 'Exception Report', pageReportModeDescription: 'Page report mode.', pageReportModeAccept: 'Accept', pageReportModeCancel: 'Cancel', ), LocalizationOptions( 'de', pageReportModeTitle: 'Ausnahmebericht', pageReportModeDescription: 'Seitenberichtsmodus', pageReportModeAccept: 'Akzeptieren', pageReportModeCancel: 'Stornieren', ), ], logger: CustomCatcherTwoLogger(), );
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/settings/settings_controller.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:catcher_two_demo/src/settings/settings_service.dart'; import 'package:flutter/material.dart'; /// A class that many Widgets can interact with to read user settings, update /// user settings, or listen to user settings changes. /// /// Controllers glue Data Services to Flutter Widgets. The SettingsController /// uses the SettingsService to store and retrieve user settings. class SettingsController with ChangeNotifier { SettingsController(this._settingsService); // Make SettingsService a private variable so it is not used directly. final SettingsService _settingsService; // Make ThemeMode a private variable so it is not updated directly without // also persisting the changes with the SettingsService. late ThemeMode _themeMode; // Allow Widgets to read the user's preferred ThemeMode. ThemeMode get themeMode => _themeMode; /// Load the user's settings from the SettingsService. It may load from a /// local database or the internet. The controller only knows it can load the /// settings from the service. Future<void> loadSettings() async { _themeMode = await _settingsService.themeMode(); // Important! Inform listeners a change has occurred. notifyListeners(); } /// Update and persist the ThemeMode based on the user's selection. Future<void> updateThemeMode(ThemeMode? newThemeMode) async { if (newThemeMode == null) return; // Do not perform any work if new and old ThemeMode are identical if (newThemeMode == _themeMode) return; // Otherwise, store the new ThemeMode in memory _themeMode = newThemeMode; // Important! Inform listeners a change has occurred. notifyListeners(); // Persist the changes to a local database or the internet using the // SettingService. await _settingsService.updateThemeMode(newThemeMode); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/settings/settings_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:catcher_two_demo/src/localization/l10n.dart'; import 'package:catcher_two_demo/src/settings/settings_controller.dart'; import 'package:flutter/material.dart'; /// Displays the various settings that can be customized by the user. /// /// When a user changes a setting, the SettingsController is updated and /// Widgets that listen to the SettingsController are rebuilt. class SettingsView extends StatelessWidget { const SettingsView({super.key, required this.controller,}); static const routeName = '/settings'; final SettingsController controller; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(CustomAppLocalizations.of(context).settingsViewTitle), ), body: Padding( padding: const EdgeInsets.all(16), // Glue the SettingsController to the theme selection DropdownButton. // // When a user selects a theme from the dropdown list, the // SettingsController is updated, which rebuilds the MaterialApp. child: DropdownButton<ThemeMode>(items: [ DropdownMenuItem(value: ThemeMode.system, child: Text(CustomAppLocalizations.of(context).settingsSystemTheme),), DropdownMenuItem(value: ThemeMode.light, child: Text(CustomAppLocalizations.of(context).settingsLightTheme),), DropdownMenuItem(value: ThemeMode.dark, child: Text(CustomAppLocalizations.of(context).settingsDarkTheme),), ], value: controller.themeMode, onChanged: controller.updateThemeMode, ), ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/settings/settings_service.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; /// A service that stores and retrieves user settings. /// /// By default, this class does not persist user settings. If you'd like to /// persist the user settings locally, use the shared_preferences package. If /// you'd like to store settings on a web server, use the http package. class SettingsService { /// Loads the User's preferred ThemeMode from local or remote storage. Future<ThemeMode> themeMode() async => ThemeMode.system; /// Persists the user's preferred ThemeMode to local or remote storage. Future<void> updateThemeMode(ThemeMode theme) async { // Use the shared_preferences package to persist settings locally or the // http package to persist settings over the network. } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/sample_feature/sample_item_details_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:catcher_two_demo/src/localization/l10n.dart'; import 'package:flutter/material.dart'; /// Displays detailed information about a SampleItem. class SampleItemDetailsView extends StatelessWidget { const SampleItemDetailsView({super.key}); static const routeName = '/sample_item'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(CustomAppLocalizations.of(context).sampleItemDetailsViewTitle), ), body: Center( child: Text(CustomAppLocalizations.of(context).sampleItemDetailsViewDetail), ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/sample_feature/sample_item.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /// A placeholder class that represents an entity or model. class SampleItem { const SampleItem(this.id); final int id; }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/sample_feature/sample_item_list_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:catcher_two_demo/src/localization/l10n.dart'; import 'package:catcher_two_demo/src/sample_feature/sample_item.dart'; import 'package:catcher_two_demo/src/sample_feature/sample_item_details_view.dart'; import 'package:catcher_two_demo/src/settings/settings_view.dart'; import 'package:flutter/material.dart'; /// Displays a list of SampleItems. class SampleItemListView extends StatelessWidget { const SampleItemListView({ super.key, this.items = const [SampleItem(1), SampleItem(2), SampleItem(3),], }); static const routeName = '/'; final List<SampleItem> items; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(CustomAppLocalizations.of(context).sampleItemListViewTitle), actions: [ IconButton( onPressed: () {Navigator.restorablePushNamed(context, SettingsView.routeName,);}, icon: const Icon(Icons.settings), ), ], ), // To work with lists that may contain a large number of items, it’s best // to use the ListView.builder constructor. // // In contrast to the default ListView constructor, which requires // building all Widgets up front, the ListView.builder constructor lazily // builds Widgets as they’re scrolled into view. body: ListView.builder( itemBuilder: (BuildContext context, int index,) {final item = items[index]; return ListTile( leading: const CircleAvatar(foregroundImage: AssetImage('assets/images/flutter_logo.png')), title: Text(CustomAppLocalizations.of(context).listTileTitle(item.id)), onTap: () {Navigator.restorablePushNamed(context, SampleItemDetailsView.routeName,);},);}, itemCount: items.length, restorationId: 'sampleItemListView', ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization/l10n.dart
// GENERATED CODE - DO NOT MODIFY BY HAND import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'intl/messages_all.dart'; // ************************************************************************** // Generator: Flutter Intl IDE plugin // Made by Localizely // ************************************************************************** // ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars // ignore_for_file: join_return_with_assignment, prefer_final_in_for_each // ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes class CustomAppLocalizations { CustomAppLocalizations(); static CustomAppLocalizations? _current; static CustomAppLocalizations get current { assert(_current != null, 'No instance of CustomAppLocalizations was loaded. Try to initialize the CustomAppLocalizations delegate before accessing CustomAppLocalizations.current.'); return _current!; } static const AppLocalizationDelegate delegate = AppLocalizationDelegate(); static Future<CustomAppLocalizations> load(Locale locale) { final name = (locale.countryCode?.isEmpty ?? false) ? locale.languageCode : locale.toString(); final localeName = Intl.canonicalizedLocale(name); return initializeMessages(localeName).then((_) { Intl.defaultLocale = localeName; final instance = CustomAppLocalizations(); CustomAppLocalizations._current = instance; return instance; }); } static CustomAppLocalizations of(BuildContext context) { final instance = CustomAppLocalizations.maybeOf(context); assert(instance != null, 'No instance of CustomAppLocalizations present in the widget tree. Did you add CustomAppLocalizations.delegate in localizationsDelegates?'); return instance!; } static CustomAppLocalizations? maybeOf(BuildContext context) { return Localizations.of<CustomAppLocalizations>( context, CustomAppLocalizations); } /// `App` String get title { return Intl.message( 'App', name: 'title', desc: 'Title for the App', args: [], ); } /// `SampleItem {value}` String listTileTitle(int value) { return Intl.message( 'SampleItem $value', name: 'listTileTitle', desc: 'ListTile title', args: [value], ); } /// `Sample Items` String get sampleItemListViewTitle { return Intl.message( 'Sample Items', name: 'sampleItemListViewTitle', desc: 'Sample Item List View Title', args: [], ); } /// `Item Details` String get sampleItemDetailsViewTitle { return Intl.message( 'Item Details', name: 'sampleItemDetailsViewTitle', desc: 'Sample Item Detials view Title', args: [], ); } /// `Settings` String get settingsViewTitle { return Intl.message( 'Settings', name: 'settingsViewTitle', desc: 'Settings View Title', args: [], ); } /// `System Theme` String get settingsSystemTheme { return Intl.message( 'System Theme', name: 'settingsSystemTheme', desc: 'Settings System Theme', args: [], ); } /// `Light Theme` String get settingsLightTheme { return Intl.message( 'Light Theme', name: 'settingsLightTheme', desc: 'Settings Light Theme', args: [], ); } /// `Dark Theme` String get settingsDarkTheme { return Intl.message( 'Dark Theme', name: 'settingsDarkTheme', desc: 'Settings Dark Theme', args: [], ); } /// `More Information Here` String get sampleItemDetailsViewDetail { return Intl.message( 'More Information Here', name: 'sampleItemDetailsViewDetail', desc: 'Sample Item Detials View Detail', args: [], ); } } class AppLocalizationDelegate extends LocalizationsDelegate<CustomAppLocalizations> { const AppLocalizationDelegate(); List<Locale> get supportedLocales { return const <Locale>[ Locale.fromSubtags(languageCode: 'en'), Locale.fromSubtags(languageCode: 'de'), ]; } @override bool isSupported(Locale locale) => _isSupported(locale); @override Future<CustomAppLocalizations> load(Locale locale) => CustomAppLocalizations.load(locale); @override bool shouldReload(AppLocalizationDelegate old) => false; bool _isSupported(Locale locale) { for (var supportedLocale in supportedLocales) { if (supportedLocale.languageCode == locale.languageCode) { return true; } } return false; } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization/intl/messages_en.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a en locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'en'; static String m0(value) => "SampleItem ${value}"; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{ "listTileTitle": m0, "sampleItemDetailsViewDetail": MessageLookupByLibrary.simpleMessage("More Information Here"), "sampleItemDetailsViewTitle": MessageLookupByLibrary.simpleMessage("Item Details"), "sampleItemListViewTitle": MessageLookupByLibrary.simpleMessage("Sample Items"), "settingsDarkTheme": MessageLookupByLibrary.simpleMessage("Dark Theme"), "settingsLightTheme": MessageLookupByLibrary.simpleMessage("Light Theme"), "settingsSystemTheme": MessageLookupByLibrary.simpleMessage("System Theme"), "settingsViewTitle": MessageLookupByLibrary.simpleMessage("Settings"), "title": MessageLookupByLibrary.simpleMessage("App") }; }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization/intl/messages_de.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a de locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'de'; static String m0(value) => "Musterartikel ${value}"; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{ "listTileTitle": m0, "sampleItemDetailsViewDetail": MessageLookupByLibrary.simpleMessage("Weitere Informationen Hier"), "sampleItemDetailsViewTitle": MessageLookupByLibrary.simpleMessage("Artikeldetails"), "sampleItemListViewTitle": MessageLookupByLibrary.simpleMessage("Beispielartikel"), "settingsDarkTheme": MessageLookupByLibrary.simpleMessage("Dunkles Thema"), "settingsLightTheme": MessageLookupByLibrary.simpleMessage("Licht Thema"), "settingsSystemTheme": MessageLookupByLibrary.simpleMessage("System Thema"), "settingsViewTitle": MessageLookupByLibrary.simpleMessage("Einstellungen"), "title": MessageLookupByLibrary.simpleMessage("App") }; }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/lib/src/localization/intl/messages_all.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that looks up messages for specific locales by // delegating to the appropriate library. // Ignore issues from commonly used lints in this file. // ignore_for_file:implementation_imports, file_names, unnecessary_new // ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering // ignore_for_file:argument_type_not_assignable, invalid_assignment // ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases // ignore_for_file:comment_references import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; import 'package:intl/src/intl_helpers.dart'; import 'messages_de.dart' as messages_de; import 'messages_en.dart' as messages_en; typedef Future<dynamic> LibraryLoader(); Map<String, LibraryLoader> _deferredLibraries = { 'de': () => new SynchronousFuture(null), 'en': () => new SynchronousFuture(null), }; MessageLookupByLibrary? _findExact(String localeName) { switch (localeName) { case 'de': return messages_de.messages; case 'en': return messages_en.messages; default: return null; } } /// User programs should call this before using [localeName] for messages. Future<bool> initializeMessages(String localeName) { var availableLocale = Intl.verifiedLocale( localeName, (locale) => _deferredLibraries[locale] != null, onFailure: (_) => null); if (availableLocale == null) { return new SynchronousFuture(false); } var lib = _deferredLibraries[availableLocale]; lib == null ? new SynchronousFuture(false) : lib(); initializeInternalMessageLookup(() => new CompositeMessageLookup()); messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor); return new SynchronousFuture(true); } bool _messagesExistFor(String locale) { try { return _findExact(locale) != null; } catch (e) { return false; } } MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) { var actualLocale = Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null); if (actualLocale == null) return null; return _findExact(actualLocale); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/test/unit_test.dart
// This is an example unit test. // // A unit test tests a single function, method, or class. To learn more about // writing unit tests, visit // https://flutter.dev/docs/cookbook/testing/unit/introduction import 'package:flutter_test/flutter_test.dart'; void main() { group('Plus Operator', () { test('should add two numbers together', () { expect(1 + 1, 2,); },); },); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/catcher_two_demo/test/widget_test.dart
// This is an example 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. // // Visit https://flutter.dev/docs/cookbook/testing/widget/introduction for // more information about Widget testing. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('MyWidget', () { testWidgets('should display a string of text', (WidgetTester tester) async { // Define a Widget const myWidget = MaterialApp( home: Scaffold( body: Text('Hello'), ), ); // Build myWidget and trigger a frame. await tester.pumpWidget(myWidget); // Verify myWidget shows some text expect(find.byType(Text), findsOneWidget,); },); },); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/main.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'src/app.dart'; import 'src/settings/settings_controller.dart'; import 'src/settings/settings_service.dart'; void main() async { // Set up the SettingsController, which will glue user settings to multiple // Flutter Widgets. final settingsController = SettingsController(SettingsService()); // Load the user's preferred theme while the splash screen is displayed. // This prevents a sudden theme change when the app is first displayed. await settingsController.loadSettings(); // Run the app and pass in the SettingsController. The app listens to the // SettingsController for changes, then passes it further down to the // SettingsView. runApp(MyApp(settingsController: settingsController)); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/app.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'sample_feature/sample_item_details_view.dart'; import 'sample_feature/sample_item_list_view.dart'; import 'settings/settings_controller.dart'; import 'settings/settings_view.dart'; /// The Widget that configures your application. class MyApp extends StatelessWidget { const MyApp({ super.key, required this.settingsController, }); final SettingsController settingsController; @override Widget build(BuildContext context) { // Glue the SettingsController to the MaterialApp. // // The ListenableBuilder Widget listens to the SettingsController for changes. // Whenever the user updates their settings, the MaterialApp is rebuilt. return ListenableBuilder( listenable: settingsController, builder: (BuildContext context, Widget? child) { return MaterialApp( debugShowCheckedModeBanner: false, // Providing a restorationScopeId allows the Navigator built by the // MaterialApp to restore the navigation stack when a user leaves and // returns to the app after it has been killed while running in the // background. restorationScopeId: 'app', // Provide the generated AppLocalizations to the MaterialApp. This // allows descendant Widgets to display the correct translations // depending on the user's locale. localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en', ''), // English, no country code ], // Use AppLocalizations to configure the correct application title // depending on the user's locale. // // The appTitle is defined in .arb files found in the localization // directory. onGenerateTitle: (BuildContext context) => AppLocalizations.of(context)!.appTitle, // Define a light and dark color theme. Then, read the user's // preferred ThemeMode (light, dark, or system default) from the // SettingsController to display the correct theme. theme: ThemeData(), darkTheme: ThemeData.dark(), themeMode: settingsController.themeMode, // Define a function to handle named routes in order to support // Flutter web url navigation and deep linking. onGenerateRoute: (RouteSettings routeSettings) { return MaterialPageRoute<void>( settings: routeSettings, builder: (BuildContext context) { switch (routeSettings.name) { case SettingsView.routeName: return SettingsView(controller: settingsController); case SampleItemDetailsView.routeName: return const SampleItemDetailsView(); case SampleItemListView.routeName: default: return const SampleItemListView(); } }, ); }, ); }, ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/settings/settings_controller.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'settings_service.dart'; /// A class that many Widgets can interact with to read user settings, update /// user settings, or listen to user settings changes. /// /// Controllers glue Data Services to Flutter Widgets. The SettingsController /// uses the SettingsService to store and retrieve user settings. class SettingsController with ChangeNotifier { SettingsController(this._settingsService); // Make SettingsService a private variable so it is not used directly. final SettingsService _settingsService; // Make ThemeMode a private variable so it is not updated directly without // also persisting the changes with the SettingsService. late ThemeMode _themeMode; // Allow Widgets to read the user's preferred ThemeMode. ThemeMode get themeMode => _themeMode; /// Load the user's settings from the SettingsService. It may load from a /// local database or the internet. The controller only knows it can load the /// settings from the service. Future<void> loadSettings() async { _themeMode = await _settingsService.themeMode(); // Important! Inform listeners a change has occurred. notifyListeners(); } /// Update and persist the ThemeMode based on the user's selection. Future<void> updateThemeMode(ThemeMode? newThemeMode) async { if (newThemeMode == null) return; // Do not perform any work if new and old ThemeMode are identical if (newThemeMode == _themeMode) return; // Otherwise, store the new ThemeMode in memory _themeMode = newThemeMode; // Important! Inform listeners a change has occurred. notifyListeners(); // Persist the changes to a local database or the internet using the // SettingService. await _settingsService.updateThemeMode(newThemeMode); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/settings/settings_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import 'settings_controller.dart'; /// Displays the various settings that can be customized by the user. /// /// When a user changes a setting, the SettingsController is updated and /// Widgets that listen to the SettingsController are rebuilt. class SettingsView extends StatelessWidget { const SettingsView({super.key, required this.controller}); static const routeName = '/settings'; final SettingsController controller; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Settings'), ), body: Padding( padding: const EdgeInsets.all(16), // Glue the SettingsController to the theme selection DropdownButton. // // When a user selects a theme from the dropdown list, the // SettingsController is updated, which rebuilds the MaterialApp. child: DropdownButton<ThemeMode>( // Read the selected themeMode from the controller value: controller.themeMode, // Call the updateThemeMode method any time the user selects a theme. onChanged: controller.updateThemeMode, items: const [ DropdownMenuItem( value: ThemeMode.system, child: Text('System Theme'), ), DropdownMenuItem( value: ThemeMode.light, child: Text('Light Theme'), ), DropdownMenuItem( value: ThemeMode.dark, child: Text('Dark Theme'), ) ], ), ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/settings/settings_service.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; /// A service that stores and retrieves user settings. /// /// By default, this class does not persist user settings. If you'd like to /// persist the user settings locally, use the shared_preferences package. If /// you'd like to store settings on a web server, use the http package. class SettingsService { /// Loads the User's preferred ThemeMode from local or remote storage. Future<ThemeMode> themeMode() async => ThemeMode.system; /// Persists the user's preferred ThemeMode to local or remote storage. Future<void> updateThemeMode(ThemeMode theme) async { // Use the shared_preferences package to persist settings locally or the // http package to persist settings over the network. } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/sample_feature/sample_item_details_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; /// Displays detailed information about a SampleItem. class SampleItemDetailsView extends StatelessWidget { const SampleItemDetailsView({super.key}); static const routeName = '/sample_item'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Item Details'), ), body: const Center( child: Text('More Information Here'), ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/sample_feature/sample_item.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /// A placeholder class that represents an entity or model. class SampleItem { const SampleItem(this.id); final int id; }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/lib/src/sample_feature/sample_item_list_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; import '../settings/settings_view.dart'; import 'sample_item.dart'; import 'sample_item_details_view.dart'; /// Displays a list of SampleItems. class SampleItemListView extends StatelessWidget { const SampleItemListView({ super.key, this.items = const [SampleItem(1), SampleItem(2), SampleItem(3)], }); static const routeName = '/'; final List<SampleItem> items; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample Items'), actions: [ IconButton( icon: const Icon(Icons.settings), onPressed: () { // Navigate to the settings page. If the user leaves and returns // to the app after it has been killed while running in the // background, the navigation stack is restored. Navigator.restorablePushNamed(context, SettingsView.routeName); }, ), ], ), // To work with lists that may contain a large number of items, it’s best // to use the ListView.builder constructor. // // In contrast to the default ListView constructor, which requires // building all Widgets up front, the ListView.builder constructor lazily // builds Widgets as they’re scrolled into view. body: ListView.builder( // Providing a restorationId allows the ListView to restore the // scroll position when a user leaves and returns to the app after it // has been killed while running in the background. restorationId: 'sampleItemListView', itemCount: items.length, itemBuilder: (BuildContext context, int index) { final item = items[index]; return ListTile( title: Text('SampleItem ${item.id}'), leading: const CircleAvatar( // Display the Flutter Logo image asset. foregroundImage: AssetImage('assets/images/flutter_logo.png'), ), onTap: () { // Navigate to the details page. If the user leaves and returns to // the app after it has been killed while running in the // background, the navigation stack is restored. Navigator.restorablePushNamed( context, SampleItemDetailsView.routeName, ); }); }, ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/test/unit_test.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This is an example unit test. // // A unit test tests a single function, method, or class. To learn more about // writing unit tests, visit // https://flutter.dev/docs/cookbook/testing/unit/introduction import 'package:flutter_test/flutter_test.dart'; void main() { group('Plus Operator', () { test('should add two numbers together', () { expect(1 + 1, 2); }); }); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/launcher_icons_demo/test/widget_test.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This is an example 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. // // Visit https://flutter.dev/docs/cookbook/testing/widget/introduction for // more information about Widget testing. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('MyWidget', () { testWidgets('should display a string of text', (WidgetTester tester) async { // Define a Widget const myWidget = MaterialApp( home: Scaffold( body: Text('Hello'), ), ); // Build myWidget and trigger a frame. await tester.pumpWidget(myWidget); // Verify myWidget shows some text expect(find.byType(Text), findsOneWidget); }); }); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main_profile.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/main_delegate.dart'; void main() { // No need to directly call the enbironment config setup as it is // lazy loaded. In the story board case one uses overrides to // set isMockOverride and buildVariantOverride mainDelegate(); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/environment_config.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. bool? isMockOverride; String? buildVariantOverride; bool? isMockDefine; String? buildVariantDefine; /// [EnvironmentConfig] assumptions are /// that there are gitignored files of /// debug.json /// release.json /// staging.json /// preview.json /// profile.json /// /// That sets the vars per environment via /// the dart-define command. Thus, this /// is a services start entry in app start up services /// blocks /// And in test tear down it is: /// /// ```dart /// EnvironmentConfig.resetOverrides(); /// ``` /// /// Note, for story boarding one sets the overrides as part of starting the story board app /// as when the story board app is started we will not have a proper dart-define-from-file /// entry in our launch config. /// /// @author Fredrick Allan Grott class EnvironmentConfig { bool get isMockDefine => isMockOverride ?? const bool.fromEnvironment('isMock'); String get buildVariantDefine => buildVariantOverride ?? const String.fromEnvironment('buildVariant'); void resetOverrides() { isMockOverride = null; buildVariantOverride = null; } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main_release.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/main_delegate.dart'; void main() { // No need to directly call the enbironment config setup as it is // lazy loaded. In the story board case one uses overrides to // set isMockOverride and buildVariantOverride mainDelegate(); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main_delegate.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/main.dart'; void mainDelegate() => main();
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main_stagging.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/main_delegate.dart'; void main() { // No need to directly call the enbironment config setup as it is // lazy loaded. In the story board case one uses overrides to // set isMockOverride and buildVariantOverride mainDelegate(); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main_preview.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // ignore_for_file: unused_import // import 'package:device_preview/device_preview.dart'; // import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; void main() { // No need to directly call the enbironment config setup as it is // lazy loaded. In the story board case one uses overrides to // set isMockOverride and buildVariantOverride //DevopsConstants.setEnvironment(Environment.preview); //runApp(DevicePreview( //enabled: !kReleaseMode, // using builder to build the app and scaffold frame // thus builder slot gets a home MaterialApp with // scaffold wrapper //builder: (_) => MyAppPreviewWrapper(), //tools: [ // ...DevicePreview.defaultTools, // advancedScreenShotModesPlugin, // ], //)); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/src/my_app.dart'; import 'package:device_preview_demo/src/settings/settings_controller.dart'; import 'package:device_preview_demo/src/settings/settings_service.dart'; import 'package:flutter/material.dart'; void main() async { // Set up the SettingsController, which will glue user settings to multiple // Flutter Widgets. final settingsController = SettingsController(SettingsService()); // Load the user's preferred theme while the splash screen is displayed. // This prevents a sudden theme change when the app is first displayed. await settingsController.loadSettings(); // Run the app and pass in the SettingsController. The app listens to the // SettingsController for changes, then passes it further down to the // SettingsView. runApp(MyApp(settingsController: settingsController)); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/main_debug.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/main_delegate.dart'; void main() { // No need to directly call the enbironment config setup as it is // lazy loaded. In the story board case one uses overrides to // set isMockOverride and buildVariantOverride mainDelegate(); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/generated/l10n.dart
// GENERATED CODE - DO NOT MODIFY BY HAND import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'intl/messages_all.dart'; // ************************************************************************** // Generator: Flutter Intl IDE plugin // Made by Localizely // ************************************************************************** // ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars // ignore_for_file: join_return_with_assignment, prefer_final_in_for_each // ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes class S { S(); static S? _current; static S get current { assert(_current != null, 'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.'); return _current!; } static const AppLocalizationDelegate delegate = AppLocalizationDelegate(); static Future<S> load(Locale locale) { final name = (locale.countryCode?.isEmpty ?? false) ? locale.languageCode : locale.toString(); final localeName = Intl.canonicalizedLocale(name); return initializeMessages(localeName).then((_) { Intl.defaultLocale = localeName; final instance = S(); S._current = instance; return instance; }); } static S of(BuildContext context) { final instance = S.maybeOf(context); assert(instance != null, 'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?'); return instance!; } static S? maybeOf(BuildContext context) { return Localizations.of<S>(context, S); } } class AppLocalizationDelegate extends LocalizationsDelegate<S> { const AppLocalizationDelegate(); List<Locale> get supportedLocales { return const <Locale>[ Locale.fromSubtags(languageCode: 'en'), ]; } @override bool isSupported(Locale locale) => _isSupported(locale); @override Future<S> load(Locale locale) => S.load(locale); @override bool shouldReload(AppLocalizationDelegate old) => false; bool _isSupported(Locale locale) { for (var supportedLocale in supportedLocales) { if (supportedLocale.languageCode == locale.languageCode) { return true; } } return false; } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/generated
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/generated/intl/messages_en.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a en locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'en'; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{}; }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/generated
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/generated/intl/messages_all.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that looks up messages for specific locales by // delegating to the appropriate library. // Ignore issues from commonly used lints in this file. // ignore_for_file:implementation_imports, file_names, unnecessary_new // ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering // ignore_for_file:argument_type_not_assignable, invalid_assignment // ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases // ignore_for_file:comment_references import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; import 'package:intl/src/intl_helpers.dart'; import 'messages_en.dart' as messages_en; typedef Future<dynamic> LibraryLoader(); Map<String, LibraryLoader> _deferredLibraries = { 'en': () => new SynchronousFuture(null), }; MessageLookupByLibrary? _findExact(String localeName) { switch (localeName) { case 'en': return messages_en.messages; default: return null; } } /// User programs should call this before using [localeName] for messages. Future<bool> initializeMessages(String localeName) { var availableLocale = Intl.verifiedLocale( localeName, (locale) => _deferredLibraries[locale] != null, onFailure: (_) => null); if (availableLocale == null) { return new SynchronousFuture(false); } var lib = _deferredLibraries[availableLocale]; lib == null ? new SynchronousFuture(false) : lib(); initializeInternalMessageLookup(() => new CompositeMessageLookup()); messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor); return new SynchronousFuture(true); } bool _messagesExistFor(String locale) { try { return _findExact(locale) != null; } catch (e) { return false; } } MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) { var actualLocale = Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null); if (actualLocale == null) return null; return _findExact(actualLocale); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/my_app.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/generated/l10n.dart'; import 'package:device_preview_demo/src/sample_feature/sample_item_details_view.dart'; import 'package:device_preview_demo/src/sample_feature/sample_item_list_view.dart'; import 'package:device_preview_demo/src/settings/settings_controller.dart'; import 'package:device_preview_demo/src/settings/settings_view.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; /// The Widget that configures your application. class MyApp extends StatelessWidget { const MyApp({ super.key, required this.settingsController, }); final SettingsController settingsController; @override Widget build(BuildContext context) { // Glue the SettingsController to the MaterialApp. // // The ListenableBuilder Widget listens to the SettingsController for changes. // Whenever the user updates their settings, the MaterialApp is rebuilt. return ListenableBuilder( listenable: settingsController, builder: (BuildContext context, Widget? child) { return MaterialApp( onGenerateRoute: (RouteSettings routeSettings) { return MaterialPageRoute<void>( builder: (BuildContext context) { switch (routeSettings.name) { case SettingsView.routeName: return SettingsView(controller: settingsController); case SampleItemDetailsView.routeName: return const SampleItemDetailsView(); case SampleItemListView.routeName: default: return const SampleItemListView(); } }, settings: routeSettings, ); }, onGenerateTitle: (BuildContext context) => AppLocalizations.of(context)!.appTitle, theme: ThemeData(), darkTheme: ThemeData.dark(), themeMode: settingsController.themeMode, localizationsDelegates: const [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [Locale('en', '')], restorationScopeId: 'app', ); }, ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/device_preview/device_preview_pages.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview/device_preview.dart'; import 'package:device_preview_demo/generated/l10n.dart'; import 'package:device_preview_demo/src/sample_feature/sample_item_details_view.dart'; import 'package:device_preview_demo/src/sample_feature/sample_item_list_view.dart'; import 'package:device_preview_demo/src/settings/settings_controller.dart'; import 'package:device_preview_demo/src/settings/settings_view.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:screenshot_modes/screenshot_modes.dart'; // Note: Usually we write the device preview wrapper using the same // navigation way as the full app. GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); late final SettingsController settingsController; Future pushSampleItemListView(BuildContext context) async { Navigator.of(navigatorKey.currentContext!).push(DirectPageRouteBuilder(builder: (_) => const SampleItemListView())); } Future pushSettingsView(BuildContext context) async { Navigator.of(navigatorKey.currentContext!).push(DirectPageRouteBuilder(builder: (_) => SettingsView(controller: settingsController,))); // we use wait if we have animations in our page so wait until animation end then take screenshot. } Future pushSampleItemDetailsView(BuildContext context) async { Navigator.of(navigatorKey.currentContext!).push(DirectPageRouteBuilder( builder: (_) => const SampleItemDetailsView( ),),); // we use wait if we have animations in our page so wait until animation end then take screenshot. } class DevicePreviewAppWrapper extends StatelessWidget { final SettingsController settingsController; const DevicePreviewAppWrapper({super.key, required this.settingsController}); @override Widget build(BuildContext context) { var locale2 = DevicePreview.locale(context); return ListenableBuilder( listenable: settingsController, builder: (BuildContext context, Widget? child) { return MaterialApp( onGenerateRoute: (RouteSettings routeSettings) { return MaterialPageRoute<void>( builder: (BuildContext context) { switch (routeSettings.name) { case SettingsView.routeName: return SettingsView(controller: settingsController); case SampleItemDetailsView.routeName: return const SampleItemDetailsView(); case SampleItemListView.routeName: default: return const SampleItemListView(); } }, settings: routeSettings, ); }, onGenerateTitle: (BuildContext context) => AppLocalizations.of(context)!.appTitle, theme: ThemeData(), darkTheme: ThemeData.dark(), themeMode: settingsController.themeMode, locale: locale2, localizationsDelegates: const [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: [if (locale2 != null) locale2, const Locale('en', 'US')], restorationScopeId: 'app', ); }, ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/device_preview/screen_shot_modes_plugin.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'dart:io'; import 'package:device_preview/device_preview.dart'; import 'package:device_preview_demo/src/device_preview/device_preview_pages.dart'; import 'package:device_preview_demo/src/sample_feature/sample_item_list_view.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart'; import 'package:screenshot_modes/screenshot_modes.dart'; final screenShotModesPlugin = ScreenShotModesPlugin(processor: saveScreenShot, modes: listDevice); Future<String> saveScreenShot(DeviceScreenshotWithLabel screen) async { final String name = screen.label.join('/'); final path = join(Directory.current.path, 'screenshot', '$name.png'); final imageFile = File(path); await imageFile.create(recursive: true); await imageFile.writeAsBytes(screen.deviceScreenshot.bytes); return '$path saved'; // message printed to device preview plugins windows. } final listDevice = [ ItemScreenMode(function: setDeviceToIphone, modes: listLightDark, label: "iphone"), ItemScreenMode(function: setDeviceToNote, label: "note", modes: listLightDark), ]; final listLightDark = [ ItemScreenMode( function: (context) async { await setModeTo(context, ThemeMode.light); }, modes: listPush, label: "light"), ItemScreenMode( function: (context) async { await setModeTo(context, ThemeMode.dark); }, modes: listPush, label: "dark"), ]; final listPush = [ const ItemScreenMode(function: pushSampleItemListView, label: 'sample item list view'), const ItemScreenMode(function: pushSettingsView, label: 'settings view'), const ItemScreenMode(function: pushSampleItemDetailsView, label: 'item details view'), ]; Future<void> changeModeDarkLight(BuildContext context) async { DevicePreviewHelper.toggleMode(context); } Future<void> setModeTo(BuildContext context, ThemeMode mode) async { Navigator.of(navigatorKey.currentContext!).push(DirectPageRouteBuilder(builder: (_) => SampleItemListView())); final store = DevicePreviewHelper.getDevicePreviewStore(context); if (store.data.isDarkMode && mode == ThemeMode.light) { store.toggleDarkMode(); } } Future<void> setDeviceToNote(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.samsungGalaxyNote20Ultra.identifier); } Future<void> setDeviceToIphone(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone13.identifier); } Future<void> setDeviceToPixel4(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.pixel4.identifier); } Future<void> setDeviceToOnePlus8Pro(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.onePlus8Pro.identifier); } Future<void> setDeviceToSamsungGalaxyA50(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.samsungGalaxyA50.identifier); } Future<void> setDeviceToSamsungGalaxyNote20(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.samsungGalaxyNote20.identifier); } Future<void> setDeviceToSamsungGalaxyS20(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.samsungGalaxyS20.identifier); } Future<void> setDeviceToSonyXperialII(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.android.sonyXperia1II.identifier); } Future<void> setDeviceToIpad(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPad.identifier); } Future<void> setDeviceToIpad12inchesGen2(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPad12InchesGen2.identifier); } Future<void> setDeviceToIpad12InchesGen4(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPad12InchesGen4.identifier); } Future<void> setDeviceToIpadAir4(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPadAir4.identifier); } Future<void> setDeviceToIpadPro11Inches(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPadPro11Inches.identifier); } Future<void> setDeviceToIphone12Mini(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone12Mini.identifier); } Future<void> setDeviceToIphone12ProMax(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone12ProMax.identifier); } Future<void> setDeviceToIphone13Mini(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone13Mini.identifier); } Future<void> setDeviceToIphone13ProMax(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone13ProMax.identifier); } Future<void> setDeviceToIphone13(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone13.identifier); } Future<void> setDeviceToIphone14Pro(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhone14Pro.identifier); } Future<void> setDeviceToIphoneSE(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.ios.iPhoneSE.identifier); } Future<void> setDeviceToLinuxLaptop(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.linux.laptop.identifier); } Future<void> setDeviceToMacLaptop(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.macOS.macBookPro.identifier); } Future<void> setDeviceToWindowsLaptop(BuildContext context) async { DevicePreviewHelper.changeDevice(context, Devices.windows.laptop.identifier); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/settings/settings_controller.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/src/settings/settings_service.dart'; import 'package:flutter/material.dart'; /// A class that many Widgets can interact with to read user settings, update /// user settings, or listen to user settings changes. /// /// Controllers glue Data Services to Flutter Widgets. The SettingsController /// uses the SettingsService to store and retrieve user settings. class SettingsController with ChangeNotifier { SettingsController(this._settingsService); // Make SettingsService a private variable so it is not used directly. final SettingsService _settingsService; // Make ThemeMode a private variable so it is not updated directly without // also persisting the changes with the SettingsService. late ThemeMode _themeMode; // Allow Widgets to read the user's preferred ThemeMode. ThemeMode get themeMode => _themeMode; /// Load the user's settings from the SettingsService. It may load from a /// local database or the internet. The controller only knows it can load the /// settings from the service. Future<void> loadSettings() async { _themeMode = await _settingsService.themeMode(); // Important! Inform listeners a change has occurred. notifyListeners(); } /// Update and persist the ThemeMode based on the user's selection. Future<void> updateThemeMode(ThemeMode? newThemeMode) async { if (newThemeMode == null) return; // Do not perform any work if new and old ThemeMode are identical if (newThemeMode == _themeMode) return; // Otherwise, store the new ThemeMode in memory _themeMode = newThemeMode; // Important! Inform listeners a change has occurred. notifyListeners(); // Persist the changes to a local database or the internet using the // SettingService. await _settingsService.updateThemeMode(newThemeMode); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/settings/settings_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/src/settings/settings_controller.dart'; import 'package:flutter/material.dart'; /// Displays the various settings that can be customized by the user. /// /// When a user changes a setting, the SettingsController is updated and /// Widgets that listen to the SettingsController are rebuilt. class SettingsView extends StatelessWidget { const SettingsView({super.key, required this.controller}); static const routeName = '/settings'; final SettingsController controller; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Settings'), ), body: Padding( padding: const EdgeInsets.all(16), // Glue the SettingsController to the theme selection DropdownButton. // // When a user selects a theme from the dropdown list, the // SettingsController is updated, which rebuilds the MaterialApp. child: DropdownButton<ThemeMode>( items: const [ DropdownMenuItem(value: ThemeMode.system, child: Text('System Theme')), DropdownMenuItem(value: ThemeMode.light, child: Text('Light Theme')), DropdownMenuItem(value: ThemeMode.dark, child: Text('Dark Theme')), ], value: controller.themeMode, onChanged: controller.updateThemeMode, ), ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/settings/settings_service.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; /// A service that stores and retrieves user settings. /// /// By default, this class does not persist user settings. If you'd like to /// persist the user settings locally, use the shared_preferences package. If /// you'd like to store settings on a web server, use the http package. class SettingsService { /// Loads the User's preferred ThemeMode from local or remote storage. Future<ThemeMode> themeMode() async => ThemeMode.system; /// Persists the user's preferred ThemeMode to local or remote storage. Future<void> updateThemeMode(ThemeMode theme) async { // Use the shared_preferences package to persist settings locally or the // http package to persist settings over the network. } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/sample_feature/sample_item_details_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:flutter/material.dart'; /// Displays detailed information about a SampleItem. class SampleItemDetailsView extends StatelessWidget { const SampleItemDetailsView({super.key}); static const routeName = '/sample_item'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Item Details'), ), body: const Center( child: Text('More Information Here'), ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/sample_feature/sample_item.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /// A placeholder class that represents an entity or model. class SampleItem { const SampleItem(this.id); final int id; }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/lib/src/sample_feature/sample_item_list_view.dart
// Copyright 2023 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import 'package:device_preview_demo/src/sample_feature/sample_item.dart'; import 'package:device_preview_demo/src/sample_feature/sample_item_details_view.dart'; import 'package:device_preview_demo/src/settings/settings_view.dart'; import 'package:flutter/material.dart'; /// Displays a list of SampleItems. class SampleItemListView extends StatelessWidget { const SampleItemListView({ super.key, this.items = const [SampleItem(1), SampleItem(2), SampleItem(3)], }); static const routeName = '/'; final List<SampleItem> items; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample Items'), actions: [ IconButton( onPressed: () { Navigator.restorablePushNamed(context, SettingsView.routeName); }, icon: const Icon(Icons.settings), ), ], ), // To work with lists that may contain a large number of items, it’s best // to use the ListView.builder constructor. // // In contrast to the default ListView constructor, which requires // building all Widgets up front, the ListView.builder constructor lazily // builds Widgets as they’re scrolled into view. body: ListView.builder( itemBuilder: (BuildContext context, int index) { final item = items[index]; return ListTile( leading: const CircleAvatar( foregroundImage: AssetImage('assets/images/flutter_logo.png'), ), title: Text('SampleItem ${item.id}'), onTap: () {Navigator.restorablePushNamed(context, SampleItemDetailsView.routeName);}, ); }, itemCount: items.length, restorationId: 'sampleItemListView', ), ); } }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/test/unit_test.dart
// This is an example unit test. // // A unit test tests a single function, method, or class. To learn more about // writing unit tests, visit // https://flutter.dev/docs/cookbook/testing/unit/introduction import 'package:flutter_test/flutter_test.dart'; void main() { group('Plus Operator', () { test('should add two numbers together', () { expect(1 + 1, 2); }); }); }
0
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo
mirrored_repositories/flutter_bytes_devops/code_infrastructure/device_preview_demo/test/widget_test.dart
// This is an example 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. // // Visit https://flutter.dev/docs/cookbook/testing/widget/introduction for // more information about Widget testing. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('MyWidget', () { testWidgets('should display a string of text', (WidgetTester tester) async { // Define a Widget const myWidget = MaterialApp( home: Scaffold( body: Text('Hello'), ), ); // Build myWidget and trigger a frame. await tester.pumpWidget(myWidget); // Verify myWidget shows some text expect(find.byType(Text), findsOneWidget); }); }); }
0
mirrored_repositories/Light_Weather
mirrored_repositories/Light_Weather/lib/main.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/routers/routers.dart'; import 'package:weather_built_by_flutter/routers/application.dart'; import 'package:weather_built_by_flutter/views/welcome_page.dart'; import 'package:fluro/fluro.dart'; void main() async { runApp(MyApp()); } class MyApp extends StatefulWidget { MyApp() { final router = new Router(); Routes.configurRoutes(router); Application.router = router; } @override State<StatefulWidget> createState() { return _MyAppState(); } } class _MyAppState extends State { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return new MaterialApp( title: "Light Weather", theme: new ThemeData( backgroundColor: Color(0xffffffff), textTheme: TextTheme(body1: TextStyle(color: Color(0xff333333)))), home: WelcomePage(), debugShowCheckedModeBanner: false, onGenerateRoute: Application.router.generator, ); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/home_page.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/views/home_page_view.dart'; import 'package:weather_built_by_flutter/views/more_page.dart'; class AppHome extends StatefulWidget { @override State<StatefulWidget> createState() { return _HomePageState(); } } class _HomePageState extends State<AppHome> { int _curIndex = 0; List<Widget> _widgets = List(); @override void initState() { super.initState(); _widgets..add(HomePageView())..add(MorePage()); } @override Widget build(BuildContext context) { return new Scaffold( body: IndexedStack( index: _curIndex, children: _widgets, ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.cloud), title: Text("天气"), ), BottomNavigationBarItem( icon: Icon(Icons.more), title: Text("更多"), ), ], currentIndex: _curIndex, onTap: _itemTapped, type: BottomNavigationBarType.fixed, backgroundColor: Color(0xff212121), selectedItemColor: Color(0xff3d93ee), unselectedItemColor: Color(0xff8e8e8e), iconSize: 25, selectedFontSize: 12, unselectedFontSize: 12, ), ); } void _itemTapped(int index) { setState(() { _curIndex = index; }); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/city_page.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/model/city.dart'; import 'dart:convert'; class CityPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.blueGrey, leading: IconButton( icon: Icon(Icons.arrow_back_ios, color: Colors.white), onPressed: () { Navigator.of(context).pop(); }, ), title: Text( "选择城市", style: TextStyle(color: Colors.white), ), ), body: _HomePage(), ); } } class _HomePage extends StatefulWidget { @override State<StatefulWidget> createState() { return _PageState(); } } class _PageState extends State<_HomePage> { List<City> citys = []; List<City> searchCitys = []; TextEditingController _controller = new TextEditingController(); @override void initState() { super.initState(); loadCitys(); } @override Widget build(BuildContext context) { return Container( color: Colors.white, child: Column( children: <Widget>[ _buildSearch(), ListView.builder( shrinkWrap: true, itemBuilder: (context, index) { return _getItem(searchCitys[index].city); }, itemCount: searchCitys.length, ) ], ), ); } loadCitys() async { Future<String> future = DefaultAssetBundle.of(context).loadString("json/city.json"); future.then((value) { CityBean cityBean = CityBean.fromJson(json.decode(value)); citys.addAll(cityBean.result); }); } Widget _buildSearch() { return Container( height: 60, padding: EdgeInsets.all(10), child: Row( children: <Widget>[ Expanded( child: Container( height: 40, decoration: BoxDecoration( color: Color(0xfff3f3f3), borderRadius: BorderRadius.only( topLeft: Radius.circular(10), bottomLeft: Radius.circular(10))), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( width: 10, ), Expanded( child: TextField( autofocus: true, controller: _controller, decoration: InputDecoration( border: InputBorder.none, hintText: '请输入城市名称', hintStyle: TextStyle( color: Color(0xffaeaeb0), ), ), ), ) ], ), ), ), GestureDetector( child: Container( height: 40, width: 40, decoration: BoxDecoration( color: Color(0xff02a8f1), borderRadius: BorderRadius.only( topRight: Radius.circular(10), bottomRight: Radius.circular(10))), child: Icon( Icons.search, size: 30, color: Colors.white, ), ), onTap: () { searchData(_controller.text); }, ), ], ), ); } Widget _getItem(String city) { return GestureDetector( child: Container( padding: EdgeInsets.only(left: 20), color: Color(0xffE8E8E8), alignment: Alignment.centerLeft, height: 40, child: Text(city, style: TextStyle(fontSize: 18, color: Colors.black))), onTap: () { Navigator.of(context).pop(city); }, ); } void searchData(String text) async { if (text.isEmpty) { setState(() { searchCitys.clear(); }); } else { searchCitys.clear(); for (City city in citys) { if (city.city.contains(text)) { searchCitys.add(city); } } setState(() {}); } } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/welcome_page.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/views/home_page.dart'; class WelcomePage extends StatelessWidget { @override Widget build(BuildContext context) { Future.delayed(Duration(seconds: 2), () { Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => AppHome()), (route) => route == null); }); return Scaffold( body: Container( padding: EdgeInsets.all(10), child: Flex( direction: Axis.vertical, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 200), Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text("Welcome to Light Weather", style: TextStyle( fontSize: 26, color: Colors.blue, fontStyle: FontStyle.normal), ), ], ), ], ), ], ), ), ); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/first_page_view.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/model/weather_bean.dart'; import 'package:weather_built_by_flutter/utilitys/weather_icon_utility.dart'; class FirstPageView extends StatefulWidget { final WeatherResult weatherResult; FirstPageView(this.weatherResult); @override State<StatefulWidget> createState() { return _PageState(); } } class _PageState extends State<FirstPageView> { @override Widget build(BuildContext context) { return Stack( fit: StackFit.expand, children: <Widget>[ Image( image: AssetImage("image/first_page.jpg"), fit: BoxFit.cover, ), Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( height: 30, ), buildTopTem(widget.weatherResult), Expanded(child: Container()), buildBottomTem(widget.weatherResult) ], ) ], ); } } Widget buildTopTem(WeatherResult result) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.max, children: <Widget>[ //左边天气 Column( children: <Widget>[ //左边温度 Container( width: 200, height: 90, child: Stack( alignment: Alignment.center, fit: StackFit.expand, children: <Widget>[ Positioned( child: Text( result.temp, style: TextStyle( color: Colors.white, fontSize: 90, fontWeight: FontWeight.w200), ), left: 10, ), Positioned( child: Text( "℃", style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.w300), ), left: 115, top: 5, ), Positioned( child: Text( result.weather, style: TextStyle(color: Colors.white, fontSize: 18), maxLines: 1, overflow: TextOverflow.ellipsis, ), bottom: 5, left: 115, ) ], ), ), //风力,湿度 Container( decoration: BoxDecoration( color: Color(0x4fffffff), borderRadius: BorderRadius.circular(2)), padding: EdgeInsets.all(6), margin: EdgeInsets.only(top: 20), child: Text( "${result.winddirect} ${result.windpower} 湿度 ${result.humidity}%", style: TextStyle(fontSize: 16, color: Colors.white), ), ), ], ), Expanded(child: Container()), //右边空气质量 Container( width: 70, height: 30, padding: EdgeInsets.only(left: 10), decoration: BoxDecoration( color: Color(0x4fffffff), borderRadius: BorderRadius.circular(2)), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( width: 2, height: 15, decoration: BoxDecoration( color: Colors.green, borderRadius: BorderRadius.circular(1)), ), Text( " ${result.aqi.quality} ${result.aqi.aqi}", style: TextStyle(color: Colors.white, fontSize: 16), ) ], ), ), ], ); } Widget buildBottomTem(WeatherResult weatherResult) { return Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ bottomItem("今天", weatherResult.dailys[0]), bottomItem("明天", weatherResult.dailys[1]) ], ); } Widget bottomItem(String day, WeatherDaily daily) { final textStyle = TextStyle(color: Colors.white, fontSize: 14); return Expanded( child: Container( height: 100, child: Stack( fit: StackFit.expand, alignment: Alignment.center, children: <Widget>[ Positioned( child: Text( day, style: textStyle, ), left: 10, top: 12, ), Positioned( left: 10, child: Text( "${daily.day.temphigh}/${daily.night.templow}℃", style: textStyle, ), ), Positioned( child: Text( daily.day.weather, style: textStyle, ), left: 10, bottom: 15, ), Positioned( child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( "良", style: textStyle, ), SizedBox( width: 10, ), Container( width: 2, height: 15, decoration: BoxDecoration( color: Colors.green, borderRadius: BorderRadius.circular(1)), ), ], ), right: 10, top: 12, ), Positioned( child: Image( image: AssetImage(WeatherIconUtil.getWeatherIconAssetsPath(daily.day.img)), width: 30, fit: BoxFit.cover, ), right: 10, bottom: 12, ) ], ), ) ); }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/aboutme_page.dart
import 'package:flutter/material.dart'; class AboutMePage extends StatelessWidget { @override Widget build(BuildContext context) { String source = "https://github.com/lvqinzhi/Light_Weather-Flutter"; return Scaffold( appBar: AppBar( backgroundColor: Colors.blueGrey, leading: IconButton( icon: Icon(Icons.arrow_back_ios, color: Colors.white), onPressed: () { Navigator.pop(context); }, ), title: Text( "关于", style: TextStyle(color: Colors.white), ), ), body: Container( padding: EdgeInsets.all(10), child: Flex( direction: Axis.vertical, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( "项目地址:", style: TextStyle(color: Color(0xff333333), fontSize: 16), ), Text( source, style: TextStyle(color: Color(0xff555555), fontSize: 14), ), Spacer(flex: 1), Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Version 1.0.1", style: TextStyle(color: Color(0xff555555), fontSize: 12), ), ], ), SizedBox(height: 5), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "使用", style: TextStyle(color: Color(0xff333333), fontSize: 16), ), Image.asset("image/flutter_logo.png", alignment: Alignment.bottomCenter, width: 80, fit: BoxFit.contain), Text( "技术构建", style: TextStyle(color: Color(0xff333333), fontSize: 16), ), ], ) ], ), ], ), )); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/second_page_view.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/model/weather_bean.dart'; import 'package:weather_built_by_flutter/model/page_event.dart'; import 'package:weather_built_by_flutter/utilitys/weather_icon_utility.dart'; import 'package:weather_built_by_flutter/widgets/weather_line_widget.dart'; import 'package:weather_built_by_flutter/widgets/process_widget.dart'; import 'package:flutter/services.dart' show rootBundle; import 'dart:async'; import 'dart:ui' as ui; import 'dart:typed_data'; class SecondPageView extends StatefulWidget { final WeatherResult weatherResult; SecondPageView(this.weatherResult); @override State<StatefulWidget> createState() { return _PageState(); } } class _PageState extends State<SecondPageView> { ScrollController _scrollController = new ScrollController(); bool top = false; StreamSubscription streamSubscription; @override void initState() { super.initState(); top = false; //滑动属性 _scrollController.addListener(() { if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) { } else if (_scrollController.position.pixels == _scrollController.position.minScrollExtent) { setState(() { top = true; }); } else { top = false; } }); //滑动事件 streamSubscription = eventBus.on<PageEvent>().listen((event) { setState(() { top = false; }); }); initDayIcon(WeatherIconUtil.getWeatherIconAssetsPath( widget.weatherResult.dailys[0].day.img)); initNightIcon(WeatherIconUtil.getWeatherIconAssetsPath( widget.weatherResult.dailys[0].night.img)); } @override void dispose() { top = false; if (streamSubscription != null) { streamSubscription.cancel(); } super.dispose(); } bool imageLoaded = false; @override Widget build(BuildContext context) { if (imageLoaded) { return Stack( fit: StackFit.expand, children: <Widget>[ Image(image: AssetImage("image/second_page.jpg"),fit: BoxFit.cover,), SingleChildScrollView( physics: getScrollPhysics(top), controller: _scrollController, child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ _buildTitle("24小时预报"), _buildLine(), _buildHour(widget.weatherResult.hours), _buildLine(), _buildTitle("7日预报"), _buildLine(), _buildDaily( widget.weatherResult.dailys, dayImages, nightImages), _buildLine(), _buildTitle("生活指数"), _buildLine(), _buildGrid(widget.weatherResult.indexs), ], ), ), ], ); } else { return ProgressView(); } } List<ui.Image> dayImages = []; List<ui.Image> nightImages = []; Future<Null> initDayIcon(String path) async { final ByteData data = await rootBundle.load(path); ui.Image image = await loadDayImage(new Uint8List.view(data.buffer)); dayImages.add(image); int length = widget.weatherResult.dailys.length; if (dayImages.length < length) { var dayNight = widget.weatherResult.dailys[dayImages.length].day; initDayIcon(WeatherIconUtil.getWeatherIconAssetsPath(dayNight.img)); } else { if (dayImages.length == length && nightImages.length == length) { setState(() { imageLoaded = true; }); } } } Future<ui.Image> loadDayImage(List<int> img) async { final Completer<ui.Image> completer = new Completer(); ui.decodeImageFromList(img, (ui.Image img) { return completer.complete(img); }); return completer.future; } initNightIcon(String path) async { final ByteData data = await rootBundle.load(path); ui.Image image = await loadNightImage(new Uint8List.view(data.buffer)); nightImages.add(image); int length = widget.weatherResult.dailys.length; if (nightImages.length < length) { var dayNight = widget.weatherResult.dailys[dayImages.length].night; initNightIcon(WeatherIconUtil.getWeatherIconAssetsPath(dayNight.img)); } else { if (dayImages.length == length && nightImages.length == length) { setState(() { imageLoaded = true; }); } } } Future<ui.Image> loadNightImage(List<int> img) async { final Completer<ui.Image> completer = new Completer(); ui.decodeImageFromList(img, (ui.Image img) { return completer.complete(img); }); return completer.future; } } //滑动系数 ScrollPhysics getScrollPhysics(bool top) { if (top) { return NeverScrollableScrollPhysics(); } else { return BouncingScrollPhysics(); } } Widget _buildTitle(String title) { return Container( padding: EdgeInsets.all(10), child: Text( title, style: TextStyle(color: Colors.white, fontSize: 16), ), ); } Widget _buildLine({double height, Color color}) { return Container( height: height == null ? 0.5 : height, color: color ?? Colors.white, ); } //24小时预报 Widget _buildHour(List<WeatherHourly> hours) { List<Widget> widgets = []; for (int i = 0; i < hours.length; i++) { widgets.add(_getHourItem(hours[i])); } return Container( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: widgets, ), ), ); } Widget _getHourItem(WeatherHourly hourly) { return Container( height: 110, width: 80, padding: EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( hourly.time, style: TextStyle(color: Colors.white, fontSize: 12), ), SizedBox( height: 10, ), Image( image: AssetImage(WeatherIconUtil.getWeatherIconAssetsPath(hourly.img)), height: 30, ), SizedBox( height: 10, ), Text( hourly.temp + "℃", style: TextStyle(color: Colors.white, fontSize: 16), ), ], ), ); } //7日预报 Widget _buildDaily(List<WeatherDaily> dailys, List<ui.Image> dayImages, List<ui.Image> nightImages) { return Container( height: 340, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: WeatherLineWidget(dailys, dayImages, nightImages), ), ); } //生活指数 Widget _buildGrid(List<WeatherIndex> indexs) { List<Widget> childs = []; for (int i = 0; i < indexs.length; i++) { childs.add(_getGridItem(indexs[i])); } return Container( child: GridView( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, ), children: childs, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), ), ); } Widget _getGridItem(WeatherIndex index) { return Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ Text( index.ivalue, style: TextStyle(color: Colors.white, fontSize: 18), ), SizedBox( height: 10, ), Text( index.iname, style: TextStyle(color: Colors.white, fontSize: 14), ), ], ), ); }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/home_page_view.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/api/api.dart'; import 'package:weather_built_by_flutter/model/weather_bean.dart'; import 'package:weather_built_by_flutter/model/page_event.dart'; import 'package:weather_built_by_flutter/routers/application.dart'; import 'package:weather_built_by_flutter/routers/routers.dart'; import 'package:weather_built_by_flutter/utilitys/shared_preferences_utility.dart'; import 'package:weather_built_by_flutter/views/first_page_view.dart'; import 'package:weather_built_by_flutter/views/second_page_view.dart'; import 'package:weather_built_by_flutter/widgets/process_widget.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; class HomePageView extends StatefulWidget { HomePageView(); @override State<StatefulWidget> createState() { return _PageState(); } } class _PageState extends State<HomePageView> { String city = ""; String jsondata = ""; WeatherResult weatherResult; int loadState = 2; //0:failed; 1:succeed; 2:loading PageController _pageController = new PageController(); @override void initState() { super.initState(); loadWeatherData(); _pageController.addListener(() { if (_pageController.position.pixels == _pageController.position.extentInside) { eventBus.fire(PageEvent); } }); } @override Widget build(BuildContext context) { if (jsondata.isNotEmpty) { WeatherBean weatherBean = WeatherBean.fromJson(json.decode(jsondata)); if (weatherBean.succeed()) { loadState = 1; weatherResult = weatherBean.result; } else { loadState = 0; } } return Material( child: Column( children: <Widget>[ buildBar(context), Expanded(child: _buildPageView()) ], ), ); } loadWeatherAssets() async { Future<String> future = DefaultAssetBundle.of(context).loadString("json/weather_default.json"); future.then((value) { setState(() { jsondata = value; }); }); } loadWeatherData() async { if (city.isEmpty) { await shared_preferences_utility.instance.then((sp) { city = sp.get("city"); }); } if (city == null) city = "杭州"; final response = await http.get(Api.WEATHER_QUERY + city); setState(() { jsondata = response.body; }); } Widget _buildPageView() { if (loadState == 2) { return new ProgressView(); } else if (loadState == 1) { return new PageView( scrollDirection: Axis.vertical, controller: _pageController, children: <Widget>[ FirstPageView(weatherResult), SecondPageView(weatherResult) ], ); } else { return Center( child: Column( children: <Widget>[ Icon(Icons.sms_failed), SizedBox(height: 10), Text("加载失败", style: TextStyle(fontSize: 16, color: Color(0xff8a8a8a))), ], ), ); } } Widget buildBar(BuildContext context) { return Container( padding: EdgeInsets.only(left: 10, top: MediaQuery.of(context).padding.top), height: MediaQuery.of(context).padding.top + 40, color: Colors.blueGrey, child: GestureDetector( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Icon(Icons.edit, color: Colors.white, size: 20), SizedBox(width: 10), Text( city, style: TextStyle(fontSize: 16, color: Colors.white), ), ], ), onTap: () { Future future = Application.router.navigateTo(context, Routes.cityPage); future.then((value) { if (value != null) { setState(() { loadState = 2; }); city = value.toString(); loadWeatherData(); shared_preferences_utility.instance.then((sp) { sp.putString("city", value.toString()); }); } }); }, )); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/views/more_page.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/views/aboutme_page.dart'; class MorePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('更多', style: TextStyle(color: Colors.white)), backgroundColor: Colors.blueGrey, ), body: Container( child: ListView( physics: const NeverScrollableScrollPhysics(), children: <Widget>[ ListTile( leading: Icon(Icons.settings), title: Text('设置'), trailing: Icon(Icons.chevron_right), onTap: () { Scaffold.of(context) .showSnackBar(SnackBar(content: Text('开发中,敬请期待'))); }, ), ListTile( leading: Icon(Icons.person), title: Text('关于'), trailing: Icon(Icons.chevron_right), onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => AboutMePage())); }, ), ], ), ), ); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/widgets/weather_line_widget.dart
import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/model/weather_bean.dart'; import 'package:weather_built_by_flutter/utilitys/time_utility.dart'; import 'dart:ui' as ui; class WeatherLineWidget extends StatelessWidget { WeatherLineWidget(this.dailys, this.dayIcons, this.nightIcons); final List<WeatherDaily> dailys; final List<ui.Image> dayIcons; final List<ui.Image> nightIcons; @override Widget build(BuildContext context) { return CustomPaint( painter: _customPainter(dailys, dayIcons, nightIcons), size: Size(420, 310), ); } } class _customPainter extends CustomPainter { _customPainter(this.dailys, this.dayImages, this.nightIcons); List<WeatherDaily> dailys; List<ui.Image> dayImages; List<ui.Image> nightIcons; final double itemWidth = 60; final double textHeight = 130; final double temHeight = 80; int maxTem, minTem; @override void paint(Canvas canvas, Size size) async { setMinMax(); print("======= night:" + nightIcons.length.toString() + " day:" + dayImages.length.toString()); var maxPaint = new Paint() ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke ..color = Color(0xffeceea6) ..isAntiAlias = true ..strokeWidth = 2; var minPaint = new Paint() ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke ..color = Color(0xffa3f4fe) ..isAntiAlias = true ..strokeWidth = 2; var pointPaint = Paint() ..color = Colors.green ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..isAntiAlias = true ..strokeWidth = 8; var linePaint = Paint() ..color = Colors.white70 ..strokeWidth = 0.5 ..style = PaintingStyle.stroke; var maxPath = new Path(); var minPath = new Path(); List<Offset> maxPoints = []; List<Offset> minPoints = []; double oneTemHeight = temHeight / (maxTem - minTem); //每个温度的高度 for (int i = 0; i < dailys.length; i++) { var daily = dailys[i]; var dx = itemWidth / 2 + itemWidth * i; var maxDy = textHeight + (maxTem - int.parse(daily.day.temphigh)) * oneTemHeight; var minDy = textHeight + (maxTem - int.parse(daily.night.templow)) * oneTemHeight; var maxOffset = new Offset(dx, maxDy); var minOffset = new Offset(dx, minDy); if (i == 0) { maxPath.moveTo(dx, maxDy); minPath.moveTo(dx, minDy); } else { maxPath.lineTo(dx, maxDy); minPath.lineTo(dx, minDy); } maxPoints.add(maxOffset); minPoints.add(minOffset); if (i != 0) { canvas.drawLine(Offset(itemWidth * i, 0), Offset(itemWidth * i, textHeight * 2 + textHeight), linePaint); } var date; if (i == 0) { date = daily.week + "\n" + "今天"; } else if (i == 1) { date = daily.week + "\n" + "明天"; } else { date = daily.week + "\n" + TimeUtil.getWeatherDate(daily.date); } //日期 drawText(canvas, i, date, 10); //白天天气图片 canvas.drawImageRect( dayImages[i], Rect.fromLTWH(0, 0, dayImages[i].width.toDouble(), dayImages[i].height.toDouble()), Rect.fromLTWH(itemWidth / 4 + itemWidth * i, 50, 30, 30), linePaint); //白天天气 drawText(canvas, i, daily.day.weather, 85); //白天气温 drawText(canvas, i, daily.day.temphigh + "℃", 110); //夜间天气图片 canvas.drawImageRect( nightIcons[i], Rect.fromLTWH(0, 0, nightIcons[i].width.toDouble(), nightIcons[i].height.toDouble()), Rect.fromLTWH(itemWidth / 4 + itemWidth * i, textHeight + temHeight + 25, 30, 30), new Paint()); //夜间天气 drawText(canvas, i, daily.night.weather, textHeight + temHeight + 60); //夜间气温 drawText(canvas, i, daily.night.templow + "℃", textHeight + temHeight + 5); //风向和风力 drawText(canvas, i, daily.night.winddirect + "\n" + daily.night.windpower, textHeight + temHeight + 90, frontSize: 10); } //最高温度折线 canvas.drawPath(maxPath, maxPaint); //最低温度折线 canvas.drawPath(minPath, minPaint); //最高温度点 canvas.drawPoints(ui.PointMode.points, maxPoints, pointPaint); //最低温度点 canvas.drawPoints(ui.PointMode.points, minPoints, pointPaint); } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } //最高最低温度 setMinMax() { minTem = maxTem = int.parse(dailys[0].day.temphigh); for (WeatherDaily daily in dailys) { if (int.parse(daily.day.temphigh) > maxTem) { maxTem = int.parse(daily.day.temphigh); } if (int.parse(daily.night.templow) < minTem) { minTem = int.parse(daily.night.templow); } } } //文字 drawText(Canvas canvas, int i, String text, double height, {double frontSize}) { var pb = ui.ParagraphBuilder(ui.ParagraphStyle( textAlign: TextAlign.center, //居中 fontSize: frontSize == null ? 14 : frontSize, //大小 )); pb.addText(text); pb.pushStyle(ui.TextStyle(color: Colors.white)); //文字宽度 var paragraph = pb.build() ..layout(ui.ParagraphConstraints(width: itemWidth)); //绘制文字 canvas.drawParagraph(paragraph, Offset(itemWidth * i, height)); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/widgets/process_widget.dart
import 'package:flutter/material.dart'; class ProgressView extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: CircularProgressIndicator( strokeWidth: 2, ), ); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/model/city.dart
class CityBean { final List<City> result; CityBean({this.result}); factory CityBean.fromJson(Map<String, dynamic> json) { var tempList = json['result'] as List; List<City> items = tempList.map((i) => City.fromJson(i)).toList(); return CityBean(result: items); } } class City { final int cityid; final String city; City({this.cityid, this.city}); factory City.fromJson(Map<String, dynamic> json) { return City(cityid: json['cityid'], city: json['city']); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/model/weather_bean.dart
class WeatherBean { final int status; final String msg; final WeatherResult result; WeatherBean({ this.status, this.msg, this.result, }); bool succeed() { return status == 0; } factory WeatherBean.fromJson(Map<String, dynamic> json) { return WeatherBean( status: json['status'], msg: json['msg'], result: json['status'] == 0 ? WeatherResult.fromJson(json['result']) : null); } } class WeatherResult { final String city; //城市 final String citycode; //城市代码 final String date; //日期 final String week; //星期 final String weather; //天气 final String temp; //当前气温 final String temphigh; //最高温度 final String templow; //最低温度 final String img; //图片 final String humidity; //湿度 final String pressure; //气压 final String windspeed; //风速 final String winddirect; //风向 final String windpower; //风级 final String updatetime; //更新时间 final Aqi aqi; final List<WeatherIndex> indexs; //生活指数 final List<WeatherDaily> dailys; //一周天气 final List<WeatherHourly> hours; //24小时天气 WeatherResult( {this.city, this.citycode, this.date, this.weather, this.temp, this.temphigh, this.templow, this.img, this.humidity, this.pressure, this.windspeed, this.winddirect, this.windpower, this.updatetime, this.week, this.aqi, this.indexs, this.dailys, this.hours}); factory WeatherResult.fromJson(Map<String, dynamic> json) { var temIndexs = json['index'] as List; List<WeatherIndex> indexList = temIndexs.map((i) => WeatherIndex.fromJson(i)).toList(); var temDailys = json['daily'] as List; List<WeatherDaily> dailyList = temDailys.map((i) => WeatherDaily.fromJson(i)).toList(); var temHours = json['hourly'] as List; List<WeatherHourly> hoursList = temHours.map((i) => WeatherHourly.fromJson(i)).toList(); return WeatherResult( city: json['city'], citycode: json['citycode'].toString(), date: json['date'], week: json['week'], weather: json['weather'], temp: json['temp'], temphigh: json['temphigh'], templow: json['templow'], img: json['img'], humidity: json['humidity'], pressure: json['pressure'], windspeed: json['windspeed'], winddirect: json['winddirect'], windpower: json['windpower'], updatetime: json['updatetime'], aqi: Aqi.fromJson(json['aqi']), indexs: indexList, dailys: dailyList, hours: hoursList); } } class WeatherIndex { final String iname; //指数名 final String ivalue; //指数值 final String detail; //描述 WeatherIndex({this.iname, this.ivalue, this.detail}); factory WeatherIndex.fromJson(Map<String, dynamic> json) { return new WeatherIndex( iname: json['iname'], ivalue: json['ivalue'], detail: json['detail'], ); } } class WeatherDaily { final String date; //日期 final String week; //星期 final String sunrise; //日出 final String sunset; //日落 final DayNight night; //夜间天气 final DayNight day; //白天天气 WeatherDaily( {this.date, this.week, this.sunrise, this.sunset, this.night, this.day}); factory WeatherDaily.fromJson(Map<String, dynamic> json) { return WeatherDaily( date: json['date'], week: json['week'], sunrise: json['sunrise'], sunset: json['sunset'], night: json['night'] != null ? DayNight.fromJson(json['night']) : null, day: json['day'] != null ? DayNight.fromJson(json['day']) : null, ); } } class DayNight { final String weather; //天气 final String temphigh; //白天最高温度 final String templow; //夜间最低温度 final String img; //图片 final String winddirect; //风速 final String windpower; //风力 DayNight( {this.weather, this.temphigh, this.templow, this.img, this.winddirect, this.windpower}); factory DayNight.fromJson(Map<String, dynamic> json) { return DayNight( weather: json['weather'], temphigh: json['temphigh'], templow: json['templow'], img: json['img'], winddirect: json['winddirect'], windpower: json['windpower']); } } class WeatherHourly { final String time; //时间 final String weather; //天气 final String temp; //温度 final String img; //图片 WeatherHourly({this.time, this.weather, this.temp, this.img}); factory WeatherHourly.fromJson(Map<String, dynamic> json) { return new WeatherHourly( time: json['time'], weather: json['weather'], temp: json['temp'], img: json['img']); } } class Aqi { final String aqi; final String quality; final AqiInfo aqiinfo; Aqi({this.aqi, this.quality, this.aqiinfo}); factory Aqi.fromJson(Map<String, dynamic> json) { return Aqi( aqi: json['aqi'], quality: json['quality'], aqiinfo: AqiInfo.fromJson(json['aqiinfo'])); } } class AqiInfo { final String level; final String color; final String affect; final String measure; AqiInfo({ this.level, this.color, this.affect, this.measure, }); factory AqiInfo.fromJson(Map<String, dynamic> json) { return AqiInfo( level: json['level'], color: json['color'], affect: json['affect'], measure: json['measure']); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/model/page_event.dart
import 'package:event_bus/event_bus.dart'; EventBus eventBus = new EventBus(); class PageEvent {}
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/api/api.dart
class Api{ static const String WEATHER_QUERY ="https://api.jisuapi.com/weather/query?appkey=e871c41f905794e8&city="; static const String APPKEY_JS = "e871c41f905794e8"; }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/routers/router_handler.dart
import 'package:fluro/fluro.dart'; import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/views/city_page.dart'; import 'package:weather_built_by_flutter/views/home_page.dart'; import 'package:weather_built_by_flutter/views/more_page.dart'; var homeHandler = new Handler( handlerFunc: (BuildContext context, Map<String, List<String>> parameters) { return AppHome(); }); var cityHandler = new Handler( handlerFunc: (BuildContext context, Map<String, List<String>> parameters) { return new CityPage(); }); var moreHandler = new Handler( handlerFunc: (BuildContext context, Map<String, List<String>> parameters) { return new MorePage(); });
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/routers/routers.dart
import 'package:fluro/fluro.dart'; import 'package:flutter/material.dart'; import 'package:weather_built_by_flutter/routers/router_handler.dart'; class Routes { static String root = '/'; static String home = "/home"; static String cityPage = "/city"; static String morePage = "/more"; static void configurRoutes(Router router) { router.notFoundHandler = new Handler( handlerFunc: (BuildContext context, Map<String, List<String>> params) {}); router.define(home, handler: homeHandler); router.define(cityPage, handler: cityHandler); router.define(morePage, handler: moreHandler); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/routers/application.dart
import 'package:fluro/fluro.dart'; class Application { static Router router; }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/utilitys/time_utility.dart
class TimeUtil { static String getWeatherDate(String date) { date = date.replaceAll("-", "/"); return date.substring(date.indexOf("/") + 1); } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/utilitys/weather_icon_utility.dart
class WeatherIconUtil{ static String getWeatherIconAssetsPath(String img){ return "image/$img.png"; } }
0
mirrored_repositories/Light_Weather/lib
mirrored_repositories/Light_Weather/lib/utilitys/shared_preferences_utility.dart
import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; class shared_preferences_utility { static shared_preferences_utility _instance; static Future<shared_preferences_utility> get instance async { return await getInstance(); } static SharedPreferences _spf; shared_preferences_utility._(); Future _init() async { _spf = await SharedPreferences.getInstance(); } static Future<shared_preferences_utility> getInstance() async { if (_instance == null) { _instance = new shared_preferences_utility._(); await _instance._init(); } return _instance; } static bool _beforecheck() { if (_spf == null) { return true; } return false; } bool hasKey(String key) { Set keys = getKeys(key); return keys.contains(keys); } Set<String> getKeys(String key) { if (_beforecheck()) return null; return _spf.getKeys(); } get(String key) { if (_beforecheck()) return null; return _spf.get(key); } getString(String key) { if (_beforecheck()) return null; return _spf.getString(key); } Future<bool> putString(String key, String value) { if (_beforecheck()) return null; return _spf.setString(key, value); } bool getBool(String key) { if (_beforecheck()) return null; return _spf.getBool(key); } Future<bool> putBool(String key, bool value) { if (_beforecheck()) return null; return _spf.setBool(key, value); } int getInt(String key) { if (_beforecheck()) return null; return _spf.getInt(key); } Future<bool> putInt(String key, int value) { if (_beforecheck()) return null; return _spf.setInt(key, value); } double getDouble(String key) { if (_beforecheck()) return null; return _spf.getDouble(key); } Future<bool> putDouble(String key, double value) { if (_beforecheck()) return null; return _spf.setDouble(key, value); } List<String> getStringList(String key) { if (_beforecheck()) return null; return _spf.getStringList(key); } Future<bool> putStringLisg(String key, List<String> value) { if (_beforecheck()) return null; return _spf.setStringList(key, value); } dynamic getDynamic(String key) { if (_beforecheck()) return null; return _spf.get(key); } Future<bool> remove(String key) { if (_beforecheck()) return null; return _spf.remove(key); } Future<bool> clear() { if (_beforecheck()) return null; return _spf.clear(); } }
0
mirrored_repositories/Light_Weather
mirrored_repositories/Light_Weather/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:weather_built_by_flutter/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/user_tag_demo
mirrored_repositories/user_tag_demo/lib/main.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/views/home_view.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'User Tag Demo', theme: ThemeData( textSelectionTheme: TextSelectionThemeData( selectionColor: Colors.redAccent.withOpacity(.3), ), primarySwatch: Colors.red, ), home: const HomeView(), ); } }
0
mirrored_repositories/user_tag_demo/lib
mirrored_repositories/user_tag_demo/lib/views/home_view.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/models/post.dart'; import 'package:user_tag_demo/views/view_models/home_view_model.dart'; import 'package:user_tag_demo/views/widgets/comment_text_field.dart'; import 'package:user_tag_demo/views/widgets/post_widget.dart'; import 'package:user_tag_demo/views/widgets/user_tagger_widget.dart'; class HomeView extends StatefulWidget { const HomeView({Key? key}) : super(key: key); @override State<HomeView> createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> { late final homeViewModel = HomeViewModel(); late final _controller = TextEditingController(); late final _focusNode = FocusNode(); String _formattedText = ""; VoidCallback? _dismissOverlay; void _focusListener() { if (!_focusNode.hasFocus) { _dismissOverlay?.call(); } } @override void initState() { super.initState(); _focusNode.addListener(_focusListener); } @override void dispose() { _focusNode.removeListener(_focusListener); _focusNode.dispose(); _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var insets = MediaQuery.of(context).viewInsets; return GestureDetector( onTap: () { _dismissOverlay?.call(); }, child: Scaffold( appBar: AppBar( backgroundColor: Colors.redAccent, title: const Text("The Squad"), ), bottomNavigationBar: UserTagger( onCreate: (onClose) { _dismissOverlay = onClose; }, onFormattedTextChanged: (formattedText) { _formattedText = formattedText; }, controller: _controller, builder: (context, containerKey) { return CommentTextField( focusNode: _focusNode, containerKey: containerKey, insets: insets, controller: _controller, onSend: () { FocusScope.of(context).unfocus(); homeViewModel.addPost(_formattedText); _controller.clear(); }, ); }), body: ValueListenableBuilder<List<Post>>( valueListenable: homeViewModel.posts, builder: (_, posts, __) { return ListView.builder( itemCount: posts.length, itemBuilder: (_, index) { return PostWidget(post: posts[index]); }, ); }), ), ); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/widgets/comment_text_field.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/models/user.dart'; import 'package:user_tag_demo/views/widgets/custom_text_field.dart'; class CommentTextField extends StatelessWidget { final TextEditingController controller; final List<String> emojis; final VoidCallback onSend; final EdgeInsets insets; final FocusNode? focusNode; ///Key passed down from UserTagger final Key? containerKey; const CommentTextField({ Key? key, required this.controller, required this.onSend, required this.insets, this.emojis = const [ '😍', '😜', '👍', '🤞', '🙌', '😉', '🙏', ], this.focusNode, this.containerKey, }) : super(key: key); @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Container( key: containerKey, constraints: BoxConstraints( maxHeight: insets == EdgeInsets.zero ? 150 : 150 + insets.bottom, ), padding: const EdgeInsets.symmetric( vertical: 20, horizontal: 10, ), color: Colors.white, child: Column( mainAxisAlignment: insets == EdgeInsets.zero ? MainAxisAlignment.end : MainAxisAlignment.start, children: [ SingleChildScrollView( scrollDirection: Axis.horizontal, child: SizedBox( width: width, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ for (var emoji in emojis) EmojiIcon( fontSize: 24, emoji: emoji, onTap: (emoji) { controller.text += emoji; controller.selection = TextSelection.fromPosition( TextPosition(offset: controller.text.length), ); }, ) ], ), ), ), const SizedBox(height: 18), Row( children: [ Container( height: 50, width: 50, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( fit: BoxFit.cover, image: NetworkImage(User.anon().avatar), ), ), ), const Spacer(), SizedBox( width: width * .82, child: CustomTextField( focusNode: focusNode, controller: controller, hint: "Type something fun...", suffix: IconButton( onPressed: onSend, icon: const Icon( Icons.send, color: Colors.redAccent, ), ), ), ), ], ) ], ), ); } } class EmojiIcon extends StatelessWidget { final String emoji; final Function(String) onTap; final double fontSize; const EmojiIcon({ Key? key, required this.emoji, required this.onTap, this.fontSize = 24, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: () => onTap(emoji), child: Text( emoji, style: TextStyle( fontSize: fontSize, ), ), ); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/widgets/post_widget.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/models/post.dart'; import 'package:user_tag_demo/views/widgets/custom_text.dart'; class PostWidget extends StatelessWidget { final Post post; const PostWidget({Key? key, required this.post}) : super(key: key); @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: 50, width: 50, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( fit: BoxFit.cover, image: NetworkImage(post.poster.avatar), ), ), ), const SizedBox(width: 8), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.symmetric(vertical: 5), constraints: BoxConstraints(maxWidth: width * .76), child: CustomText( text: post.caption, parentText: "${post.poster.userName} ", parentTextStyle: const TextStyle( color: Colors.black, fontSize: 14, fontWeight: FontWeight.w600, ), onUserTagPressed: (userId) { //typically, you'd navigate to details screen //and fetch user details with userId print(userId); }, ), ), Text( post.time, style: const TextStyle( color: Colors.grey, fontSize: 12, fontWeight: FontWeight.w400, ), ), ], ), ], ), ], ), ); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/widgets/user_tagger_widget.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/models/user.dart'; import 'package:user_tag_demo/views/view_models/search_view_model.dart'; import 'package:user_tag_demo/views/widgets/loading_indicator.dart'; ///Search view model final _searchViewModel = SearchViewModel(); class UserTagger extends StatefulWidget { const UserTagger({ Key? key, required this.controller, required this.onFormattedTextChanged, required this.builder, this.onCreate, }) : super(key: key); ///Child TextField's controller final TextEditingController controller; ///Callback to dispatch updated formatted text final void Function(String) onFormattedTextChanged; ///Returns callback that can be used to dismiss the overlay ///from parent widget. final void Function(VoidCallback)? onCreate; ///Widget builder. ///Returned widget must use the [GlobalKey] as it's key. final Widget Function(BuildContext, GlobalKey) builder; @override State<UserTagger> createState() => _UserTaggerState(); } class _UserTaggerState extends State<UserTagger> { TextEditingController get controller => widget.controller; late final _containerKey = GlobalKey( debugLabel: "TextField Container Key", ); late Offset _offset = Offset.zero; late double _width = 0; late bool _hideOverlay = true; OverlayEntry? _overlayEntry; ///Retrieves rendering information necessary to determine where ///the overlay is positioned on the screen. void _computeSize() { try { final renderBox = _containerKey.currentContext!.findRenderObject() as RenderBox; _width = renderBox.size.width; _offset = renderBox.localToGlobal(Offset.zero); } catch (e) { debugPrint(e.toString()); } } ///Hides overlay if [val] is true. ///Otherwise, this computes size, creates and inserts and OverlayEntry. void _shouldHideOverlay(bool val) { try { if (_hideOverlay == val) return; setState(() { _hideOverlay = val; if (_hideOverlay) { _overlayEntry?.remove(); _overlayEntry = null; } else { _computeSize(); _overlayEntry = _createOverlay(); Overlay.of(context)!.insert(_overlayEntry!); } }); } catch (e) { debugPrint(e.toString()); } } ///Creates an overlay to show search result OverlayEntry _createOverlay() { return OverlayEntry( builder: (_) => Positioned( left: _offset.dx, width: _width, height: 380, top: _offset.dy - 390, child: _UserListView( tagUser: _tagUser, onClose: () => _shouldHideOverlay(true), ), ), ); } ///Table of tagged user names and their ids late final Map<String, String> _taggedUsers = {}; ///Formatted text where tagged user names are replaced in this format: ///```dart ///"@Lucky Ebere" ///``` ///becomes /// ///```dart ///"@6zo22531b866ce0016f9e5tt#Lucky Ebere#" ///``` ///assuming that `Lucky Ebere`'s id is `6zo22531b866ce0016f9e5tt` String get _formattedText { String text = controller.text; for (var name in _taggedUsers.keys) { if (text.contains(name)) { final userName = name.replaceAll("@", ""); text = text.replaceAll(name, "@${_taggedUsers[name]}#$userName#"); } } return text; } ///Whether to not execute the [_tagListener] logic bool _defer = false; ///Current tagged user selected in TextField String _selectedTag = ""; ///Executes user search with [query] void _search(String query) { if (query.isEmpty) return; _shouldHideOverlay(false); _searchViewModel.search(query.trim()); } ///Adds [name] and [id] to [_taggedUsers] and ///updates content of TextField with [name] void _tagUser(String name, String id) { _shouldSearch = false; _shouldHideOverlay(true); name = "@${name.trim()}"; id = id.trim(); if (_taggedUsers[name] != null) { //user has already been tagged //show error return; } final text = controller.text; late final position = controller.selection.base.offset - 1; int index = 0; if (position != text.length - 1) { index = text.substring(0, position).lastIndexOf("@"); } else { index = text.lastIndexOf("@"); } if (index >= 0) { final tag = text.substring(index, position + 1); _defer = true; _taggedUsers[name] = id; final newText = text.replaceAll(tag, name); _lastCachedText = newText; controller.text = newText; _defer = true; int offset = newText.indexOf(name) + name.length + 1; if (offset > newText.length) offset -= 1; controller.selection = TextSelection.fromPosition( TextPosition( offset: offset, ), ); widget.onFormattedTextChanged(_formattedText); } } ///Highlights a tagged user from [_taggedUsers] when keyboard action attempts to remove them ///to prompt the user. /// ///Highlighted user when [_removeEditedTags] is triggered is removed from ///the TextField. /// ///Does nothing when there is no tagged user or when there's no attempt ///to remove a tagged user from the TextField. /// ///Returns `true` if a tagged user is either selected or removed ///(if they were previously selected). ///Otherwise, returns `false`. bool _removeEditedTags() { try { final text = controller.text; if (text.isEmpty) { _taggedUsers.clear(); _lastCachedText = text; return false; } final position = controller.selection.base.offset - 1; if (text[position] == "@") { _shouldSearch = true; return false; } for (var tag in _taggedUsers.keys) { if (!text.contains(tag)) { if (_isTagSelected) { _removeSelection(); return true; } else { if (_backtrackAndSelect(tag)) return true; } } } } catch (e, trace) { debugPrint("FROM _removeEditedTags: $e"); debugPrint("FROM _removeEditedTags: $trace"); } _lastCachedText = controller.text; _defer = false; return false; } ///Back tracks from current cursor position to find and select ///a tagged user, if any. /// ///Returns `true` if a tagged user is found and selected. ///Otherwise, returns `false`. bool _backtrackAndSelect(String tag) { String text = controller.text; if (!text.contains("@")) return false; final length = controller.selection.base.offset; _defer = true; controller.text = _lastCachedText; text = _lastCachedText; _defer = true; controller.selection = TextSelection.fromPosition( TextPosition(offset: length), ); late String temp = ""; for (int i = length; i >= 0; i--) { if (i == length && text[i] == "@") return false; temp = text[i] + temp; if (text[i] == "@" && temp.length > 1 && temp == tag) { _selectedTag = tag; _isTagSelected = true; _startOffset = i; _endOffset = length + 1; _defer = true; controller.selection = TextSelection( baseOffset: _startOffset!, extentOffset: _endOffset!, ); return true; } } return false; } ///Updates offsets after [_selectedTag] set in [_backtrackAndSelect] ///has been removed. void _removeSelection() { _taggedUsers.remove(_selectedTag); _selectedTag = ""; _lastCachedText = controller.text; _startOffset = null; _endOffset = null; _isTagSelected = false; widget.onFormattedTextChanged(_formattedText); } ///Whether a tagged user is selected in the TextField bool _isTagSelected = false; ///Start offset for selection in the TextField int? _startOffset; ///End offset for selection in the TextField int? _endOffset; ///Text from the TextField in it's previous state before a new update ///(new text input from keyboard or deletion). /// ///This is necessary to compare and see if changes have occured and to restore ///the text field content when user attempts to remove a tagged user ///so the tagged user can be selected and with further action, be removed. String _lastCachedText = ""; ///Whether to initiate a user search bool _shouldSearch = false; ///Regex to match allowed search characters. ///Non-conforming characters terminate the search context. late final _regExp = RegExp(r'^[a-zA-Z-]*$'); ///This is triggered when deleting text from TextField that isn't ///a tagged user. Useful for continuing search without having to ///type `@` first. /// ///E.g, if you typed ///```dart ///@lucky| ///``` ///the search context is activated and `lucky` is sent as the search query. /// ///But if you continue with a terminating character like so: ///```dart ///@lucky | ///``` ///the search context is exited and the overlay is dismissed. /// ///However, if the text is edited to bring the cursor back to /// ///```dart ///@luck| ///``` ///the search context is entered again and the text after the `@` is ///sent as the search query. /// ///Returns `false` when a search query is found from back tracking. ///Otherwise, returns `true`. bool _backtrackAndSearch() { String text = controller.text; if (!text.contains("@")) return true; final length = controller.selection.base.offset - 1; late String temp = ""; for (int i = length; i >= 0; i--) { if (i == length && text[i] == "@") return true; if (!_regExp.hasMatch(text[i]) && text[i] != "@") return true; temp = text[i] + temp; if (text[i] == "@" && temp.length > 1) { _shouldSearch = true; _isTagSelected = false; _extractAndSearch(controller.text, length); return false; } } _lastCachedText = controller.text; return true; } ///Shifts cursor to end of tagged user name ///when an attempt to edit one is made. /// ///This shift of the cursor allows the next backbutton press from the ///same position to trigger the selection (and removal on next press) ///of the tagged user. void _shiftCursorForTaggedUser() { String text = controller.text; if (!text.contains("@")) return; final length = controller.selection.base.offset - 1; late String temp = ""; for (int i = length; i >= 0; i--) { if (i == length && text[i] == "@") { temp = "@"; break; } temp = text[i] + temp; if (text[i] == "@" && temp.length > 1) break; } if (temp.isEmpty) return; for (var user in _taggedUsers.keys) { if (user.contains(temp)) { final names = user.split(" "); if (names.length != 2) return; int offset = length + names.last.length + (names.first.length - temp.length + 1) + 1; if (offset > text.length) { offset = text.length; } if (text.substring(length + 1, offset).trim().contains(names.last)) { _defer = true; controller.selection = TextSelection.fromPosition( TextPosition(offset: offset), ); return; } } } } ///Listener attached to [controller] to listen for change in ///search context and tagged user selection. /// ///Triggers search: ///Starts the search context when last entered character is `@`. /// ///Ends Search: ///Exits search context and hides overlay when a terminating character ///not matched by [_regExp] is entered. void _tagListener() { if (_defer) { _defer = false; return; } final text = controller.text; if (text.isEmpty && _selectedTag.isNotEmpty) { _removeSelection(); } //When a previously selected tag is unselected without removing //reset tag selection values if (_startOffset != null && controller.selection.base.offset != _startOffset) { _selectedTag = ""; _startOffset = null; _endOffset = null; _isTagSelected = false; } late final position = controller.selection.base.offset - 1; if (_shouldSearch && position != text.length - 1 && text.contains("@")) { _extractAndSearch(text, position); return; } if (_lastCachedText == text) { _shiftCursorForTaggedUser(); widget.onFormattedTextChanged(_formattedText); return; } if (_lastCachedText.trim().length > text.trim().length) { if (_removeEditedTags()) { _shouldHideOverlay(true); widget.onFormattedTextChanged(_formattedText); return; } _shiftCursorForTaggedUser(); final hideOverlay = _backtrackAndSearch(); if (hideOverlay) _shouldHideOverlay(true); widget.onFormattedTextChanged(_formattedText); return; } _lastCachedText = text; if (text[position] == "@") { _shouldSearch = true; widget.onFormattedTextChanged(_formattedText); return; } if (!_regExp.hasMatch(text[position])) { _shouldSearch = false; } if (_shouldSearch) { _extractAndSearch(text, position); } else { _shouldHideOverlay(true); } widget.onFormattedTextChanged(_formattedText); } ///Extract text appended to the last `@` symbol found in [text] ///or the substring of [text] up until [position] if [position] is not null ///and performs a user search. void _extractAndSearch(String text, int endOffset) { try { int index = text.substring(0, endOffset).lastIndexOf("@"); if (index < 0) return; final userName = text.substring( index + 1, endOffset + 1, ); if (userName.isNotEmpty) _search(userName); } catch (e, trace) { debugPrint("$trace"); } } @override void initState() { super.initState(); controller.addListener(_tagListener); } @override void dispose() { controller.removeListener(_tagListener); _overlayEntry?.remove(); super.dispose(); } @override Widget build(BuildContext context) { widget.onCreate?.call(() { _shouldHideOverlay(true); }); return widget.builder(context, _containerKey); } } class _UserListView extends StatelessWidget { final Function(String, String) tagUser; final VoidCallback onClose; const _UserListView({ Key? key, required this.tagUser, required this.onClose, }) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 2), decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black.withOpacity(.2), offset: const Offset(0, -5), blurRadius: 10, ), ], ), child: Material( color: Colors.transparent, child: ValueListenableBuilder<bool>( valueListenable: _searchViewModel.loading, builder: (_, loading, __) { return ValueListenableBuilder<List<User>>( valueListenable: _searchViewModel.users, builder: (_, users, __) { if (loading && users.isEmpty) { return const Center( child: LoadingWidget(), ); } return Column( children: [ Align( alignment: Alignment.centerRight, child: IconButton( onPressed: onClose, icon: const Icon(Icons.close), ), ), if (users.isEmpty) const Center(child: Text("No user found")) else Expanded( child: ListView.builder( padding: EdgeInsets.zero, itemCount: users.length, itemBuilder: (_, index) { final user = users[index]; return ListTile( leading: Container( height: 50, width: 50, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( image: NetworkImage(user.avatar), ), ), ), title: Text(user.fullName), subtitle: Text("@${user.userName}"), onTap: () { tagUser(user.userName, user.id); }, ); }, ), ), ], ); }); }), ), ); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/widgets/loading_indicator.dart
import 'package:flutter/cupertino.dart'; class LoadingWidget extends StatelessWidget { const LoadingWidget({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ Text( "Loading", ), SizedBox(width: 10), CupertinoActivityIndicator(radius: 10), ], ); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/widgets/custom_text_field.dart
import 'package:flutter/material.dart'; class CustomTextField extends StatelessWidget { final TextEditingController? controller; final FocusNode? focusNode; final String? hint; final Widget? suffix; const CustomTextField({ Key? key, this.controller, this.focusNode, this.hint, this.suffix, }) : super(key: key); @override Widget build(BuildContext context) { return TextFormField( controller: controller, focusNode: focusNode, style: const TextStyle( color: Colors.black, fontWeight: FontWeight.w400, fontSize: 16, ), cursorColor: Colors.redAccent, decoration: InputDecoration( suffixIcon: suffix, hintText: hint, hintStyle: const TextStyle( color: Colors.blueGrey, fontWeight: FontWeight.w400, fontSize: 14, ), border: OutlineInputBorder( borderSide: const BorderSide( color: Colors.pinkAccent, ), borderRadius: BorderRadius.circular(30), ), enabledBorder: OutlineInputBorder( borderSide: const BorderSide( color: Colors.pinkAccent, ), borderRadius: BorderRadius.circular(30), ), disabledBorder: OutlineInputBorder( borderSide: const BorderSide( color: Colors.pinkAccent, ), borderRadius: BorderRadius.circular(30), ), focusedBorder: OutlineInputBorder( borderSide: const BorderSide( color: Colors.pinkAccent, ), borderRadius: BorderRadius.circular(30), ), ), ); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/widgets/custom_text.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:linkify/linkify.dart'; import 'package:url_launcher/url_launcher.dart'; class CustomText extends StatelessWidget { final String text; final double? fontSize; final Color? textColor; final int maxTextLength; final VoidCallback? onSuffixPressed; final bool showAllText; final String suffix; final String? parentText; final TextStyle? parentTextStyle; final VoidCallback? onParentPressed; final Function(String)? onUserTagPressed; CustomText({ Key? key, required this.text, this.maxTextLength = 300, this.showAllText = false, this.suffix = "Show more", this.fontSize, this.onSuffixPressed, this.parentText, this.parentTextStyle, this.textColor, this.onParentPressed, this.onUserTagPressed, }) : _suffix = "...$suffix", _text = text.trim(), _fontSize = fontSize ?? 14, super(key: key); final double _fontSize; final String _text; final String _suffix; late final List<TextSpan> _spans = []; int _length = 0; TextSpan _copyWith(TextSpan span, {String? text}) { return TextSpan( style: span.style, recognizer: span.recognizer, children: span.children, text: text ?? span.text, ); } int get _maxTextLength { if (showAllText) return _text.length; return maxTextLength; } void _addText(TextSpan span) { if (_length >= _maxTextLength) { if (_spans.isNotEmpty && _spans.last.text == _suffix) { return; } if (span.text!.length > _maxTextLength) { _spans.add( _copyWith( span, text: text.substring(0, _maxTextLength), ), ); } else { _spans.add(span); } if (_length > maxTextLength) { _spans.add( TextSpan( text: _suffix, style: const TextStyle(color: Colors.pink), recognizer: TapGestureRecognizer()..onTap = onSuffixPressed, ), ); } return; } _spans.add(span); } bool _isEmail(String? email) { if (email != null) { String p = "[a-zA-Z0-9\+\.\_\%\-\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+"; return RegExp(p).hasMatch(email); } return false; } TextSpan get _parsedTextSpan { final elements = linkify( _text, options: const LinkifyOptions( removeWww: true, looseUrl: true, ), linkifiers: [ const UrlLinkifier(), CustomUserTagLinkifier(), ], ); for (var element in elements) { _length += element.text.length; if (element is UrlElement) { _addText( TextSpan( text: element.text, style: TextStyle( fontWeight: FontWeight.w400, fontSize: _fontSize, color: Colors.pinkAccent, ), recognizer: TapGestureRecognizer() ..onTap = () async { final isEmail = _isEmail(element.text); if (isEmail) { await launchUrl(Uri.parse("mailto:${element.text}")); } else { await launchUrl(Uri.parse(element.url)); } }, ), ); } else if (element is CustomUserTagElement) { _addText( TextSpan( text: element.name, style: TextStyle( fontWeight: FontWeight.w400, fontSize: _fontSize, color: Colors.pinkAccent, ), recognizer: TapGestureRecognizer() ..onTap = () { onUserTagPressed?.call(element.userId); }, ), ); } else { _addText( TextSpan( text: element.text, style: TextStyle( fontWeight: FontWeight.w400, fontSize: _fontSize, color: textColor ?? Colors.black.withOpacity(.8), ), ), ); } } if (showAllText && _length > maxTextLength && _spans.isNotEmpty && _spans.last.text != _suffix) { _spans.add( TextSpan( text: _suffix, style: const TextStyle(color: Colors.pink), recognizer: TapGestureRecognizer()..onTap = onSuffixPressed, ), ); } return TextSpan(children: _spans); } @override Widget build(BuildContext context) { TextSpan child = _parsedTextSpan; if (parentText != null) { child = TextSpan( text: parentText, style: parentTextStyle, children: [child], recognizer: TapGestureRecognizer()..onTap = onParentPressed, ); } return RichText( text: child, ); } } class CustomUserTagLinkifier extends Linkifier { ///This matches any string in this format ///"@{userId}#{userName}#" final _userTagRegex = RegExp(r'^(.*?)(\@.\w+\#..+?\#)'); @override List<LinkifyElement> parse( List<LinkifyElement> elements, LinkifyOptions options, ) { final list = <LinkifyElement>[]; for (var element in elements) { if (element is TextElement) { final match = _userTagRegex.firstMatch(element.text); if (match == null) { list.add(element); } else { final text = element.text.replaceFirst(match.group(0)!, ''); if (match.group(1)?.isNotEmpty == true) { list.add(TextElement(match.group(1)!)); } if (match.group(2)?.isNotEmpty == true) { final blob = match.group(2)!.split("#"); list.add( CustomUserTagElement( userId: blob.first.replaceAll( "@", "", ), name: "@${blob[1]}", ), ); } if (text.isNotEmpty) { list.addAll(parse([TextElement(text)], options)); } } } else { list.add(element); } } return list; } } class CustomUserTagElement extends LinkableElement { final String userId; final String name; CustomUserTagElement({required this.userId, required this.name}) : super(userId, name); @override String toString() { return "CustomUserTagElement: '$userId' ($name)"; } @override bool operator ==(other) => equals(other); @override bool equals(other) => other is CustomUserTagElement && super.equals(other) && other.userId == userId && other.name == name; }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/view_models/search_view_model.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/models/user.dart'; class SearchViewModel { late final ValueNotifier<List<User>> _users = ValueNotifier([]); ValueNotifier<List<User>> get users => _users; late final ValueNotifier<bool> _loading = ValueNotifier(false); ValueNotifier<bool> get loading => _loading; void _setLoading(bool val) { if (val != _loading.value) { _loading.value = val; } } Future<void> search(String query) async { if (query.isEmpty) return; query = query.toLowerCase().trim(); _users.value = []; _users.notifyListeners(); _setLoading(true); await Future.delayed(const Duration(milliseconds: 250)); final result = User.allUsers .where( (user) => user.userName.toLowerCase().contains(query) || user.fullName.toLowerCase().contains(query), ) .toList(); _users.value = result; _users.notifyListeners(); _setLoading(false); } }
0
mirrored_repositories/user_tag_demo/lib/views
mirrored_repositories/user_tag_demo/lib/views/view_models/home_view_model.dart
import 'package:flutter/material.dart'; import 'package:user_tag_demo/models/post.dart'; import 'package:user_tag_demo/models/user.dart'; class HomeViewModel { final ValueNotifier<List<Post>> _posts = ValueNotifier(Post.posts); ValueNotifier<List<Post>> get posts => _posts; void addPost(String caption) { if (caption.isEmpty) return; final post = Post( caption: caption, poster: User.anon(), time: "now", ); _posts.value.add(post); _posts.notifyListeners(); } }
0
mirrored_repositories/user_tag_demo/lib
mirrored_repositories/user_tag_demo/lib/models/user.dart
class User { final String id; final String userName; final String fullName; final String avatar; User({ required this.id, required this.userName, required this.fullName, required this.avatar, }); factory User.lucky() => User( id: "63a27531b866ce0016f9e582", fullName: "Lucky Ebere", userName: "crazelu", avatar: "https://github.githubassets.com/images/modules/profile/achievements/quickdraw-default.png", ); factory User.brad() => User( id: "11a27531b866ce0016f9e582", fullName: "Brad Francis", userName: "brad", avatar: "https://avatars.githubusercontent.com/u/45284758?v=4", ); factory User.sharky() => User( id: "69a12531b866ce0016f9h082", fullName: "Tom Hanks", userName: "sharky", avatar: "https://github.githubassets.com/images/modules/profile/achievements/pull-shark-default.png", ); factory User.billy() => User( id: "69a48531n066ce0016f9h082", fullName: "Vecna Finn", userName: "billy", avatar: "https://github.githubassets.com/images/modules/profile/achievements/yolo-default.png", ); factory User.lyon() => User( id: "69a48531n066cekk16f9h082", fullName: "Russel Van", userName: "lyon", avatar: "https://avatars.githubusercontent.com/u/26209401?s=64&v=4", ); factory User.aurora() => User( id: "08a98331b866ce0017k9h082", fullName: "Aurora Peters", userName: "aurora", avatar: "https://github.githubassets.com/images/modules/profile/achievements/arctic-code-vault-contributor-default.png", ); factory User.anon() => User( id: "69a00531b866ce0017k9h082", fullName: "Anonymous User", userName: "anon", avatar: "https://github.githubassets.com/images/modules/profile/achievements/pair-extraordinaire-default.png", ); static List<User> allUsers = [ User.lucky(), User.anon(), User.billy(), User.sharky(), User.lyon(), User.aurora(), User.brad(), ]; }
0
mirrored_repositories/user_tag_demo/lib
mirrored_repositories/user_tag_demo/lib/models/post.dart
import 'package:user_tag_demo/models/user.dart'; class Post { final String caption; final User poster; final String time; Post({ required this.caption, required this.poster, required this.time, }); static List<Post> posts = [ Post( caption: "Hi @63a27531b866ce0016f9e582#crazelu#. Please call me", poster: User.billy(), time: "2 days ago", ), Post( caption: "@69a12531b866ce0016f9h082#sharky#,@69a48531n066ce0016f9h082#billy# you're gonna want to visit me now", poster: User.lucky(), time: "2 days ago", ), Post( caption: "Hey guys. I'm new here", poster: User.brad(), time: "2 days ago", ), Post( caption: "Y'all should check my twitter https://twitter.com/ebere_lucky. S/O to @08a98331b866ce0017k9h082#aurora# and @11a27531b866ce0016f9e582#brad#. Real OGs", poster: User.lucky(), time: "2 days ago", ), Post( caption: "Why should I visit you 😏 @63a27531b866ce0016f9e582#crazelu# SMH", poster: User.sharky(), time: "1 day ago", ), ]; }
0
mirrored_repositories/user_tag_demo
mirrored_repositories/user_tag_demo/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:user_tag_demo/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:mobile_app/screens/login_signup.dart'; import 'package:mobile_app/database/storage.dart'; import 'package:mobile_app/utilities/globals.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. Map<int, Color> color = { 50 :Color.fromRGBO(45, 30, 64, .1), 100:Color.fromRGBO(45, 30, 64, .2), 200:Color.fromRGBO(45, 30, 64, .3), 300:Color.fromRGBO(45, 30, 64, .4), 400:Color.fromRGBO(45, 30, 64, .5), 500:Color.fromRGBO(45, 30, 64, .6), 600:Color.fromRGBO(45, 30, 64, .7), 700:Color.fromRGBO(45, 30, 64, .8), 800:Color.fromRGBO(45, 30, 64, .9), 900:Color.fromRGBO(45, 30, 64, 1), }; //MaterialColor colorCustom = MaterialColor(0xFF880E4F, MyApp().color); @override Widget build(BuildContext context) { return MaterialApp( title: 'Phy', theme: ThemeData( /*cursorColor: Colors.red, cupertinoOverrideTheme: CupertinoThemeData( primaryColor: Colors.red, ),*/ //DON'T REMOVE I AM KEEPING THIS FOR LATER primarySwatch: Colors.deepPurple, // bottomAppBarColor: colorCustom, ), home: LoginSignUpPage(title: 'Login and Signup'), ); } }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/utilities/toast.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; const Color primaryColor = const Color(0xff2D1E40); void displayToast(String msg) { Fluttertoast.showToast( msg: msg, backgroundColor: Colors.white, textColor: primaryColor, toastLength: Toast.LENGTH_SHORT, ); }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/utilities/helpful_methods.dart
import 'package:url_launcher/url_launcher.dart'; void launchURLWithoutCheck(String url) async { print(url); await launch(url); }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/utilities/globals.dart
import 'package:firebase_storage/firebase_storage.dart'; import 'package:mobile_app/database/storage.dart'; class Constants{ static const String SignOut = 'Sign out'; static const List<String> choices = <String>[ SignOut ]; } class GlobalVars { static int selectedCourseIndex = 0; static List<String> courses = <String>['GCSE O Levels','GCSE A Levels','IGCSE O Levels','IGCSE A Levels','Edexcel','IB MYP', 'IB DP']; static List<String> resources = ['Syllabus','Past Papers','Worksheets','Video Lectures','Quizzes']; static List<String> pastPaperYears = ['2018','2017','2016', '2015','2014','2013','2012','2011', '2010']; static List<String> chapters = ['Units and Measurements','Force','Magnetism','Gravitation','Work, Energy and Power', 'Thermodynamics','Matter','Kinetic Theory','Oscillations','Waves']; } class GlobalPastPaperData { static Map<String, List<List<String>>> yearValuesMap = Map(); static List<int> pastPaperCounts = []; static Future<void> loadData(String selectedCourse) async { final FileStorage _storage = FileStorage(); yearValuesMap = await _storage.getPastPaperURLsAndNames(selectedCourse); for (int i = 0; i < GlobalVars.pastPaperYears.length; i++) { String year = GlobalVars.pastPaperYears[i]; dynamic value = yearValuesMap[year]; List<String> names = value[1]; pastPaperCounts.add(names.length); } } } class GlobalQuizData { static Map<String, List<List<String>>> chapterValuesMap = Map(); static List<int> quizCounts = []; static Future<void> loadData(String selectedCourse) async { final FileStorage _storage = FileStorage(); chapterValuesMap = await _storage.getQuizzesURLsAndNames(selectedCourse); for (int i = 0; i < GlobalVars.chapters.length; i++) { String chapter = GlobalVars.chapters[i]; dynamic value = chapterValuesMap[chapter]; List<String> names = value[1]; quizCounts.add(names.length); } } } class GlobalWorksheetData { static Map<String, List<List<String>>> chapterValuesMap = Map(); static List<int> worksheetCounts = []; static Future<void> loadData(String selectedCourse) async { final FileStorage _storage = FileStorage(); chapterValuesMap = await _storage.getWorksheetsURLsAndNames(selectedCourse); for (int i = 0; i < GlobalVars.chapters.length; i++) { String chapter = GlobalVars.chapters[i]; dynamic value = chapterValuesMap[chapter]; List<String> names = value[1]; worksheetCounts.add(names.length); } } } class GlobalSyllabusData { static String syllabusURL; static Future<void> loadData(String selectedCourse) async { final FileStorage _storage = FileStorage(); syllabusURL = await _storage.getSyllabusURL(selectedCourse); } } class ConstantsforSearch{ static const String Save = 'Save'; static const List<String> choices = <String>[ Save ]; } class Post { final String title; final String links; final String types; Post(this.title , this.types, this.links); }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/utilities/navigation.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:mobile_app/database/auth.dart'; import 'package:mobile_app/utilities/globals.dart'; import 'package:mobile_app/utilities/helpful_methods.dart'; import '../screens/student_view/syllabus.dart'; import '../screens/home_page.dart'; import 'package:mobile_app/screens/student_view/past_papers.dart'; import 'package:mobile_app/screens/student_view/quiz.dart'; import 'package:mobile_app/screens/student_view/syllabus.dart'; import 'package:mobile_app/screens/student_view/video_lectures.dart'; import 'package:mobile_app/screens/student_view/worksheets.dart'; Future navigateToHomePage(context) async { Navigator.push(context, MaterialPageRoute(builder:(context) => MyHomePage( title: 'Main Skeleton' ), ) ); } Future navigateToResourceView(context, String selectedResource, String selectedCourse) async { switch (selectedResource) { case 'Syllabus': print('navigating to syllabus'); /*Navigator.push(context, MaterialPageRoute(builder:(context)=> Syllabus() ), );*/ await GlobalSyllabusData.loadData(selectedCourse); launchURLWithoutCheck(GlobalSyllabusData.syllabusURL); break; case 'Past Papers' : print('navigating to past papers'); await GlobalPastPaperData.loadData(selectedCourse); Navigator.push(context, MaterialPageRoute(builder:(context)=> PastPapersStudentsView() ), ); break; case 'Worksheets' : print('navigating to worksheets'); await GlobalWorksheetData.loadData(selectedCourse); Navigator.push(context, MaterialPageRoute(builder:(context)=> WorksheetStudentsView() ), ); break; case 'Video Lectures' : print('navigating to video lectures'); Navigator.push(context, MaterialPageRoute(builder:(context)=> VideoLecturesStudentsView() ), ); break; case 'Quizzes' : print('navigating to quizzes'); await GlobalQuizData.loadData(selectedCourse); Navigator.push(context, MaterialPageRoute(builder:(context)=> QuizStudentsView() ), ); break; default: print('error: no valid resource selected'); break; } } Future navigateBack(context) async { Navigator.pop(context); } Future navigateToStartPage(context) async { // get currently logged in user final AuthService _auth = AuthService(); User user = _auth.currentUser; GoogleSignIn googleSignIn = _auth.googleSignIn; // google sign in or email sign in? String loginType = user.providerData[0].providerId; // email sign out if (loginType == 'password') { print('signing out with email'); _auth.signOut(); } // google sign out else if (loginType == 'google.com') { print('signing out with google'); googleSignIn.signOut(); } // go back to first screen Navigator.popUntil(context, ModalRoute.withName('/')); }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/database/auth.dart
import 'package:google_sign_in/google_sign_in.dart'; import 'package:firebase_auth/firebase_auth.dart'; class AuthService { final FirebaseAuth _auth = FirebaseAuth.instance; final GoogleSignIn googleSignIn = GoogleSignIn(); // get current signed in user User get currentUser { return _auth.currentUser; } // check if user is the teacher bool isUserTeacher() { String email = this.currentUser.email; print('email'); return email == 'ivyphysicsapp.gmail.com'; } // sign in anonymously Future signInAnon() async { try { UserCredential result = await _auth.signInAnonymously(); User user = result.user; return user; } catch (e) { print(e.toString()); return null; } } // sign in with email and password Future signInWithEmailAndPassword(String email, String password) async { try { UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password); User user = result.user; return user; } catch(e) { print(e.toString()); return null; } } // register with email and password Future registerWithEmailAndPassword(String email, String password) async { try { UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password); User user = result.user; return user; } catch(e) { print(e.toString()); return null; } } // sign out Future signOut() async { try { return await _auth.signOut(); } catch(e) { print(e.toString()); return null; } } // request new password Future resetPassword(String email) async { try { return await _auth.sendPasswordResetEmail(email: email); } catch (e) { print(e.toString()); return null; } } // google sign in Future signInWithGoogle() async { dynamic user; dynamic googleSignInAccount = await googleSignIn.signIn(); if (googleSignInAccount != null) { final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); try { final UserCredential userCredential = await _auth.signInWithCredential(credential); user = userCredential.user; } on FirebaseAuthException catch(e) { print(e.toString()); if (e.code == 'account-exists-with-different-credential') { } if (e.code == 'invalid-credential') { } return null; } catch (e) { print(e.toString()); return null; } } return user; } // google sign out Future signOutWithGoogle() async { try { return await googleSignIn.signOut(); } catch(e) { print(e.toString()); return null; } } // change password Future updatePassword(String pass) async { try { User user = _auth.currentUser; return await user.updatePassword(pass); } catch (e) { print(e.toString()); return null; } } }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/database/storage.dart
import 'dart:math'; import 'dart:io'; import 'package:mobile_app/utilities/globals.dart'; import 'package:path/path.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:file_picker/file_picker.dart'; class FileStorage { final FirebaseStorage _storage = FirebaseStorage.instance; Future uploadFile() async { FilePickerResult result = await FilePicker.platform.pickFiles(); File file = File(result.files.single.path); String filename = basename(file.path); String url = this.savePDF(file, filename) as String; } Future savePDF(File pdfFile, String filename) async { try { Reference ref = _storage.ref().child('any').child(filename); UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'application/pdf')); TaskSnapshot snapshot = await uploadTask; String url = await snapshot.ref.getDownloadURL(); print("URL of uploaded file is: $url"); return url; } catch (e) { print(e.toString()); return null; } } Future<int> getNumberOfItems() async { final Reference ref = _storage.ref().child('any'); dynamic result = await ref.listAll(); var resultItems = result.items; return resultItems.length; } Future<Map<String, List<List<String>>>> getPastPaperURLsAndNames(String selectedCourse) async { final Reference ref = _storage.ref().child(selectedCourse).child('past_papers'); Map<String, List<List<String>>> yearValuesMap = Map(); for (int i = 0; i < GlobalVars.pastPaperYears.length; i++) { String year = GlobalVars.pastPaperYears[i]; Reference ref2 = ref.child(year); List <String> listOfAllURLs = []; List <String> fileNames = []; dynamic res = await ref2.listAll().then( (result) async { var resultItems = result.items; for (int i = 0; i< resultItems.length; i++){ var item = resultItems[i]; dynamic downloadUrl = await item.getDownloadURL(); String url = downloadUrl.toString(); String name = item.name; listOfAllURLs.add(url); fileNames.add(name); //print('Added $url to list of all urls'); } List<List<String>> results = []; results.add(listOfAllURLs); results.add(fileNames); return results; } ); yearValuesMap[year] = res; } //print(yearValuesMap); return yearValuesMap; } Future<Map<String, List<List<String>>>> getQuizzesURLsAndNames(String selectedCourse) async { final Reference ref = _storage.ref().child(selectedCourse).child('quizzes'); Map<String, List<List<String>>> chapterValuesMap = Map(); for (int i = 0; i < GlobalVars.chapters.length; i++) { String chapter = GlobalVars.chapters[i]; Reference ref2 = ref.child(chapter); List <String> listOfAllURLs = []; List <String> fileNames = []; dynamic res = await ref2.listAll().then( (result) async { var resultItems = result.items; for (int i = 0; i< resultItems.length; i++){ var item = resultItems[i]; dynamic downloadUrl = await item.getDownloadURL(); String url = downloadUrl.toString(); String name = item.name; listOfAllURLs.add(url); fileNames.add(name); //print('Added $url to list of all urls'); } List<List<String>> results = []; results.add(listOfAllURLs); results.add(fileNames); return results; } ); chapterValuesMap[chapter] = res; } //print(yearValuesMap); return chapterValuesMap; } Future<Map<String, List<List<String>>>> getWorksheetsURLsAndNames(String selectedCourse) async { final Reference ref = _storage.ref().child(selectedCourse).child('worksheets'); Map<String, List<List<String>>> chapterValuesMap = Map(); for (int i = 0; i < GlobalVars.chapters.length; i++) { String chapter = GlobalVars.chapters[i]; Reference ref2 = ref.child(chapter); List <String> listOfAllURLs = []; List <String> fileNames = []; dynamic res = await ref2.listAll().then( (result) async { var resultItems = result.items; for (int i = 0; i< resultItems.length; i++){ var item = resultItems[i]; dynamic downloadUrl = await item.getDownloadURL(); String url = downloadUrl.toString(); String name = item.name; listOfAllURLs.add(url); fileNames.add(name); //print('Added $url to list of all urls'); } List<List<String>> results = []; results.add(listOfAllURLs); results.add(fileNames); return results; } ); chapterValuesMap[chapter] = res; } //print(yearValuesMap); return chapterValuesMap; } Future<String> getSyllabusURL(String selectedCourse) async { final Reference ref = _storage.ref().child(selectedCourse).child('syllabus'); dynamic res = await ref.listAll().then( (result) async { var resultItems = result.items; String url = ''; for (int i = 0; i < resultItems.length; i++){ var item = resultItems[i]; dynamic downloadUrl = await item.getDownloadURL(); url = downloadUrl.toString(); } return url; } ); return res; } Future<void> getVideoLinks(String selectedCourse) async { //DocumentReference docRef = FirebaseFirestore.instance.collection(selectedCourse).document(); } }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/home_page.dart
import 'dart:ffi'; import 'package:flappy_search_bar/flappy_search_bar.dart'; import 'package:flappy_search_bar/search_bar_style.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:flutter/services.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:mobile_app/utilities/navigation.dart'; import 'package:mobile_app/utilities/globals.dart'; import 'package:mobile_app/database/auth.dart'; import 'package:mobile_app/utilities/toast.dart'; class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { int _currentindex = 0; int _childcount = 5; var appbartitletext = 'Home'; Size size ; int tapped_index = 0;//for course selection in the home page static const Color primaryColor = const Color(0xff2D1E40); static const Color primarylightColor = const Color(0x4DE3CBED); static const Color primaryhighlightColor = Colors.greenAccent; // for the drawer and its listview List<String> courses = GlobalVars.courses; int get childcountnum{ return _childcount; } set childcountnum(int x) { _childcount = x; _changecountofhomeoptions(x); } void _changeAppBarTitle(int x) { setState(() { if (x == 0 ){ appbartitletext = 'Home'; } if (x == 1 ){ appbartitletext = 'Search'; } if (x == 2 ){ appbartitletext = 'Library'; } if (x == 3 ){ appbartitletext = 'Settings'; } }); } void _changecountofhomeoptions(int x) { setState(() { _childcount = x; }); } void _updateSize(Size x) { setState(() { size = x ; }); } // This is for the sign out button, you can add the code here for signing out void choiceAction(String choice){ if(choice == Constants.SignOut){ print('SignOut'); navigateToStartPage(context); } } //USED IN THE HOME DRAWER void updateSelectedofDrawerList(int ind){ setState(() { tapped_index = ind; GlobalVars.selectedCourseIndex = tapped_index; }); } @override Widget build(BuildContext context) { Size nsize = MediaQuery.of(context).size; _updateSize(nsize); return Scaffold( resizeToAvoidBottomInset: false, //Disabling drawer on search and settings tab drawerEdgeDragWidth: ((_currentindex == 0 || _currentindex == 2 )) ? nsize.width : 0, appBar: AppBar( centerTitle: true, title: Text(appbartitletext, style: TextStyle( color: Colors.white, ), ), backgroundColor: primaryColor, backwardsCompatibility: false, systemOverlayStyle:SystemUiOverlayStyle.dark.copyWith(statusBarIconBrightness: Brightness.light , ), actions: <Widget>[ PopupMenuButton<String>( color: Colors.white, icon: Icon(Icons.more_vert, color: Colors.white, ), onSelected: choiceAction, itemBuilder: (BuildContext context){ return Constants.choices.map((String choice){ return PopupMenuItem<String>( value: choice, child: Text(choice), ); }).toList(); }, ) ], leading: Builder( builder: (BuildContext context) { if ((_currentindex == 0 || _currentindex == 2 )) { return IconButton( icon: const Icon(Icons.menu, color: Colors.white, ), onPressed: () { Scaffold.of(context).openDrawer(); }, tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip, ); } else { return new Container(width: 0, height: 0); } }, ), ), body: //tabs[_currentindex], _currentindex == 0 ? MyHomeLayout() : _currentindex == 1 ? MySearchLayout() : _currentindex == 2 ? MySavedLayout() : MySettingsLayout(), drawer: Container( //width: 200, decoration: BoxDecoration( color: primaryColor, ), child: Drawer( child: ListView( // Important: Remove any padding from the ListView. padding: EdgeInsets.zero, //shrinkWrap: true, children: <Widget>[ Container( height: 200.0, padding: EdgeInsets.zero, decoration: BoxDecoration( //color: primarylightColor color: const Color(0x8CE3CBED), ), child : DrawerHeader( //padding: EdgeInsets.zero, decoration: BoxDecoration( color: primaryColor, image: DecorationImage( image: (_currentindex == 0) ? AssetImage("images/vector-formidable-forest-illustration.jpg"): AssetImage("images/Sunset_Forest_Landscape_Illustration_generated.jpg"), colorFilter: new ColorFilter.mode(Colors.blue.withOpacity(0.7), BlendMode.dstATop), fit: BoxFit.cover, ), //borderRadius: BorderRadius.only( // topRight: Radius.circular(20), // ), ), child: Column( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Text('Courses', style: TextStyle( color: Colors.white, fontSize: 25, ), textAlign: TextAlign.center, ), ] ), ), ), SingleChildScrollView( physics: ScrollPhysics(), child : Container( height: (nsize.height/ 12)* (courses.length + 2), // Giving the box dynamic height, 12 fields fit in the screen color: primarylightColor, child : Column( children: <Widget>[ Expanded( child: SizedBox( height: (nsize.height/ 12), child: new ListView.builder( padding: EdgeInsets.zero, physics: NeverScrollableScrollPhysics(), shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: courses.length, itemBuilder: (BuildContext context, int index) { return new ListTile( selected : (index == tapped_index) ? true : false , selectedTileColor: (index % 2 == 0) ? Colors.purpleAccent : Colors.lightBlueAccent, tileColor: (index % 2 == 0) ? primarylightColor :const Color(0x998ECFE1), title: Text(courses[index], style: TextStyle( fontSize: 18, color: Colors.black, ), textAlign: TextAlign.center, ), trailing: (index == tapped_index) ? Icon(Icons.arrow_right, color: Colors.black, size: 40, ): Icon(Icons.arrow_drop_down, color: Colors.black, size: 40, ), onTap: () { updateSelectedofDrawerList(index); }, ); }, ), ), ), ], ), ), ), ], ), ), ), bottomNavigationBar: BottomNavigationBar( currentIndex: _currentindex, showUnselectedLabels: false, showSelectedLabels: false, iconSize: 20, type: BottomNavigationBarType.fixed, backgroundColor: primaryColor, selectedItemColor: primaryhighlightColor, unselectedItemColor: Colors.white, items: [ BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.home), title : Text('Home'), ), BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.search), title : Text('Search'), ), BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.bookmark), title : Text('Library'), ), BottomNavigationBarItem( icon: FaIcon(FontAwesomeIcons.cog), title : Text('Settings'), ), ], onTap:(index){ setState(() { _currentindex = index; _changeAppBarTitle(index); }); } , ) // This trailing comma makes auto-formatting nicer for build methods. ); } } class MyHomeLayout extends StatefulWidget { MyHomeLayout({Key key, this.title}) : super(key: key); final String title; @override _HomeLayoutState createState() => _HomeLayoutState(); } class _HomeLayoutState extends State<MyHomeLayout> { int homeButtonIndex; //For the Home page var button_name = GlobalVars.resources; List<IconData> icons = [Icons.description_outlined ,Icons.library_books_outlined,Icons.assignment_outlined,Icons.videocam_outlined,Icons.fact_check_outlined]; //USED FOR HOME PAGE void updateHomeIndex(int ind){ setState(() { homeButtonIndex = ind; }); } @override Widget build(BuildContext context) { return Center ( child : Scaffold( backgroundColor: _MyHomePageState.primarylightColor, body: Center( child: CustomScrollView( slivers: <Widget>[ SliverPadding( padding: EdgeInsets.fromLTRB(15, 15, 15, 15), sliver :SliverGrid( delegate: SliverChildBuilderDelegate( (context, index) { return ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.purple[100 * (index % 9 + 1)], onPrimary: Colors.white, onSurface: Colors.greenAccent, padding: EdgeInsets.only(right:10.0,left: 10, top:10.0, bottom: 10.0), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ), ), onPressed: () { updateHomeIndex(index); print('selected index:'); print(index); String selectedResource = GlobalVars.resources[index]; String selectedCourse = GlobalVars.courses[GlobalVars.selectedCourseIndex]; print('selected resource: ' + selectedResource); print('selected course: ' + selectedCourse); navigateToResourceView(context, selectedResource, selectedCourse); }, child: Column ( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(icons[index], size: 60, color: (index == homeButtonIndex ) ? _MyHomePageState.primaryhighlightColor: Colors.white, ), const SizedBox(height: 5), Text(button_name[index], textDirection: TextDirection.ltr, style: TextStyle( fontSize: 13, color: (index == homeButtonIndex ) ? _MyHomePageState.primaryhighlightColor: Colors.white, ), ), ] ), ) ; }, childCount: _MyHomePageState().childcountnum, ), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 15, crossAxisSpacing: 15, childAspectRatio: 1.0, ), ), ), ], ), ), floatingActionButton:FloatingActionButton( backgroundColor: _MyHomePageState.primaryColor, foregroundColor: Colors.white, onPressed: () { // Respond to button press //Have to deal with additional code here and then obv designs will get back to ou about it // _MyHomePageState()._changecountofhomeoptions(_MyHomePageState().childcountnum + 1); }, child: Icon(Icons.add), ), ), ); } } class MySearchLayout extends StatefulWidget { MySearchLayout({Key key, this.title}) : super(key: key); final String title; @override _SearchLayoutState createState() => _SearchLayoutState(); } class _SearchLayoutState extends State<MySearchLayout> { // This is for the sign out button, you can add the code here for signing out void choiceAction(String choice){ if(choice == ConstantsforSearch.Save){ print('Save'); navigateToStartPage(context); } } void _launchURL(_url) async => await canLaunch(_url) ? await launch(_url) : throw 'Could not launch $_url'; Future<List<Post>> search(String search) async { await Future.delayed(Duration(seconds: 2)); if (search == "empty") return []; if (search == "error") throw Error(); return List.generate(search.length,(int index) { return Post( "Title : $search $index", "Type : Past Papers", "https://api.flutter.dev/flutter/material/ListTile-class.html", ); }); } @override Widget build(BuildContext context) { Size sssize = MediaQuery.of(context).size; return Scaffold( resizeToAvoidBottomInset: false, body: SafeArea( child: Container ( decoration: BoxDecoration( border: Border.all(color: Colors.black), image: new DecorationImage( alignment: Alignment.bottomLeft, fit: BoxFit.fitWidth, colorFilter: new ColorFilter.mode(const Color(0xff4D2EA6).withOpacity(0.2), BlendMode.overlay), image: AssetImage("images/Search Background3.png"), ), gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment(0.2, 0.3), //colors: [const Color(0xffE4EDF0),Colors.purple] colors: [const Color(0xffE4EDF0),const Color(0xff4D2EA6)] ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: SearchBar<Post>( searchBarStyle: SearchBarStyle( backgroundColor: Colors.white, padding: EdgeInsets.all(0), borderRadius: BorderRadius.circular(20), ), hintText: 'Type here to search', hintStyle: TextStyle( color: Colors.grey[400], ), mainAxisSpacing: 10, crossAxisSpacing: 10, minimumChars: 1, loader: const Center(child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(Colors.greenAccent))), iconActiveColor: _MyHomePageState.primaryhighlightColor , icon: Padding( padding: const EdgeInsetsDirectional.only(start: 12.0), child: Icon(Icons.search), // myIcon is a 48px-wide widget. ), onSearch: search, onItemFound: (Post post, int index) { return Container ( decoration: BoxDecoration( border: Border.all(color: Colors.black), ), child: ListTile( leading : ( post.types == "Type : Past Papers" ) ? Icon(Icons.library_books_outlined, color: Colors.black, size: 30,) : ( post.types == "Type : Syllabus" ) ? Icon(Icons.description_outlined, color: Colors.black, size: 30,): ( post.types == "Type : Worksheets" ) ? Icon(Icons.assignment_outlined, color: Colors.black, size: 30,): ( post.types == "Type : Video Lectures" ) ? Icon(Icons.videocam_outlined,color: Colors.black, size: 30,): Icon(Icons.fact_check_outlined,color: Colors.black, size: 30,), tileColor: const Color(0xffE3CBED), //_MyHomePageState.primarylightColor , trailing: Padding( padding: const EdgeInsets.symmetric(vertical: 0.0), child: PopupMenuButton<String>( color: Colors.white, icon: Icon(Icons.more_vert, color: Colors.black, ), onSelected: choiceAction, itemBuilder: (BuildContext context){ return ConstantsforSearch.choices.map((String choice){ return PopupMenuItem<String>( value: choice, child: Text(choice), ); }).toList(); }, ) ), title: Text(post.title, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, ), ), isThreeLine:true, //selected: true, selectedTileColor: Colors.purpleAccent, subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(post.types, style: TextStyle( color: Colors.black, ), ), GestureDetector( child: Text(post.links, style: TextStyle( color: Colors.blueAccent, ), ), onTap: () { print("Lets Load the Link!"); _launchURL(post.links); }, ), ], ), ), ); }, onError: (error) { return Center( //child: Text("Error occurred : $error"),//I AM KEEPING THIS FOR YOU IN CASE YOU WANT TO DISPLAY ANYTHING HERE //WITH A VARIABLE (FOR SANA) child: Text("No results found."), ); }, emptyWidget: Center( child: Text("Enter something to search."), ), ), ), ), ), ); } } class MySavedLayout extends StatefulWidget { MySavedLayout({Key key, this.title}) : super(key: key); final String title; @override _SavedLayoutState createState() => _SavedLayoutState(); } class _SavedLayoutState extends State<MySavedLayout> { int homeButtonIndex; //For the Home page var button_name = ['Syllabus','Past Papers','Worksheets','Video Lectures','Quizzes']; List<IconData> icons = [Icons.description_outlined ,Icons.library_books_outlined,Icons.assignment_outlined,Icons.videocam_outlined,Icons.fact_check_outlined]; //USED FOR HOME PAGE void updateHomeIndex(int ind){ setState(() { homeButtonIndex = ind; }); } @override Widget build(BuildContext context) { return Center ( child : Scaffold( backgroundColor: _MyHomePageState.primarylightColor, body: Center( child: CustomScrollView( slivers: <Widget>[ SliverPadding( padding: EdgeInsets.fromLTRB(15, 15, 15, 15), sliver :SliverGrid( delegate: SliverChildBuilderDelegate( (context, index) { return ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.blue[100 * (index % 9 + 3)], onPrimary: Colors.white, onSurface: Colors.greenAccent, padding: EdgeInsets.only(right:10.0,left: 10, top:10.0, bottom: 10.0), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ), ), onPressed: () { updateHomeIndex(index); }, child: Column ( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(icons[index], size: 60, color: (index == homeButtonIndex ) ? _MyHomePageState.primaryhighlightColor: Colors.white, ), const SizedBox(height: 5), Text(button_name[index], textDirection: TextDirection.ltr, style: TextStyle( fontSize: 13, color: (index == homeButtonIndex ) ? _MyHomePageState.primaryhighlightColor: Colors.white, ), ), ] ), ) ; }, childCount: _MyHomePageState().childcountnum, ), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 15, crossAxisSpacing: 15, childAspectRatio: 1.0, ), ), ), ], ), ), ), ); } } class MySettingsLayout extends StatefulWidget { MySettingsLayout({Key key, this.title}) : super(key: key); final String title; @override _SettingsLayoutState createState() => _SettingsLayoutState(); } class _SettingsLayoutState extends State<MySettingsLayout> { final _formKey = GlobalKey<FormState>(); final AuthService _auth = AuthService(); Size size ; int eyeicon1 = 1; int eyeicon2 = 1; String _newpass = ''; String _confirmpass = ''; void _updateSize(Size x) { setState(() { size = x ; }); } void _updateeyeicon1() { if (eyeicon1 == 1){ setState(() { eyeicon1 = 0 ; });} else if (eyeicon1 == 0){ setState(() { eyeicon1 = 1 ; });} print(eyeicon1); } void _updateeyeicon2() { if (eyeicon2 == 1) setState(() { eyeicon2 = 0 ; }); else if (eyeicon2 == 0) setState(() { eyeicon2 = 1 ; }); } @override Widget build(BuildContext context) { Size sssize = MediaQuery.of(context).size; _updateSize(sssize); return Scaffold ( resizeToAvoidBottomInset: false, body : Center( child : Stack(children: <Widget>[ Container( //padding: EdgeInsets.only(top:100.0), height: sssize.height, decoration: BoxDecoration(color:Colors.white, //const Color(0xffE4EDF0),// image: new DecorationImage( alignment: Alignment.bottomLeft, fit: BoxFit.fitWidth, //colorFilter: new ColorFilter.mode(Colors.purple.withOpacity(0.1), BlendMode.srcOver), image: AssetImage("images/Free Caribou Vector 02.jpg"), ), ), ), Positioned( child :Align( alignment: Alignment.bottomCenter, child: Container( height: sssize.height/2 -86, alignment: Alignment.bottomCenter, decoration: BoxDecoration( color: Colors.white, gradient: LinearGradient( begin: FractionalOffset.topCenter, end: FractionalOffset.bottomCenter, colors: [ Colors.white.withOpacity(1.0), Colors.transparent, ], stops: [ 0.0, 1.0 ])), ), ),), SingleChildScrollView( child: Stack(children: <Widget>[ Center( child : Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ const SizedBox(height: 136,), Container( //color: Colors.white, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10) ), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), spreadRadius: 8, blurRadius: 7, offset: Offset(0, 3), // changes position of shadow ), ], ), child: Padding( padding: EdgeInsets.only(left:20.0,right: 20.0,top:40 , bottom: 20,), child: Form( autovalidateMode: AutovalidateMode.onUserInteraction, key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( //textAlign: TextAlign.center, style: TextStyle(fontSize: 15.0, color: const Color(0xff2D1E40)), cursorColor: const Color(0xff2D1E40), decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.greenAccent, width: 2.5), ), errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), borderRadius: BorderRadius.circular(10), ), fillColor: const Color(0x40576681), //filled: true, //isDense: true, prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.person, color: const Color(0xff2D1E40), size: 20,), ), hintText: _auth.currentUser.email, // email of signed in user enabled: false, // user cannot edit their email hintStyle: TextStyle( fontSize: 15, color: const Color(0xff2D1E40), ), ), ), ), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( validator: (val) => val.length < 6 ? 'Enter a password 6+ characters long' : null, onChanged: (val) { setState(() => _newpass = val); print(_newpass); }, //textAlign: TextAlign.center, style: TextStyle(fontSize: 15.0, color: const Color(0xff2D1E40)), cursorColor: const Color(0xff2D1E40), obscureText: (eyeicon1 == 1) ? true : false, decoration: InputDecoration( errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), borderRadius: BorderRadius.circular(10), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.greenAccent, width: 2.5), ), prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.lock, color: const Color(0xff2D1E40), size: 20,), ), suffixIcon: Padding( padding: EdgeInsets.only(right: 15.0), child: IconButton( color: const Color(0xff2D1E40), iconSize: 20, onPressed: (){ print(eyeicon1); _updateeyeicon1(); }, icon: (eyeicon1 == 1) ? Icon(Icons.visibility,) : Icon(Icons.visibility_off,), ),), hintText: 'New Password', hintStyle: TextStyle( fontSize: 15, color: const Color(0xff2D1E40), ), ), ), ), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( validator: (val) => val != _newpass ? 'Passwords should match' : null, onChanged: (val) { setState(() => _confirmpass = val); print(_confirmpass); }, //textAlign: TextAlign.center, style: TextStyle(fontSize: 15.0, color: const Color(0xff2D1E40)), cursorColor: const Color(0xff2D1E40), obscureText: (eyeicon2 == 1) ? true : false, decoration: InputDecoration( errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), borderRadius: BorderRadius.circular(10), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.greenAccent, width: 2.5), ), prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.lock, color: const Color(0xff2D1E40), size: 20,), ), suffixIcon: Padding( padding: EdgeInsets.only(right: 15.0), child: IconButton( color: const Color(0xff2D1E40), iconSize: 20, onPressed: (){ _updateeyeicon2(); }, icon: (eyeicon2 == 1 ) ? Icon(Icons.visibility,) : Icon(Icons.visibility_off,), ),), hintText: 'Confirm Password', hintStyle: TextStyle( fontSize: 15, color: const Color(0xff2D1E40), ), ), ), ), const SizedBox(height: 17), ElevatedButton( style: ElevatedButton.styleFrom( primary: const Color(0xff2D1E40), onPrimary: Colors.white, onSurface: Colors.grey, padding: EdgeInsets.only(right:50.0,left: 50, top:10.0, bottom: 10.0), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ), ), onPressed: () async { if (_formKey.currentState.validate()) { dynamic result = _auth.updatePassword(_newpass); if (result != null) { print('password changed'); // display toast message displayToast('Password change successful'); } else { displayToast('Password change unsuccessful'); } } }, child: Text('Change Password', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 15, color:Colors.white, ), ), ), ] ), ), ), ), ], ), ), Center( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ // Padding( // padding: EdgeInsets.only(bottom:20.0), // child: const SizedBox(height: 40), Text( 'My Account', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 20, color: _MyHomePageState.primaryColor, ), ), //), //Padding( //padding: EdgeInsets.only(bottom:335.0), // child: const SizedBox(height: 18), Icon( FontAwesomeIcons.solidUserCircle, color: const Color(0xff2D1E40), size: 90, ), // ), ] ), ), ), ], ), ), ], ), ), ); } }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/login_signup.dart
import 'package:flappy_search_bar/flappy_search_bar.dart'; import 'package:flappy_search_bar/search_bar_style.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:flutter/services.dart'; import 'package:mobile_app/database/storage.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:mobile_app/database/auth.dart'; import 'package:mobile_app/utilities/toast.dart'; import 'home_page.dart'; import 'package:mobile_app/utilities/navigation.dart'; class LoginSignUpPage extends StatefulWidget { LoginSignUpPage({Key key, this.title}) : super(key: key); final String title; @override _LoginSignUpPageState createState() => _LoginSignUpPageState(); } class _LoginSignUpPageState extends State<LoginSignUpPage> with SingleTickerProviderStateMixin { final AuthService _auth = AuthService(); final _formKey = GlobalKey<FormState>(); bool _loading = false; String _email = ''; String _password = ''; String _msg = ''; static const Color primaryColor = const Color(0xff2D1E40); static const Color primarylightColor = const Color(0x4DE3CBED); static const Color primaryhighlightColor = Colors.greenAccent; int eyeicon1 = 1; int eyeicon2 = 1; void _updateeyeicon1() { if (eyeicon1 == 1){ setState(() { eyeicon1 = 0 ; });} else if (eyeicon1 == 0){ setState(() { eyeicon1 = 1 ; });} print(eyeicon1); } void _updateeyeicon2() { if (eyeicon2 == 1) setState(() { eyeicon2 = 0 ; }); else if (eyeicon2 == 0) setState(() { eyeicon2 = 1 ; }); } TabController _controller; var _controller2 ; void initState() { super.initState(); _controller = new TabController(length: 2, vsync: this); _controller2 = TextEditingController(); } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Scaffold( body: Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( height: 290, decoration: BoxDecoration( color:primaryColor, image: DecorationImage( image: AssetImage("images/T_9-01.jpg"), colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.8), BlendMode.dstATop), fit: BoxFit.cover, ), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: EdgeInsets.only(top:95.0), child: Text( 'Phy', textDirection: TextDirection.ltr, style: TextStyle( fontFamily: "kg-legacy-of-virtue", fontSize: 60, color: Colors.white, ), ), ), Padding( padding: EdgeInsets.only(top:8.0,bottom: 60), child: Text( //'GCSE O Levels | GCSE A Levels | Edexcel', 'A Walkthrough Physics', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 16, color:const Color(0x99E3CBED) ), ), ), ], ), ), ), Container( decoration: BoxDecoration(color: primaryColor), child: TabBar( labelColor: primaryhighlightColor, unselectedLabelColor: Colors.white, indicatorColor:primaryhighlightColor, controller:_controller, tabs: [ new Tab( text: 'Login', ), new Tab( text: 'Sign up', ), ], ), ), Container( height: 345.0, decoration: BoxDecoration(color: Colors.white), child: Form( autovalidateMode: AutovalidateMode.onUserInteraction, key: _formKey, child: TabBarView( controller:_controller, children: [ //LOGIN TAB Container( decoration: BoxDecoration(color: primarylightColor), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ const SizedBox(height: 30), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( validator: (val) => val.isEmpty || !val.contains("@") ? 'Enter a valid email' : null, onChanged: (val) { setState(() => _email = val); print(_email); }, //textAlign: TextAlign.center, style: TextStyle(fontSize: 15.0, color: primaryColor), cursorColor: primaryColor, decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: primaryhighlightColor, width: 2.5), ), errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), borderRadius: BorderRadius.circular(10) ), fillColor: const Color(0x40576681), //filled: true, //isDense: true, prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.person, color: primaryColor, size: 20,), ), hintText: 'Your Email', hintStyle: TextStyle( fontSize: 15, color: primaryColor, ), ), ), ), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( validator: (val) => val.length < 6 ? 'Enter a password 6+ characters long' : null, onChanged: (val) { setState(() => _password = val); print(_password); }, //textAlign: TextAlign.center, style: TextStyle(fontSize: 15.0, color: primaryColor), cursorColor: primaryColor, obscureText: (eyeicon1 == 1) ? true : false, decoration: InputDecoration( errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), borderRadius: BorderRadius.circular(10) ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color:primaryhighlightColor, width: 2.5), ), prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.lock, color: primaryColor, size: 20,), ), suffixIcon: Padding( padding: EdgeInsets.only(right: 15.0), child: IconButton( color: primaryColor, iconSize: 20, onPressed: (){ print('Pressed'); _updateeyeicon1(); }, //=> _controller2.clear(), icon: (eyeicon1 == 1) ? Icon(Icons.visibility,) : Icon(Icons.visibility_off,), ),), hintText: 'Your Password', hintStyle: TextStyle( fontSize: 15, color: primaryColor, ), ), ), ), const SizedBox(height: 17), ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, onPrimary: Colors.white, onSurface: Colors.grey, padding: EdgeInsets.only(right:100.0,left: 100, top:10.0, bottom: 10.0), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ), ), onPressed: () async { if (_formKey.currentState.validate()) { setState(() => _loading = true); dynamic result = await _auth.signInWithEmailAndPassword(_email, _password); if (result == null) { print('unsuccessful sign in'); setState(() { _loading = false; _msg = 'Invalid email or password'; }); } else { setState(() { _loading = false; _msg = 'Signing in'; }); } print(_msg); // display toast message displayToast(_msg); if (result != null) { navigateToHomePage(context); } } }, child: Text('Login', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 15, color:Colors.white, ), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: EdgeInsets.only(top:0.0), child: Text( 'Trouble signing in? ', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 12, color: Colors.black, ), ), ), TextButton( style: TextButton.styleFrom( primary: primaryhighlightColor, onSurface: Colors.blueAccent, padding: EdgeInsets.only(right:0.0,left: 0), ), child: Text('Forgot Password',textDirection: TextDirection.ltr, style: TextStyle( fontSize: 12, color: primaryColor, decoration: TextDecoration.underline ), ), onPressed: () async { print('forgot password pressed'); // need an email if (_email.isEmpty || !_email.contains('@')) { setState(() { _msg = 'Provide an email'; }); } // test out the email else { dynamic result = await _auth.resetPassword(_email); // if reset password failed if (result == null) { setState(() { _msg = 'Password Reset Unsuccessful'; }); } // if successful else { setState(() { _msg = 'Password Reset Email Sent'; }); } } // display confirmation / warning message displayToast(_msg); } ) ], ), ] ), ), ), //SIGN UP TAB Container( decoration: BoxDecoration(color:primarylightColor), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ const SizedBox(height: 30), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( validator: (val) => val.isEmpty || !val.contains("@") ? 'Enter a valid email' : null, onChanged: (val) { setState(() => _email = val); print(_email); }, //textAlign: TextAlign.center, style: TextStyle(fontSize: 15.0, color: primaryColor), cursorColor: primaryColor, decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: primaryhighlightColor, width: 2.5), ), errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), ), fillColor: const Color(0x40576681), //filled: true, //isDense: true, prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.person, color: primaryColor, size: 20,), ), hintText: 'Your Email', hintStyle: TextStyle( fontSize: 15, color: primaryColor, ), ), ), ), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 50), child: TextFormField( validator: (val) => val.length < 5 ? 'Enter a password 6+ characters long' : null, onChanged: (val) { setState(() => _password = val); print(_password); }, //textAlign: TextAlign.center, controller: _controller2, style: TextStyle(fontSize: 15.0, color: primaryColor), cursorColor: primaryColor, obscureText: (eyeicon2 == 1) ? true : false, decoration: InputDecoration( focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: primaryhighlightColor, width: 2.5), ), errorBorder: new UnderlineInputBorder( borderSide: new BorderSide(color: Colors.redAccent, width: 2.5), ), prefixIcon: Padding( padding: EdgeInsets.only(left: 30.0, right: 10.0), child: Icon( Icons.lock, color: primaryColor, size: 20,), ), suffixIcon: Padding( padding: EdgeInsets.only(right: 15.0), child: IconButton( color: primaryColor, iconSize: 20, onPressed: (){ print('Pressed'); _updateeyeicon2(); }, //=> _controller2.clear(), icon: (eyeicon2 == 1) ? Icon(Icons.visibility,) : Icon(Icons.visibility_off,), ),), hintText: 'Your Password', hintStyle: TextStyle( fontSize: 15, color: primaryColor, ), ), ), ), const SizedBox(height: 17), ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, onPrimary: Colors.white, onSurface: Colors.grey, padding: EdgeInsets.only(right:100.0,left: 100, top:10.0, bottom: 10.0), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ), ), // sign up button onPressed: () async { if (_formKey.currentState.validate()) { dynamic result = await _auth.registerWithEmailAndPassword(_email, _password); if (result == null) { print('unsuccessful sign up'); setState(() { _msg = 'Sign up unsuccessful'; }); } else { setState(() { _msg = 'Sign up successful'; }); } print(_msg); displayToast(_msg); } }, child: Text('Sign up', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 15, color:Colors.white, ), ), ), const SizedBox(height: 17), Text( '__________________ OR __________________ ', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 12, color: Colors.black, ), ), const SizedBox(height: 10), ConstrainedBox( constraints: BoxConstraints.tightFor(width: 250, height: 40), child:ElevatedButton( style: ElevatedButton.styleFrom( primary: const Color(0xffC94130), onPrimary: Colors.white, onSurface: Colors.grey, padding: EdgeInsets.only(right:30.0,left: 0.0, top:10.0, bottom: 10.0), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ), ), // sign up with google onPressed: () async { dynamic result = await _auth.signInWithGoogle(); if (result == null) { print('sign in with google unsuccessful'); } else { print('sign in with google successful'); navigateToHomePage(context); } }, child: Row( // Replace with a Row for horizontal icon + text mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Icon(FontAwesomeIcons.google, size: 20,), Text('Sign in with Google', textDirection: TextDirection.ltr, style: TextStyle( fontSize: 15, color:Colors.white, ), ), ], ), ), ), ] ), ), ), ], ), ), ), ], ), ), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/student_view/video_lectures.dart
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/material/theme.dart'; import 'package:mobile_app/utilities/globals.dart'; import 'package:mobile_app/utilities/navigation.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:flutter/cupertino.dart'; //import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart'; //================================================================================================================================ //===============================================VIDEO LECTURE==================================================================== //================================================================================================================================ class VideoLecturesStudentsView extends StatelessWidget { static const Color primaryColor = const Color(0xff2D1E40); Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( scaffoldBackgroundColor: Colors.white, primaryColor: Colors.white, ), home: Scaffold( appBar: new AppBar( elevation: 0, backgroundColor: Colors.white, //leading: IconButton(icon: Icon(Icons.menu_outlined ,color: Colors.deepPurple,), onPressed: () {},), leading: IconButton( icon: Icon(Icons.arrow_back_ios_sharp, color: primaryColor,), onPressed: (){ navigateBack(context); }, ), title: Text("Lecture Videos ",style: TextStyle(color: primaryColor), ), ), body: Center( child: MyStatefulWidgetVLSW(), ), ), ); } } // stores ExpansionPanel state information class ItemVLSV { ItemVLSV({ this.expandedValue, this.headerValue, this.isExpanded = false, }); int expandedValue; String headerValue; bool isExpanded; } List<ItemVLSV> generateItemVLSV(int numberOfItems) //VLSV = video lecture student view { List<int> lectures =[3,4,2,3,4,5,3,4,3,5]; List<String> Chapters = GlobalVars.chapters; return List<ItemVLSV>.generate(numberOfItems, (int index) { return ItemVLSV( headerValue: Chapters[index], expandedValue: lectures[index], ); }); } class MyStatefulWidgetVLSW extends StatefulWidget { MyStatefulWidgetVLSW({Key key}) : super(key: key); @override _MyStatefulWidgetStateVLSW createState() => _MyStatefulWidgetStateVLSW(); } /// This is the private State class that goes with MyStatefulWidget. class _MyStatefulWidgetStateVLSW extends State<MyStatefulWidgetVLSW> { static const Color primaryColor = const Color(0xff2D1E40); var LectNum = 0; final List<ItemVLSV> _data = generateItemVLSV(10); List<bool> selected = List<bool>.generate(10, (int index) => false); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( color: Colors.white, child: _buildPanel(), ), ); } Widget _buildPanel() { return ExpansionPanelList( expansionCallback: (int index, bool isExpanded) { setState(() { _data[index].isExpanded = !isExpanded; }); }, children: _data.map<ExpansionPanel>((ItemVLSV item) { return ExpansionPanel( headerBuilder: (BuildContext context, bool isExpanded) { return Container( margin: EdgeInsets.all(16), child: Stack( children: <Widget>[ Card( shadowColor: Colors.blueGrey[600], elevation: 12, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), color: primaryColor, child: Container( padding: const EdgeInsets.symmetric( horizontal: 18.0, vertical: 18), decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), color: primaryColor, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ SizedBox( width: 16, height: 30, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(item.headerValue, style: TextStyle(color: Colors.white)), ], ), ), ], ), ), ), ], ), ); }, body: ListViewTilesVLSV('https://www.youtube.com/watch?v=OOMxU9f1FBU',item.expandedValue), isExpanded: item.isExpanded, ); }).toList(), ); } } //for list view class ListViewTilesVLSV extends StatelessWidget{ void _launchURL(_url) async { if (await canLaunch(_url)){ await launch(_url); } else { throw 'Could not launch $_url';} //_launchURL(text); } String text; int numLect; ListViewTilesVLSV(this.text,this.numLect); @override Widget build(BuildContext context) { return ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: numLect, itemBuilder: (context,index){ return ListTile( //tileColor: Colors.lightBlueAccent[700], selectedTileColor: Colors.grey[400], leading: Icon(Icons.arrow_right_outlined), title: Text("lecture $index",style: TextStyle( fontSize: 18.0, ),), onTap: () { _launchURL(text); } , ); }, ); } } //================================================================================================================================ //===============================================VIDEO LECTURE END================================================================ //================================================================================================================================
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/student_view/generated_plugin_registrant.dart
// // Generated file. Do not edit. // // ignore_for_file: lines_longer_than_80_chars import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { UrlLauncherPlugin.registerWith(registrar); registrar.registerMessageHandler(); }
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/student_view/quiz.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/material/theme.dart'; import 'package:mobile_app/utilities/globals.dart'; import 'package:mobile_app/utilities/helpful_methods.dart'; import 'package:mobile_app/utilities/navigation.dart'; import 'package:url_launcher/url_launcher.dart'; //import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart'; //================================================================================================================================ //===============================================QUIZ============================================================================= //================================================================================================================================ class QuizStudentsView extends StatelessWidget { static const Color primaryColor = const Color(0xff2D1E40); Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( scaffoldBackgroundColor: Colors.white, primaryColor: Colors.white, ), home: Scaffold( appBar: new AppBar( elevation: 0, backgroundColor: Colors.white, //leading: IconButton(icon: Icon(Icons.menu_outlined ,color: Colors.deepPurple,), onPressed: () {},), leading: IconButton( icon: Icon(Icons.arrow_back_ios_sharp, color: primaryColor,), onPressed: (){ navigateBack(context); }, ), title: Text("Quizzes ",style: TextStyle(color: primaryColor), ), ), body: Center( child: MyStatefulWidgetQSW(), ), ), ); } } // stores ExpansionPanel state information class ItemQSV { ItemQSV({ this.expandedValue, this.headerValue, this.isExpanded = false, }); int expandedValue; String headerValue; bool isExpanded; } List<ItemQSV> generateItemQSV(int numberOfItems) //VLSV = video lecture student view { List<int> lectures =[3,4,2,3,4,5,3,4,3,5]; List<String> Chapters = GlobalVars.chapters; List<int> noQuizzes = GlobalQuizData.quizCounts; return List<ItemQSV>.generate(numberOfItems, (int index) { return ItemQSV( headerValue: Chapters[index], expandedValue: noQuizzes[index], ); }); } class MyStatefulWidgetQSW extends StatefulWidget { MyStatefulWidgetQSW({Key key}) : super(key: key); @override _MyStatefulWidgetStateQSW createState() => _MyStatefulWidgetStateQSW(); } /// This is the private State class that goes with MyStatefulWidget. class _MyStatefulWidgetStateQSW extends State<MyStatefulWidgetQSW> { static const Color primaryColor = const Color(0xff2D1E40); var LectNum = 0; final List<ItemQSV> _data = generateItemQSV(GlobalVars.chapters.length); List<bool> selected = List<bool>.generate(GlobalVars.chapters.length, (int index) => false); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( color: Colors.white, child: _buildPanel(), ), ); } Widget _buildPanel() { return ExpansionPanelList( expansionCallback: (int index, bool isExpanded) { setState(() { _data[index].isExpanded = !isExpanded; }); }, children: _data.map<ExpansionPanel>((ItemQSV item) { return ExpansionPanel( headerBuilder: (BuildContext context, bool isExpanded) { return Container( margin: EdgeInsets.all(16), child: Stack( children: <Widget>[ Card( shadowColor: Colors.blueGrey[600], elevation: 12, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), color: primaryColor, child: Container( padding: const EdgeInsets.symmetric( horizontal: 18.0, vertical: 18), decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), color: primaryColor, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ SizedBox( width: 16, height: 30, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(item.headerValue, style: TextStyle(color: Colors.white)), ], ), ), ], ), ), ), ], ), ); }, body: ListViewTilesQSV('https://www.youtube.com/watch?v=OOMxU9f1FBU',item.expandedValue, item.headerValue), isExpanded: item.isExpanded, ); }).toList(), ); } } //for list view class ListViewTilesQSV extends StatelessWidget { String text; int numLect; String chapter; ListViewTilesQSV(this.text,this.numLect, this.chapter); Map<String, List<List<String>>> chapterValuesMap = GlobalQuizData.chapterValuesMap; String getName(int index) { dynamic value = chapterValuesMap[chapter]; List<String> names = value[1]; return names[index]; } String getURL(int index) { dynamic value = chapterValuesMap[chapter]; List<String> urls = value[0]; return urls[index]; } @override Widget build(BuildContext context) { return ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: numLect, itemBuilder: (context,index){ return ListTile( //tileColor: Colors.lightBlueAccent[700], selectedTileColor: Colors.grey[400], leading: Icon(Icons.arrow_right_outlined), title: Text(getName(index), style: TextStyle( fontSize: 18.0, ),), onTap: () { launchURLWithoutCheck(getURL(index)); } , ); }, ); } } //================================================================================================================================ //===============================================QUIZ END========================================================================= //================================================================================================================================
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/student_view/past_papers.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:mobile_app/database/storage.dart'; import 'package:mobile_app/utilities/globals.dart'; import 'package:mobile_app/utilities/helpful_methods.dart'; import 'package:mobile_app/utilities/navigation.dart'; import 'package:url_launcher/url_launcher.dart'; //import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart'; //================================================================================================================================ //===============================================PAST PAPERS====================================================================== //================================================================================================================================ class PastPapersStudentsView extends StatelessWidget { static const Color primaryColor = const Color(0xff2D1E40); Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( scaffoldBackgroundColor: Colors.white, primaryColor: Colors.white, ), home: Scaffold( appBar: new AppBar( elevation: 0, backgroundColor: Colors.white, //leading: IconButton(icon: Icon(Icons.menu_outlined ,color: Colors.deepPurple,), onPressed: () {},), leading: IconButton( icon: Icon(Icons.arrow_back_ios_sharp, color: primaryColor,), onPressed: (){ navigateBack(context); }, ), title: Text("Past Papers ",style: TextStyle(color: primaryColor), ), ), body: Center( child: MyStatefulWidgetPPSW(), ), ), ); } } // stores ExpansionPanel state information class ItemPPSV { ItemPPSV({ this.expandedValue, this.headerValue, this.isExpanded = false, }); int expandedValue; String headerValue; bool isExpanded; } List<ItemPPSV> generateItemPPSV(int numberOfItems) //VLSV = video lecture student view { List<int> lectures =[4,4,2,3,4,5,3,4,3,5]; List<String> pastPaperYears = GlobalVars.pastPaperYears; List<int> noPastPapers = GlobalPastPaperData.pastPaperCounts; return List<ItemPPSV>.generate(numberOfItems, (int index) { return ItemPPSV( headerValue: pastPaperYears[index], expandedValue: noPastPapers[index], ); }); } class MyStatefulWidgetPPSW extends StatefulWidget { MyStatefulWidgetPPSW({Key key}) : super(key: key); @override _MyStatefulWidgetStatePPSW createState() => _MyStatefulWidgetStatePPSW(); } /// This is the private State class that goes with MyStatefulWidget. class _MyStatefulWidgetStatePPSW extends State<MyStatefulWidgetPPSW> { static const Color primaryColor = const Color(0xff2D1E40); var LectNum = 0; final List<ItemPPSV> _data = generateItemPPSV(GlobalVars.pastPaperYears.length); List<bool> selected = List<bool>.generate(GlobalVars.pastPaperYears.length, (int index) => false); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( color: Colors.white, child: _buildPanel(), ), ); } Widget _buildPanel() { return ExpansionPanelList( expansionCallback: (int index, bool isExpanded) { setState(() { _data[index].isExpanded = !isExpanded; }); }, children: _data.map<ExpansionPanel>((ItemPPSV item) { return ExpansionPanel( headerBuilder: (BuildContext context, bool isExpanded) { return Container( margin: EdgeInsets.all(16), child: Stack( children: <Widget>[ Card( shadowColor: Colors.blueGrey[600], elevation: 12, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), color: primaryColor, child: Container( padding: const EdgeInsets.symmetric( horizontal: 18.0, vertical: 18), decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), color: primaryColor, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ SizedBox( width: 16, height: 30, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(item.headerValue, style: TextStyle(color: Colors.white)), ], ), ), ], ), ), ), ], ), ); }, body: ListViewTilesPPSV('https://www.youtube.com/watch?v=OOMxU9f1FBU',item.expandedValue, item.headerValue), isExpanded: item.isExpanded, ); }).toList(), ); } } //for list view class ListViewTilesPPSV extends StatelessWidget { String text; int numLect; String year; ListViewTilesPPSV(this.text,this.numLect, this.year); Map<String, List<List<String>>> yearValuesMap = GlobalPastPaperData.yearValuesMap; String getName(int index) { dynamic value = yearValuesMap[year]; List<String> names = value[1]; return names[index]; } String getURL(int index) { dynamic value = yearValuesMap[year]; List<String> urls = value[0]; return urls[index]; } @override Widget build(BuildContext context) { return ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: numLect, itemBuilder: (context,index){ return ListTile( //tileColor: Colors.lightBlueAccent[700], selectedTileColor: Colors.grey[400], leading: Icon(Icons.arrow_right_outlined), title: Text(getName(index), style: TextStyle( fontSize: 18.0, ), ), onTap: () { launchURLWithoutCheck(getURL(index)); } , ); }, ); } } //================================================================================================================================ //===============================================PAST PAPERS END================================================================== //================================================================================================================================
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/student_view/syllabus.dart
//================================================================================================== //=================================FOR THE STUDENT VIEW============================================= //================================================================================================== import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/material/theme.dart'; import 'package:mobile_app/utilities/navigation.dart'; import 'package:url_launcher/url_launcher.dart'; //import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart'; //================================================================================================================================ //===============================================SYLLABUS BEGIN=========================================================== //================================================================================================================================ class Syllabus extends StatelessWidget { static const Color primaryColor = const Color(0xff2D1E40); Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( scaffoldBackgroundColor: Colors.white, primaryColor: Colors.white, ), home: Scaffold( appBar: new AppBar( elevation: 0, backgroundColor: Colors.white, //leading: IconButton(icon: Icon(Icons.menu_outlined ,color: Colors.deepPurple,), onPressed: () {},), leading: IconButton( icon: Icon(Icons.arrow_back_ios_sharp, color: primaryColor,), onPressed: (){ navigateBack(context); }, ), title: Text("Syllabus ",style: TextStyle(color: primaryColor), ), ), body: Center( child: syllabusPage(), ), ), ); } } class syllabusPage extends StatefulWidget { @override syllabusPageState createState() => syllabusPageState(); } class syllabusPageState extends State<syllabusPage> { @override @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( color: Colors.white, ), ); } } //================================================================================================================================ //===============================================SYLLABUS BEGIN END=========================================================== //================================================================================================================================
0
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens
mirrored_repositories/PHY---A-Walkthrough-Physics-E-Learning-Mobile-App/Source Code/screens/student_view/worksheets.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/src/foundation/key.dart'; import 'package:flutter/src/material/theme.dart'; import 'package:mobile_app/utilities/globals.dart'; import 'package:mobile_app/utilities/helpful_methods.dart'; import 'package:mobile_app/utilities/navigation.dart'; import 'package:url_launcher/url_launcher.dart'; //import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart'; //================================================================================================================================ //===============================================WORKSHEETS======================================================================= //================================================================================================================================ class WorksheetStudentsView extends StatelessWidget { static const Color primaryColor = const Color(0xff2D1E40); Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( scaffoldBackgroundColor: Colors.white, primaryColor: Colors.white, ), home: Scaffold( appBar: new AppBar( elevation: 0, backgroundColor: Colors.white, //leading: IconButton(icon: Icon(Icons.menu_outlined ,color: Colors.deepPurple,), onPressed: () {},), leading: IconButton( icon: Icon(Icons.arrow_back_ios_sharp, color: primaryColor,), onPressed: (){ navigateBack(context); }, ), title: Text("Work Sheets ",style: TextStyle(color: primaryColor), ), ), body: Center( child: MyStatefulWidgetWSSW(), ), ), ); } } // stores ExpansionPanel state information class ItemWSSV { ItemWSSV({ this.expandedValue, this.headerValue, this.isExpanded = false, }); int expandedValue; String headerValue; bool isExpanded; } List<ItemWSSV> generateItemWSSV(int numberOfItems) //VLSV = video lecture student view { List<int> lectures =[3,4,2,3,4,5,3,4,3,5]; List<String> Chapters = GlobalVars.chapters; List<int> noWorksheets = GlobalWorksheetData.worksheetCounts; return List<ItemWSSV>.generate(numberOfItems, (int index) { return ItemWSSV( headerValue: Chapters[index], expandedValue: noWorksheets[index], ); }); } class MyStatefulWidgetWSSW extends StatefulWidget { MyStatefulWidgetWSSW({Key key}) : super(key: key); @override _MyStatefulWidgetStateWSSW createState() => _MyStatefulWidgetStateWSSW(); } /// This is the private State class that goes with MyStatefulWidget. class _MyStatefulWidgetStateWSSW extends State<MyStatefulWidgetWSSW> { static const Color primaryColor = const Color(0xff2D1E40); var LectNum = 0; final List<ItemWSSV> _data = generateItemWSSV(GlobalVars.chapters.length); List<bool> selected = List<bool>.generate(GlobalVars.chapters.length, (int index) => false); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( color: Colors.white, child: _buildPanel(), ), ); } Widget _buildPanel() { return ExpansionPanelList( expansionCallback: (int index, bool isExpanded) { setState(() { _data[index].isExpanded = !isExpanded; }); }, children: _data.map<ExpansionPanel>((ItemWSSV item) { return ExpansionPanel( headerBuilder: (BuildContext context, bool isExpanded) { return Container( margin: EdgeInsets.all(16), child: Stack( children: <Widget>[ Card( shadowColor: Colors.blueGrey[600], elevation: 12, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), color: primaryColor, child: Container( padding: const EdgeInsets.symmetric( horizontal: 18.0, vertical: 18), decoration: BoxDecoration( borderRadius: BorderRadius.circular(60), color: primaryColor, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ SizedBox( width: 16, height: 30, ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Text(item.headerValue, style: TextStyle(color: Colors.white)), ], ), ), ], ), ), ), ], ), ); }, body: ListViewTilesWSSV('https://www.youtube.com/watch?v=OOMxU9f1FBU',item.expandedValue, item.headerValue), isExpanded: item.isExpanded, ); }).toList(), ); } } //for list view class ListViewTilesWSSV extends StatelessWidget { String text; int numLect; String chapter; ListViewTilesWSSV(this.text,this.numLect, this.chapter); Map<String, List<List<String>>> chapterValuesMap = GlobalWorksheetData.chapterValuesMap; String getName(int index) { dynamic value = chapterValuesMap[chapter]; List<String> names = value[1]; return names[index]; } String getURL(int index) { dynamic value = chapterValuesMap[chapter]; List<String> urls = value[0]; return urls[index]; } @override Widget build(BuildContext context) { return ListView.builder( scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: numLect, itemBuilder: (context,index){ return ListTile( //tileColor: Colors.lightBlueAccent[700], selectedTileColor: Colors.grey[400], leading: Icon(Icons.arrow_right_outlined), title: Text(getName(index), style: TextStyle( fontSize: 18.0, ),), onTap: () { launchURLWithoutCheck(getURL(index)); } , ); }, ); } } //================================================================================================================================ //===============================================WORKSHEETS END=================================================================== //================================================================================================================================
0
mirrored_repositories/trave_tou_app
mirrored_repositories/trave_tou_app/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:tourist_app/application/auth/bloc/auth_bloc.dart'; import 'package:tourist_app/application/trip/bloc/trip_bloc.dart'; import 'package:tourist_app/core/di/di.dart'; import 'package:tourist_app/screens/auth/login.dart'; import 'package:tourist_app/screens/splash/splash.dart'; import 'package:tourist_app/screens/trip/trip_adding.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await configureDependencies(); await Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider<AuthBloc>(create: (context) => getIt<AuthBloc>()), BlocProvider<TripBloc>(create: (context) => getIt<TripBloc>()), ], child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Trave Tou', themeMode: ThemeMode.dark, theme: ThemeData.dark(useMaterial3: true), home: const TripAdding(), ), ); } }
0
mirrored_repositories/trave_tou_app/lib/application/trip
mirrored_repositories/trave_tou_app/lib/application/trip/bloc/trip_state.dart
part of 'trip_bloc.dart'; @freezed class TripState with _$TripState { factory TripState({ required bool isLoading, bool? isAdded, }) = _TripState; factory TripState.initial() { return TripState(isLoading: false); } }
0
mirrored_repositories/trave_tou_app/lib/application/trip
mirrored_repositories/trave_tou_app/lib/application/trip/bloc/trip_event.dart
part of 'trip_bloc.dart'; @freezed class TripEvent with _$TripEvent { const factory TripEvent.createTrip({TripCreateModel? model}) = _CreateTrip; }
0
mirrored_repositories/trave_tou_app/lib/application/trip
mirrored_repositories/trave_tou_app/lib/application/trip/bloc/trip_bloc.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 'trip_bloc.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 _$TripEvent { TripCreateModel? get model => throw _privateConstructorUsedError; @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(TripCreateModel? model) createTrip, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(TripCreateModel? model)? createTrip, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(TripCreateModel? model)? createTrip, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_CreateTrip value) createTrip, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_CreateTrip value)? createTrip, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_CreateTrip value)? createTrip, required TResult orElse(), }) => throw _privateConstructorUsedError; @JsonKey(ignore: true) $TripEventCopyWith<TripEvent> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $TripEventCopyWith<$Res> { factory $TripEventCopyWith(TripEvent value, $Res Function(TripEvent) then) = _$TripEventCopyWithImpl<$Res>; $Res call({TripCreateModel? model}); $TripCreateModelCopyWith<$Res>? get model; } /// @nodoc class _$TripEventCopyWithImpl<$Res> implements $TripEventCopyWith<$Res> { _$TripEventCopyWithImpl(this._value, this._then); final TripEvent _value; // ignore: unused_field final $Res Function(TripEvent) _then; @override $Res call({ Object? model = freezed, }) { return _then(_value.copyWith( model: model == freezed ? _value.model : model // ignore: cast_nullable_to_non_nullable as TripCreateModel?, )); } @override $TripCreateModelCopyWith<$Res>? get model { if (_value.model == null) { return null; } return $TripCreateModelCopyWith<$Res>(_value.model!, (value) { return _then(_value.copyWith(model: value)); }); } } /// @nodoc abstract class _$$_CreateTripCopyWith<$Res> implements $TripEventCopyWith<$Res> { factory _$$_CreateTripCopyWith( _$_CreateTrip value, $Res Function(_$_CreateTrip) then) = __$$_CreateTripCopyWithImpl<$Res>; @override $Res call({TripCreateModel? model}); @override $TripCreateModelCopyWith<$Res>? get model; } /// @nodoc class __$$_CreateTripCopyWithImpl<$Res> extends _$TripEventCopyWithImpl<$Res> implements _$$_CreateTripCopyWith<$Res> { __$$_CreateTripCopyWithImpl( _$_CreateTrip _value, $Res Function(_$_CreateTrip) _then) : super(_value, (v) => _then(v as _$_CreateTrip)); @override _$_CreateTrip get _value => super._value as _$_CreateTrip; @override $Res call({ Object? model = freezed, }) { return _then(_$_CreateTrip( model: model == freezed ? _value.model : model // ignore: cast_nullable_to_non_nullable as TripCreateModel?, )); } } /// @nodoc class _$_CreateTrip implements _CreateTrip { const _$_CreateTrip({this.model}); @override final TripCreateModel? model; @override String toString() { return 'TripEvent.createTrip(model: $model)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_CreateTrip && const DeepCollectionEquality().equals(other.model, model)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(model)); @JsonKey(ignore: true) @override _$$_CreateTripCopyWith<_$_CreateTrip> get copyWith => __$$_CreateTripCopyWithImpl<_$_CreateTrip>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(TripCreateModel? model) createTrip, }) { return createTrip(model); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(TripCreateModel? model)? createTrip, }) { return createTrip?.call(model); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(TripCreateModel? model)? createTrip, required TResult orElse(), }) { if (createTrip != null) { return createTrip(model); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_CreateTrip value) createTrip, }) { return createTrip(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_CreateTrip value)? createTrip, }) { return createTrip?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_CreateTrip value)? createTrip, required TResult orElse(), }) { if (createTrip != null) { return createTrip(this); } return orElse(); } } abstract class _CreateTrip implements TripEvent { const factory _CreateTrip({final TripCreateModel? model}) = _$_CreateTrip; @override TripCreateModel? get model; @override @JsonKey(ignore: true) _$$_CreateTripCopyWith<_$_CreateTrip> get copyWith => throw _privateConstructorUsedError; } /// @nodoc mixin _$TripState { bool get isLoading => throw _privateConstructorUsedError; bool? get isAdded => throw _privateConstructorUsedError; @JsonKey(ignore: true) $TripStateCopyWith<TripState> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $TripStateCopyWith<$Res> { factory $TripStateCopyWith(TripState value, $Res Function(TripState) then) = _$TripStateCopyWithImpl<$Res>; $Res call({bool isLoading, bool? isAdded}); } /// @nodoc class _$TripStateCopyWithImpl<$Res> implements $TripStateCopyWith<$Res> { _$TripStateCopyWithImpl(this._value, this._then); final TripState _value; // ignore: unused_field final $Res Function(TripState) _then; @override $Res call({ Object? isLoading = freezed, Object? isAdded = freezed, }) { return _then(_value.copyWith( isLoading: isLoading == freezed ? _value.isLoading : isLoading // ignore: cast_nullable_to_non_nullable as bool, isAdded: isAdded == freezed ? _value.isAdded : isAdded // ignore: cast_nullable_to_non_nullable as bool?, )); } } /// @nodoc abstract class _$$_TripStateCopyWith<$Res> implements $TripStateCopyWith<$Res> { factory _$$_TripStateCopyWith( _$_TripState value, $Res Function(_$_TripState) then) = __$$_TripStateCopyWithImpl<$Res>; @override $Res call({bool isLoading, bool? isAdded}); } /// @nodoc class __$$_TripStateCopyWithImpl<$Res> extends _$TripStateCopyWithImpl<$Res> implements _$$_TripStateCopyWith<$Res> { __$$_TripStateCopyWithImpl( _$_TripState _value, $Res Function(_$_TripState) _then) : super(_value, (v) => _then(v as _$_TripState)); @override _$_TripState get _value => super._value as _$_TripState; @override $Res call({ Object? isLoading = freezed, Object? isAdded = freezed, }) { return _then(_$_TripState( isLoading: isLoading == freezed ? _value.isLoading : isLoading // ignore: cast_nullable_to_non_nullable as bool, isAdded: isAdded == freezed ? _value.isAdded : isAdded // ignore: cast_nullable_to_non_nullable as bool?, )); } } /// @nodoc class _$_TripState implements _TripState { _$_TripState({required this.isLoading, this.isAdded}); @override final bool isLoading; @override final bool? isAdded; @override String toString() { return 'TripState(isLoading: $isLoading, isAdded: $isAdded)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_TripState && const DeepCollectionEquality().equals(other.isLoading, isLoading) && const DeepCollectionEquality().equals(other.isAdded, isAdded)); } @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(isLoading), const DeepCollectionEquality().hash(isAdded)); @JsonKey(ignore: true) @override _$$_TripStateCopyWith<_$_TripState> get copyWith => __$$_TripStateCopyWithImpl<_$_TripState>(this, _$identity); } abstract class _TripState implements TripState { factory _TripState({required final bool isLoading, final bool? isAdded}) = _$_TripState; @override bool get isLoading; @override bool? get isAdded; @override @JsonKey(ignore: true) _$$_TripStateCopyWith<_$_TripState> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/trave_tou_app/lib/application/trip
mirrored_repositories/trave_tou_app/lib/application/trip/bloc/trip_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:injectable/injectable.dart'; import 'package:tourist_app/config/firestore_collection.dart'; import 'package:tourist_app/domain/trip_create/trip_create.dart'; import 'package:tourist_app/infrastructure/firestore/firestore.dart'; part 'trip_event.dart'; part 'trip_state.dart'; part 'trip_bloc.freezed.dart'; @injectable class TripBloc extends Bloc<TripEvent, TripState> { final FirestoreFunctions firestoreFunctions; TripBloc(this.firestoreFunctions) : super(TripState.initial()) { on<_CreateTrip>((event, emit) { emit(state.copyWith(isLoading: true)); firestoreFunctions.addDataToCollection(Collections.TRIP_DATA, { 'Trip_name': event.model!.name, 'TripFromDate': event.model!.fromDate, 'TripToDate': event.model!.toDate, 'Expense': event.model!.expense }); emit(state.copyWith(isLoading: false, isAdded: true)); }); } }
0