repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Bike-Service-App
mirrored_repositories/Bike-Service-App/lib/main.dart
// Material package for Material Design Components import 'package:bike_service_app/app/core/app_bindings/app_bindings.dart'; import 'package:flutter/material.dart'; //// External Packages // Device Preview Package import 'package:device_preview/device_preview.dart'; // GetX Package import 'package:get/get.dart'; //// Firebase Packages // Firebase Core + Firebase_Options Packages import 'package:firebase_core/firebase_core.dart'; import 'package:bike_service_app/firebase_options.dart'; // Firebase Auth Package // Firebase Firestore Package // import 'package:cloud_firestore/cloud_firestore.dart'; import 'app/features/client_panel/authentication/presentation/pages/entry_point/entry_point_page.dart'; //// Page Imports // Entry Point of App Future<void> main() async { // it will initialize our Flutter Firebase app before starting the App WidgetsFlutterBinding.ensureInitialized(); // Initilizing Firebase API await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp( // Device Preview Settings DevicePreview( enabled: false, tools: const [ ...DevicePreview.defaultTools, ], builder: (context) => const MyApp(), ), ); } // Root Widget class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { // GetMaterialApp to access all GetX functionality in our App return GetMaterialApp( initialRoute: '/', // changing app's settings, so Device Preview can run properly useInheritedMediaQuery: true, locale: DevicePreview.locale(context), builder: DevicePreview.appBuilder, // Disabled the Debug Banner debugShowCheckedModeBanner: false, title: 'Ganpati Motor Services', theme: ThemeData( // Material 3 Support Enabled useMaterial3: true, ), // App Bindings initialization initialBinding: AppBindings(), // First Page to show on screen home: EntryPointPage(), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components/snackbar/snackbar.dart
import 'package:bike_service_app/app/core/constants/theme/colors/colors.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; SnackbarController snackbarWidget(String title, String message, Color bgColor) { return Get.snackbar( title, message, backgroundColor: bgColor, colorText: AppColors.frontSheetColor, ); }
0
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components/drawer/drawer_controller.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../core/firebase_api_instances/firebase_api_instances.dart'; class DrawerControllerCommon extends GetxController { // variable to store User Name var userName = ''.obs; @override void onInit() { super.onInit(); // we are calling getUserName() method when the Controller initialized getUserName(); } // Method to get currently signedIn User's Name from Database void getUserName() { FirebaseApiInstances() .firestoreInstance .value .collection('users') .doc(FirebaseApiInstances().authInstance.value.currentUser?.email) .get() .then( (value) { final document = value.data(); userName.value = document?['name']; }, onError: (e) => debugPrint( "Error in getUserName() Method, while getting User Name from Database = $e"), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components/drawer/drawer.dart
import 'package:bike_service_app/app/core/constants/theme/colors/colors.dart'; import 'package:bike_service_app/app/core/constants/theme/textstyles/textstyle.dart'; import 'package:bike_service_app/app/core/firebase_api_instances/firebase_api_instances.dart'; import 'package:bike_service_app/app/global/widget_components/snackbar/snackbar.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'drawer_controller.dart'; class DrawerWidget extends StatelessWidget { DrawerWidget({super.key}); final DrawerControllerCommon drawerController = Get.find(); @override Widget build(BuildContext context) { return Drawer( child: ListView( children: [ // Header DrawerHeader( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ ListTile( isThreeLine: true, contentPadding: EdgeInsets.zero, leading: const CircleAvatar( radius: 36, child: Icon( Icons.person, size: 36, ), ), title: Text(drawerController.userName.value), subtitle: Text(FirebaseApiInstances() .authInstance .value .currentUser ?.email ?? ''), ), ], ), ), // Tiles ListTile( title: const Text('Sign Out'), trailing: const Icon(Icons.logout), onTap: () async { try { // Signing Out the Current User await FirebaseApiInstances().authInstance.value.signOut(); // closing the Drawer and go back to previous route / SignUpPage Get.back(closeOverlays: true, canPop: true); snackbarWidget('Account', 'You are Signed Out !', AppColors.snackBarColorWarning); } catch (e) { debugPrint('Error while Signing Out in Drawer Widget = $e'); } }, ), const Divider(), ListTile( title: const Text('Delete Account'), trailing: const Icon(Icons.person_off_outlined), onTap: () async { // Confirming From user First, after that doing the Operation await Get.dialog( name: 'Confirm', AlertDialog( title: const Column( children: [ Row( children: [ Expanded( child: Text( 'All your data will be Lost !', style: AppTextStyleTheme.alertDialogTitleText, ), ), ], ), Divider(), Row( children: [ Expanded( child: Text( 'Do you Want to Delete your Account ?', style: AppTextStyleTheme.descriptionText, ), ), ], ), ], ), actions: [ // Yes // Delete the Account TextButton( onPressed: () async { try { await FirebaseApiInstances() .authInstance .value .currentUser ?.delete(); snackbarWidget( 'Account', 'Your account has been deleted !', AppColors.snackBarColorWarning); } on FirebaseAuthException catch (e) { if (e.code == 'requires-recent-login') { snackbarWidget( 'Alert', 'Please first Sign Out & then login Again !', AppColors.snackBarColorWarning); debugPrint( 'Please Login Again to do Delete Operation !'); } } catch (e) { debugPrint( 'Error while Deleting User Account in Drawer Widget = $e'); } }, child: const Text('Yes'), ), // No // Do Not delete the Account TextButton( onPressed: () { Get.back(); }, child: const Text('No'), ), ], ), ); }, ), const Divider(), ], ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components
mirrored_repositories/Bike-Service-App/lib/app/global/widget_components/app_bar/appbar.dart
import 'package:flutter/material.dart'; import '../../../core/constants/theme/textstyles/textstyle.dart'; PreferredSizeWidget appBar(String title) { return AppBar( centerTitle: true, backgroundColor: Colors.transparent, foregroundColor: Colors.white, title: Text( title, style: AppTextStyleTheme.appBarText, ), actions: const [ Padding( padding: EdgeInsets.symmetric(horizontal: 18.0), child: CircleAvatar( radius: 16, child: Icon( Icons.person_sharp, size: 20, ), ), ), ], ); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/admin_panel/dashboard/presentation
mirrored_repositories/Bike-Service-App/lib/app/features/admin_panel/dashboard/presentation/pages/dashboard_home_page.dart
// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace import 'package:bike_service_app/app/global/widget_components/app_bar/appbar.dart'; import 'package:flutter/material.dart'; import '../../../../../core/constants/theme/colors/colors.dart'; class DashboardHomePage extends StatelessWidget { const DashboardHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, backgroundColor: AppColors.backSheetColor, appBar: appBar('Dashboard'), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // // // Manage Section const Text( 'Manage', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600), ), const SizedBox(height: 20.0), Flexible( fit: FlexFit.loose, child: GridView.count( childAspectRatio: 0.7, shrinkWrap: true, physics: const ClampingScrollPhysics(), mainAxisSpacing: 15.0, crossAxisSpacing: 15.0, crossAxisCount: 2, children: [ // card = 1 [Scheduled Services] Card( child: InkWell( onTap: () {}, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Container( child: const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( 'Scheduled Service', textAlign: TextAlign.center, ), ), ], ), ), ), const Divider( height: 1.0, indent: 10.0, endIndent: 10.0, ), Expanded( child: Container( child: const Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Center( child: Text( 'Today', textAlign: TextAlign.center, ), ), ), Expanded( child: Center( child: Text( '4', textAlign: TextAlign.center, style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.w600), ), ), ), ], ), )), ], ), ), ), ), // card = 2 [Registered Customer] Card( child: InkWell( onTap: () {}, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Container( child: const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( 'Scheduled Service', textAlign: TextAlign.center, ), ), ], ), ), ), const Divider( height: 1.0, indent: 10.0, endIndent: 10.0, ), Expanded( child: Container( child: const Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Center( child: Text( 'Total', textAlign: TextAlign.center, ), ), ), Expanded( child: Center( child: Text( '70', textAlign: TextAlign.center, style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.w600), ), ), ), ], ), )), ], ), ), ), ), ], ), ), const SizedBox(height: 40.0), // // // Analysis Section const Text( 'Analysis', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600), ), const SizedBox(height: 20.0), Flexible( fit: FlexFit.loose, child: GridView.count( childAspectRatio: 0.7, shrinkWrap: true, physics: const ClampingScrollPhysics(), mainAxisSpacing: 15.0, crossAxisSpacing: 15.0, crossAxisCount: 2, children: [ // card = 1 [Services Analysis] Card( child: InkWell( onTap: () {}, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Container( child: const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( 'Services Done', textAlign: TextAlign.center, ), ), ], ), ), ), const Divider( height: 1.0, indent: 10.0, endIndent: 10.0, ), Expanded( child: Container( child: const Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Center( child: Text( 'Today', textAlign: TextAlign.center, ), ), ), Expanded( child: Center( child: Text( '3', textAlign: TextAlign.center, style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.w600), ), ), ), ], ), )), ], ), ), ), ), // card = 2 [New Registered Customer Analysis] Card( child: InkWell( onTap: () {}, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Container( child: const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( 'New Registered', textAlign: TextAlign.center, ), ), ], ), ), ), const Divider( height: 1.0, indent: 10.0, endIndent: 10.0, ), Expanded( child: Container( child: const Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Center( child: Text( 'This Month', textAlign: TextAlign.center, ), ), ), Expanded( child: Center( child: Text( '16', textAlign: TextAlign.center, style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.w600), ), ), ), ], ), ), ), ], ), ), ), ), // card = 3 [Payments Recieved Analysis] Card( child: InkWell( onTap: () {}, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Expanded( child: Container( child: const Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( 'Payment Recieved', textAlign: TextAlign.center, ), ), ], ), ), ), const Divider( height: 1.0, indent: 10.0, endIndent: 10.0, ), Expanded( child: Container( child: const Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Center( child: Text( 'Today', textAlign: TextAlign.center, ), ), ), Expanded( child: Center( child: Text( '3200', textAlign: TextAlign.center, style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.w600), ), ), ), ], ), ), ), ], ), ), ), ), ], ), ), const SizedBox(height: 20.0), ], ), ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/data
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/data/repositories_implement/schedule_summary_repo_impl.dart
import 'dart:convert'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/entities/service_entity.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/repositories/schedule_summary_repositories.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../core/firebase_api_instances/firebase_api_instances.dart'; class ScheduleSummaryRepoImpl implements ScheduleSummaryRepository { // Firebase Instances from FirebaseApiInstances class final FirebaseApiInstances firebaseApiInstances = Get.put(FirebaseApiInstances()); @override Future<void> createService(ServiceEntity service) async { // Taking & Converting Object/Instance of ServiceEntity class to Json String final serviceEntity = serviceEntityToMap(service); // after getting Json String, We are converting it to Json Map // so that we can pass it to Firebase Firestore Database collection final data = json.decode(serviceEntity); // // Storing latest created Service\'s Map data to the Location = ( services -> doc(uid) -> myservices -> doc(auto-generated ID) {data} ) try { // await firebaseApiInstances.firestoreInstance.value .collection('services') .doc(firebaseApiInstances.authInstance.value.currentUser!.uid) .collection('myservices') .add(data); } catch (e) { // Get.snackbar('Other createService error', '$e', colorText: Colors.white); debugPrint( 'Error while Storing latest created Service\'s Map data to Firebase Firestore in ScheduleSummaryRepoImpl class = $e'); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/presentation/controllers/schedule_summary_controller/schedule_summary_controller.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../domain/entities/service_entity.dart'; import '../../../domain/use_cases/schedule_summary_use_case.dart'; class ScheduleSummaryController extends GetxController { final CreateServiceUseCase createServiceUseCase; ScheduleSummaryController(this.createServiceUseCase); // Method to pass all form values to the ServiceEntity Model class to instanciate it & // passing the Instance of ServiceEntity Model class to createServiceUseCase class Future<void> createService( int bookingId, String bikeName, String bikeNumber, String mobileNumber, String fullAddress, String serviceDate, String serviceTime, String onlinePaymentUpiNumber, List<SelectedServiceList> selectedServiceList, String totalPrice, ServiceStatus serviceStatus) async { try { await createServiceUseCase( // passing instance of ServiceEntity Model class while Initializing it ServiceEntity( bookingId: bookingId, bikeName: bikeName, bikeNumber: bikeNumber, mobileNumber: mobileNumber, fullAddress: fullAddress, serviceDate: serviceDate, serviceTime: serviceTime, onlinePaymentUpiNumber: onlinePaymentUpiNumber, selectedServiceList: selectedServiceList, serviceStatus: serviceStatus, totalPrice: totalPrice), ); } catch (e) { debugPrint( 'Error in ScheduleSummaryController while both operations - Initializing ServiceEntity Model class & Passing it\'s Instance to CreateServiceUseCase class = $e'); } } /// Other Functionality // variable to store Total price of all selected services in the ScheduleSummaryPage var price = 0.obs; var totalPrice = 0.obs; // Method for calculating & returning total price of all selectedServices int totalPriceResult(List<dynamic>? selectedServiceList) { // resetting values on every call price.value = 0; totalPrice.value = 0; // iterating through all selected services for (var element in selectedServiceList!) { price.value = (price.value + element['price']).toInt(); } return totalPrice.value = price.value; } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/presentation/pages/schedule_summary_page/schedule_summary_page.dart
import 'package:bike_service_app/app/features/client_panel/authentication/presentation/pages/landing_page/landing_page.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/entities/service_entity.dart'; import 'package:bike_service_app/app/global/widget_components/app_bar/appbar.dart'; import 'package:bike_service_app/app/global/widget_components/snackbar/snackbar.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../../core/constants/theme/colors/colors.dart'; import '../../../../../../core/constants/theme/textstyles/textstyle.dart'; import '../../controllers/schedule_summary_controller/schedule_summary_controller.dart'; class ScheduleSummaryPage extends StatelessWidget { final int? bookingId; final String? bikeName; final String? bikeNumber; final String? mobileNumber; final String? fullAddress; final List<dynamic>? selectedServiceList; final String? serviceDate; final String? serviceTime; final Map<String, Map<String, dynamic>>? serviceStatus; ScheduleSummaryPage( {super.key, this.bikeName, this.bikeNumber, this.mobileNumber, this.fullAddress, this.selectedServiceList, this.serviceDate, this.serviceTime, this.bookingId, this.serviceStatus}); // Getting Instance of scheduleSummaryController each time we call the ScheduleSummaryPage Class final ScheduleSummaryController scheduleSummaryController = Get.find(); @override Widget build(BuildContext context) { // Back Navigation Logic while using AlertDialog return PopScope( canPop: false, onPopInvoked: (didPop) async { // if true then return nothing if (didPop) { return; } // if false then return AlertDialog Widget await showDialog( context: context, barrierDismissible: false, builder: (context) => AlertDialog( title: const Text('Do you want to Edit this ?'), actions: [ OutlinedButton( onPressed: () { // if user click on Yes then, // First close the Dialog Get.back(); // Then close the current page and go back Get.back(); }, child: const Text('Yes'), ), OutlinedButton( onPressed: () { // if user click on No then, // Just close the dialog Get.back(); }, child: const Text('No'), ), ], ), ); }, child: Scaffold( resizeToAvoidBottomInset: true, backgroundColor: AppColors.backSheetColor, // Schedule Summary appBar: appBar('Schedule Summary'), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Column( children: [ // Main Container for Bill Summary Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10), decoration: const BoxDecoration( // border: Border.all(), color: AppColors.inputTextBoxInnerColor, ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const SizedBox( height: 10, ), // Main Title const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( 'Ganpati Motors', textAlign: TextAlign.center, style: AppTextStyleTheme.scheduleSummaryTitleText, ), ), ], ), const SizedBox( height: 20, ), // Bike Information const Row( children: [ Expanded( child: Text( 'Bike Information', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummarySubTitleText, ), ), ], ), const SizedBox( height: 10, ), // 1 Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Booking ID', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '$bookingId', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), // 2 Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Bike Number', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '$bikeNumber', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), // 3 Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Bike Name', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '$bikeName', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), const SizedBox( height: 20, ), // Service Charges const Row( children: [ Expanded( child: Text( 'Service Charges', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummarySubTitleText, ), ), ], ), const SizedBox( height: 10, ), // Heading Container( decoration: const BoxDecoration( border: Border(bottom: BorderSide())), child: const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( 'Service Name', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), Expanded( child: Text( 'Service Price', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), ), // 1 [ ListView.builder ] SizedBox( child: ListView.separated( padding: const EdgeInsets.symmetric(vertical: 10.0), physics: const ClampingScrollPhysics(), scrollDirection: Axis.vertical, itemCount: selectedServiceList!.length, shrinkWrap: true, primary: false, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(vertical: 1.0), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( '${selectedServiceList![index]['name']}', textAlign: TextAlign.left, style: AppTextStyleTheme .scheduleSummaryKeyText, ), ), Expanded( child: Text( '${selectedServiceList![index]['price']}', textAlign: TextAlign.left, style: AppTextStyleTheme .scheduleSummaryValueText, ), ), ], ), ); }, separatorBuilder: (BuildContext context, int index) { return const Divider(); }, ), ), // Footer Container( decoration: const BoxDecoration( border: Border.symmetric(horizontal: BorderSide())), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Total', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), Expanded( child: Obx( () => Text( scheduleSummaryController .totalPriceResult(selectedServiceList) .toString(), textAlign: TextAlign.left, style: AppTextStyleTheme .scheduleSummaryValueText, ), ), ), ], ), ), const SizedBox( height: 20, ), // Schedule Timing const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( 'Schedule Timing', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummarySubTitleText, ), ), ], ), const SizedBox( height: 10, ), // 1 Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Service Starting Date', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '$serviceDate', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), // 2 Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Service Starting Time', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '$serviceTime', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), // 3 Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Expanded( child: Text( 'Service Ending Time', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '[ After Service we will inform you, on your Registered Number = $mobileNumber ]', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), const SizedBox( height: 20, ), // Payment Option const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( 'Payment Option', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummarySubTitleText, ), ), ], ), const SizedBox( height: 10, ), // 1 const Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( 'Online Payment UPI No.', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( 'xxxxxxxxxx', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), // 2 const Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( 'Offline Option', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '[ You can pay on the service center ]', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), const SizedBox( height: 20, ), // Payment Option const Row( children: [ Expanded( child: Text( 'Service Center Address', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummarySubTitleText, ), ), ], ), const SizedBox( height: 10, ), // 1 const Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( 'Address', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryKeyText, ), ), Expanded( child: Text( '[ Ganpati Motor Services, Krishna Nagar Sendra Road, Beawar, Rajasthan 305901 ]', textAlign: TextAlign.left, style: AppTextStyleTheme.scheduleSummaryValueText, ), ), ], ), const SizedBox( height: 10, ), ], ), ), const SizedBox( height: 40, ), // Button ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(AppColors.mainButtonColor), ), onPressed: () async { //Debugging // checking values debugPrint('Bike Name = $bikeName'); debugPrint('Bike Number = $bikeNumber'); debugPrint('Mobile Number = $mobileNumber'); debugPrint('Full Address = $fullAddress'); debugPrint('Selected Service List = $selectedServiceList'); debugPrint( 'Total No. of Services = ${selectedServiceList!.length}'); debugPrint( 'Total Price of Service = ${scheduleSummaryController.totalPrice}'); debugPrint('Service Date = $serviceDate'); debugPrint('Service Time = $serviceTime'); debugPrint('Service Status = $serviceStatus'); // Sending Values/Arguments to createService() Method of scheduleSummaryController to create a new Service try { await scheduleSummaryController.createService( bookingId!, bikeName!, bikeNumber!, mobileNumber!, fullAddress!, serviceDate!, serviceTime!, '0000000000', // making List<classes> from List<Maps> & Passing it to createService Method of scheduleSummaryController List<SelectedServiceList>.from( selectedServiceList! .map( (x) => SelectedServiceList( serviceName: x["name"], servicePrice: x["price"], ), ) .toList(), growable: true), scheduleSummaryController.totalPrice.value.toString(), // making single class object from Map<String,<String, dynamic>> ServiceStatus.fromMap( serviceStatus!["Service Status"]!), ); // Showing Success Message snackbarWidget('Success', 'Service Scheduled !', AppColors.snackBarColorSuccess); // Form will be Automatically Reset // Go to landingPage -> HomePage and clear all route from Route Stack Get.offAll(() => LandingPage()); } catch (e) { debugPrint( 'error while calling createService() Method of scheduleSummaryController through ScheduleSummaryPage = $e'); } }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 16), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Confirm This Service', style: AppTextStyleTheme.buttonMainText, ), SizedBox( width: 5, ), Icon(Icons.arrow_right_alt_sharp, color: Colors.white), ], ), ), ), const SizedBox( height: 40, ), ], ), ), ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/domain/use_cases/schedule_summary_use_case.dart
import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/entities/service_entity.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/repositories/schedule_summary_repositories.dart'; class CreateServiceUseCase { final ScheduleSummaryRepository scheduleSummaryRepository; CreateServiceUseCase(this.scheduleSummaryRepository); // calling createService() method of ScheduleSummaryRepository abstract class while passing Instance/Object of ServiceEntity model class Future<void> call(ServiceEntity service) async { return await scheduleSummaryRepository.createService(service); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/domain/entities/service_entity.dart
// To parse this JSON data, do // Example = How to use // Json String to Dart Object/Instance conversion // final serviceEntity = serviceEntityFromMap(jsonString); // Dart Object to Json String and then to Dart Map conversion // final serviceEntity = serviceEntityToMap(jsonString); // after receiving Json String, we can convert it to Dart Map through below code // final data = json.decode(Json String); import 'dart:convert'; ServiceEntity serviceEntityFromMap(String str) => ServiceEntity.fromMap(json.decode(str)); // Object to Json String String serviceEntityToMap(ServiceEntity data) => json.encode(data.toMap()); class ServiceEntity { final int bookingId; final String bikeName; final String bikeNumber; final String mobileNumber; final String fullAddress; final String serviceDate; final String serviceTime; final String onlinePaymentUpiNumber; final List<SelectedServiceList> selectedServiceList; final String totalPrice; final ServiceStatus serviceStatus; ServiceEntity({ required this.bookingId, required this.bikeName, required this.bikeNumber, required this.mobileNumber, required this.fullAddress, required this.serviceDate, required this.serviceTime, required this.onlinePaymentUpiNumber, required this.selectedServiceList, required this.totalPrice, required this.serviceStatus, }); factory ServiceEntity.fromMap(Map<String, dynamic> json) => ServiceEntity( bookingId: json["Booking ID"], bikeName: json["Bike Name"], bikeNumber: json["Bike Number"], mobileNumber: json["Mobile Number"], fullAddress: json["Full Address"], serviceDate: json["Service Date"], serviceTime: json["Service Time"], onlinePaymentUpiNumber: json["Online Payment UPI Number"], selectedServiceList: List<SelectedServiceList>.from( json["Selected Service List"] .map((x) => SelectedServiceList.fromMap(x))), totalPrice: json["Total Price"], serviceStatus: ServiceStatus.fromMap(json["Service Status"]), ); Map<String, dynamic> toMap() => { "Booking ID": bookingId, "Bike Name": bikeName, "Bike Number": bikeNumber, "Mobile Number": mobileNumber, "Full Address": fullAddress, "Service Date": serviceDate, "Service Time": serviceTime, "Online Payment UPI Number": onlinePaymentUpiNumber, "Selected Service List": List<dynamic>.from(selectedServiceList.map((x) => x.toMap())), "Total Price": totalPrice, "Service Status": serviceStatus.toMap(), }; } class SelectedServiceList { final String serviceName; final int servicePrice; SelectedServiceList({ required this.serviceName, required this.servicePrice, }); factory SelectedServiceList.fromMap(Map<String, dynamic> json) => SelectedServiceList( serviceName: json["service name"], servicePrice: json["service price"], ); Map<String, dynamic> toMap() => { "service name": serviceName, "service price": servicePrice, }; } class ServiceStatus { final String service; final String amount; ServiceStatus({ required this.service, required this.amount, }); factory ServiceStatus.fromMap(Map<String, dynamic> json) => ServiceStatus( service: json["service"], amount: json["amount"], ); Map<String, dynamic> toMap() => { "service": service, "amount": amount, }; }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_summary/domain/repositories/schedule_summary_repositories.dart
import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/entities/service_entity.dart'; abstract class ScheduleSummaryRepository { Future<void> createService(ServiceEntity service); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/repositories_implement
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/repositories_implement/signin_repositories_impl/signin_repositories_impl.dart
import 'package:bike_service_app/app/core/constants/theme/colors/colors.dart'; import 'package:bike_service_app/app/global/widget_components/snackbar/snackbar.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../../core/firebase_api_instances/firebase_api_instances.dart'; import '../../../domain/entities/signin_user_entity.dart'; import '../../../domain/repositories/signin_repositories/signin_repositories.dart'; class SignInRepositoryImpl implements SignInRepositories { final FirebaseApiInstances firebaseApiInstances = Get.put(FirebaseApiInstances()); @override Future<void> signinUser(SignInUserEntity user) async { try { await firebaseApiInstances.authInstance.value.signInWithEmailAndPassword( email: user.email, password: user.password, ); Get.back(); Get.snackbar( '', '', titleText: const Text('Signed In !'), messageText: Container(), backgroundColor: AppColors.snackBarColorSuccess, ); // snackbarWidget( // 'User Signed In Successfully', '', AppColors.snackBarColorSuccess); } on FirebaseAuthException catch (e) { if (e.code == 'invalid-credential') { snackbarWidget('Invalid', 'Invalid Email & Password. Check Again !', AppColors.snackBarColorWarning); debugPrint('No user found for that email.'); } else if (e.code == 'wrong-password') { snackbarWidget( 'wrong-password', 'Wrong password provided for that user.', AppColors.snackBarColorWarning); debugPrint('Wrong password provided for that user.'); } else if (e.code == 'invalid-email') { snackbarWidget('invalid-email', 'The email address is not valid.', AppColors.snackBarColorWarning); debugPrint('The email address is not valid.'); } else if (e.code == 'user-disabled') { snackbarWidget( 'user-disabled', 'The user corresponding to the given email has been disabled.', AppColors.snackBarColorWarning); debugPrint( 'The user corresponding to the given email has been disabled.'); } else { snackbarWidget( 'Other Sign In Error', '$e', AppColors.snackBarColorWarning); debugPrint('Other Sign In Error = $e'); } } catch (e) { snackbarWidget( 'Other Sign In Error', '$e', AppColors.snackBarColorWarning); debugPrint('Other Sign In Error = $e'); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/repositories_implement
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/repositories_implement/signup_repositories_impl/signup_repositories_impl.dart
import 'package:bike_service_app/app/core/firebase_api_instances/firebase_api_instances.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/domain/entities/signup_user_entity.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/domain/repositories/signup_repositories/signup_repositories.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../../core/constants/theme/colors/colors.dart'; class SignUpRepositoryImpl implements SignUpRepositories { final FirebaseApiInstances firebaseApiInstances = Get.put(FirebaseApiInstances()); @override Future<void> createUser(SignUpUserEntity user) async { try { await firebaseApiInstances.authInstance.value .createUserWithEmailAndPassword( email: user.email, password: user.password, ); Get.snackbar('User Registered Successfully', 'User credentials saved.', colorText: Colors.white, backgroundColor: AppColors.snackBarColorSuccess); } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { Get.snackbar('weak-password', 'The password provided is too weak.', colorText: Colors.white, backgroundColor: AppColors.snackBarColorWarning); debugPrint('The password provided is too weak.'); } else if (e.code == 'email-already-in-use') { Get.snackbar('email-already-in-use', 'The account already exists for that email.', colorText: Colors.white, backgroundColor: AppColors.snackBarColorWarning); debugPrint('The account already exists for that email.'); } else if (e.code == 'invalid-email') { Get.snackbar('invalid-email', 'The email address is not valid.', colorText: Colors.white, backgroundColor: AppColors.snackBarColorWarning); debugPrint('The email address is not valid.'); } else if (e.code == 'operation-not-allowed') { Get.snackbar('operation-not-allowed', 'Email/Password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.', colorText: Colors.white, backgroundColor: AppColors.snackBarColorWarning); debugPrint( 'Email/Password accounts are not enabled. Enable email/password accounts in the Firebase Console, under the Auth tab.'); } } catch (e) { Get.snackbar('Other Sign Up error', '$e', colorText: Colors.white, backgroundColor: AppColors.snackBarColorWarning); debugPrint('Other Sign Up error = $e'); } // Storing Created User Details inside Firebase Firestore Database try { await firebaseApiInstances.firestoreInstance.value .collection('users') .doc(user.email) .set({ 'name': user.name, 'email': user.email, 'admin': false, }); } catch (e) { debugPrint('Firestore Database error in Implementation Class = $e'); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/models
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/models/signup_model/signup_user_model.dart
// To parse this JSON data, do // // final signUpUserModel = signUpUserModelFromMap(jsonString); import 'dart:convert'; SignUpUserModel signUpUserModelFromMap(String str) => SignUpUserModel.fromMap(json.decode(str)); String signUpUserModelToMap(SignUpUserModel data) => json.encode(data.toMap()); class SignUpUserModel { final String name; final String email; final String password; SignUpUserModel({ required this.name, required this.email, required this.password, }); factory SignUpUserModel.fromMap(Map<String, dynamic> json) => SignUpUserModel( name: json["name"], email: json["email"], password: json["password"], ); Map<String, dynamic> toMap() => { "name": name, "email": email, "password": password, }; }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/models
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/data/models/signin_model/signin_user_model.dart
// To parse this JSON data, do // // final signInUserModel = signInUserModelFromMap(jsonString); import 'dart:convert'; SignInUserModel signInUserModelFromMap(String str) => SignInUserModel.fromMap(json.decode(str)); String signInUserModelToMap(SignInUserModel data) => json.encode(data.toMap()); class SignInUserModel { final String email; final String password; SignInUserModel({ required this.email, required this.password, }); factory SignInUserModel.fromMap(Map<String, dynamic> json) => SignInUserModel( email: json["email"], password: json["password"], ); Map<String, dynamic> toMap() => { "email": email, "password": password, }; }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers/bottom_navigation/bottom_navigation_controller.dart
import 'package:get/get.dart'; class BottomNavigationController extends GetxController { // tabIndex to show a specific page according to it's value var tabIndex = 0.obs; // method to change tabIndex value on tap of icon of BottomNavigationBar void changeTabIndex(int index) { tabIndex.value = index; } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers/signin_page/signin_controller.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../domain/entities/signin_user_entity.dart'; import '../../../domain/use_cases/signin_usecase/signin_usecase.dart'; class SignInController extends GetxController { final SignInUserUseCase signInUserUseCase; SignInController(this.signInUserUseCase); // TextFormField Controllers final emailController = TextEditingController().obs; final passwordController = TextEditingController().obs; // Form Global Key final formKeySignIn = GlobalKey<FormState>().obs; /// saving Form values like - User Email, Password // .obs Variables to store Form values final emailID = ''.obs; final password = ''.obs; // Method to store values void saveFormValues(String email, String pass) { emailID.value = email; password.value = pass; // Debugging if (emailID.value.isEmpty || password.value.isEmpty) { debugPrint('Values are Empty'); } else { debugPrint('Values are saved'); // Calling createUser Method to Create and Store New User Account Information in Firebase signInUser(emailID.value, password.value); } } // Passing saved values to CreateUserUserCase class after initializing the Entity Class Future<void> signInUser(String email, String password) async { try { await signInUserUseCase( SignInUserEntity(email: email, password: password), ); } catch (e) { debugPrint('Sign In error in SignInController = $e'); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers/signup_page/signup_controller.dart
import 'package:bike_service_app/app/features/client_panel/authentication/domain/entities/signup_user_entity.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../domain/use_cases/signup_usecases/signup_usecases.dart'; class SignUpController extends GetxController { final CreateUserUseCase createUserUseCase; SignUpController(this.createUserUseCase); // TextFormField Controllers final nameController = TextEditingController().obs; final emailController = TextEditingController().obs; final passwordController = TextEditingController().obs; // Form Global Key final formKeySignUp = GlobalKey<FormState>().obs; /// saving Form values like - User Name, Email, Password // .obs Variables to store Form values final userName = ''.obs; final emailID = ''.obs; final password = ''.obs; // Method to store values void saveFormValues(String name, String email, String pass) { userName.value = name; emailID.value = email; password.value = pass; // Debugging if (userName.value.isEmpty || emailID.value.isEmpty || password.value.isEmpty) { debugPrint('Values are Empty'); } else { debugPrint('Values are saved'); // Calling createUser Method to Create and Store New User Account Information in Firebase createUser(userName.value, emailID.value, password.value); } } // Passing saved values to CreateUserUserCase class after initializing the Entity Class Future<void> createUser(String name, String email, String password) async { try { await createUserUseCase( SignUpUserEntity(name: name, email: email, password: password), ); } catch (e) { debugPrint('Firestore error in SignUpController = $e'); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/controllers/entry_point/entry_point_controller.dart
import 'package:bike_service_app/app/core/firebase_api_instances/firebase_api_instances.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class EntryPointController extends GetxController { var isAdmin = false.obs; @override void onInit() { super.onInit(); getAdminLoginStatus(); } void getAdminLoginStatus() { FirebaseApiInstances() .firestoreInstance .value .collection('users') .doc(FirebaseApiInstances().authInstance.value.currentUser?.email) .get() .then( (value) { final document = value.data(); if (document?['admin'] == false) { isAdmin.value = false; } else { isAdmin.value = true; } }, onError: (e) => debugPrint( "Error in getAdminLoginStatus() Method, while getting User Admin Status from Database = $e"), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/widgets/header_widget.dart
// ignore_for_file: avoid_unnecessary_containers import 'package:flutter/material.dart'; import '../../../../../core/constants/theme/textstyles/textstyle.dart'; // Header Widget class HeaderWidget extends StatelessWidget { final String title; final String subtitle; const HeaderWidget({super.key, required this.title, required this.subtitle}); @override Widget build(BuildContext context) { return Container( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const SizedBox( height: 10, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( title, style: AppTextStyleTheme.welcomeHeadingTitleText, ) ], ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(subtitle, style: AppTextStyleTheme.welcomeHeadingSubtitleText) ], ), ], ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages/home_page/home_page.dart
// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../../core/constants/assets_path/asset_path.dart'; import '../../../../../../core/constants/theme/colors/colors.dart'; import '../../../../../../core/constants/theme/textstyles/textstyle.dart'; import '../../../../services/presentation/pages/service_page/service_page.dart'; import '../../controllers/bottom_navigation/bottom_navigation_controller.dart'; class HomePage extends StatelessWidget { HomePage({super.key}); final BottomNavigationController bottomNavigationController = Get.put(BottomNavigationController()); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.backSheetColor, body: SafeArea( child: Container( height: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const SizedBox( height: 16, ), // Heading Container( child: const Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( 'Ganpati Motors', textAlign: TextAlign.center, style: AppTextStyleTheme.welcomeHeadingSubtitleText, ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Padding( padding: EdgeInsets.all(6.0), child: Text( '"Your Bike\'s Best Companion"', textAlign: TextAlign.center, style: AppTextStyleTheme .welcomeHeadingSubtitleDescriptionText, ), ), ), ], ), ], ), ), const SizedBox( height: 12, ), Expanded( child: Container( padding: const EdgeInsets.symmetric( horizontal: 24.0, vertical: 14.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Column( children: [ Container( child: Image.asset(AssetPaths.bikeImage, scale: 2), ), const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( 'Get ready for a smoother ride!', textAlign: TextAlign.center, )), ], ), const SizedBox( height: 18, ), const Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24), child: Text( 'Ganpati Motor Service is here to make bike maintenance hassle-free. From quick fixes to regular check-ups, we\'ve got you covered', textAlign: TextAlign.center, ), ), ) ], ), const SizedBox( height: 25, ), // Get Started Button ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all( AppColors.mainButtonColor), ), onPressed: () { Get.to(() => ServicePage()); }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 16), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Get Started', style: AppTextStyleTheme.buttonMainText, ), SizedBox( width: 5, ), Icon(Icons.arrow_right_alt_sharp, color: Colors.white), ], ), ), ), const SizedBox( height: 20, ), ], ), ), ), ), ], ), ), ), // Bottom Navigation Bar bottomNavigationBar: Obx( () => BottomNavigationBar( showSelectedLabels: true, showUnselectedLabels: true, backgroundColor: AppColors.backSheetColor, currentIndex: bottomNavigationController.tabIndex.value, selectedItemColor: AppColors.frontSheetColor, unselectedItemColor: AppColors.frontSheetColor.withOpacity(0.5), onTap: (value) { bottomNavigationController.changeTabIndex(value); }, items: const [ BottomNavigationBarItem( icon: Icon( Icons.home, ), label: 'Home', ), BottomNavigationBarItem( icon: Icon( Icons.auto_awesome_motion_rounded, ), label: 'Services', ), ], ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages/signin_page/signin_page.dart
// ignore_for_file: sized_box_for_whitespace import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../../core/constants/theme/colors/colors.dart'; import '../../../../../../core/constants/theme/textstyles/textstyle.dart'; import '../../controllers/signin_page/signin_controller.dart'; import '../../widgets/header_widget.dart'; class SignInPage extends StatelessWidget { SignInPage({super.key}); // controller final SignInController signInController = Get.find(); @override Widget build(BuildContext context) { return Scaffold( // avoid keyboard overlape resizeToAvoidBottomInset: true, backgroundColor: AppColors.backSheetColor, body: SafeArea( child: Container( height: double.infinity, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Header const HeaderWidget( title: 'WELCOME', subtitle: 'Sign In', ), const SizedBox( height: 15, ), // TextFormFields Expanded( child: Container( padding: const EdgeInsets.symmetric( horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Form( key: signInController.formKeySignIn.value, autovalidateMode: AutovalidateMode.onUserInteraction, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ // Email Container( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const Row( children: [ Text('Email ID', style: AppTextStyleTheme .textFormFieldLabelText), ], ), const SizedBox( height: 5, ), TextFormField( controller: signInController.emailController.value, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( contentPadding: EdgeInsets.symmetric( vertical: 0, horizontal: 5), filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty || !value.contains('@')) { return 'Please Enter Valid Email'; } else { return null; } }, ), ], ), ), // Password Container( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const Row( children: [ Text('Password', style: AppTextStyleTheme .textFormFieldLabelText), ], ), const SizedBox( height: 5, ), TextFormField( controller: signInController.passwordController.value, keyboardType: TextInputType.visiblePassword, decoration: const InputDecoration( contentPadding: EdgeInsets.symmetric( vertical: 0, horizontal: 5), filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty) { return 'Please Enter Password'; } else if (value.length < 8) { return 'Please enter password of minimum length 8'; } else { return null; } }, ), ], ), ), const SizedBox( height: 30, ), // Sign Up Page Link Padding( padding: const EdgeInsets.symmetric(vertical: 12), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { Get.back(); }, child: const Text( 'Sign Up', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox( width: 20.0, ), const Text( 'If you are New !', style: TextStyle(fontSize: 12), ), ], ), ), const SizedBox( height: 20, ), // Sign In Button ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all( AppColors.mainButtonColor), ), onPressed: () async { // Checking if Form is Valid or not if (signInController .formKeySignIn.value.currentState! .validate()) { // Debugging debugPrint('Current Form State is valid'); // if Form is valid without any error // then we save the current state of form with values signInController .formKeySignIn.value.currentState! .save(); // Saving Form Field values // Then Storing New User Account to Firebase Auth signInController.saveFormValues( signInController.emailController.value.text, signInController .passwordController.value.text); // Debuging // Checking saved Values debugPrint('Form Saved'); debugPrint( 'email = ${signInController.emailController.value.text}'); debugPrint( 'password = ${signInController.passwordController.value.text}'); } else { // Debuging // Checking saved invalid Values debugPrint('Current Form State is not valid'); debugPrint( 'email = ${signInController.emailController.value.text}'); debugPrint( 'password = ${signInController.passwordController.value.text}'); } }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 14), child: Text( 'Sign In', style: AppTextStyleTheme.buttonMainText, ), ), ), const SizedBox( height: 30, ), // Sign In as ADMIN Button // ElevatedButton( // style: ButtonStyle( // backgroundColor: MaterialStateProperty.all( // AppColors.knowMoreButtonColor), // ), // onPressed: () {}, // child: const Padding( // padding: EdgeInsets.symmetric(vertical: 14), // child: Text( // 'Go to Admin Panel', // style: AppTextStyleTheme.buttonMainText, // ), // ), // ), const SizedBox( height: 30, ), ], ), ), ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages/signup_page/signup_page.dart
// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers import 'package:bike_service_app/app/core/constants/theme/colors/colors.dart'; import 'package:bike_service_app/app/core/constants/theme/textstyles/textstyle.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/presentation/pages/signin_page/signin_page.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../controllers/signup_page/signup_controller.dart'; import '../../widgets/header_widget.dart'; class SignUpPage extends StatelessWidget { SignUpPage({super.key}); final SignUpController signUpController = Get.find(); @override Widget build(BuildContext context) { return Scaffold( // avoid keyboard overlape resizeToAvoidBottomInset: true, backgroundColor: AppColors.backSheetColor, body: SafeArea( child: Container( height: double.infinity, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Header const HeaderWidget( title: 'WELCOME', subtitle: 'Sign Up', ), const SizedBox( height: 15, ), // TextFormFields Expanded( child: Container( padding: const EdgeInsets.symmetric( horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Form( key: signUpController.formKeySignUp.value, autovalidateMode: AutovalidateMode.onUserInteraction, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ // Name Container( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const Row( children: [ Text('User Name', style: AppTextStyleTheme .textFormFieldLabelText), ], ), const SizedBox( height: 5, ), TextFormField( controller: signUpController.nameController.value, keyboardType: TextInputType.name, decoration: const InputDecoration( contentPadding: EdgeInsets.symmetric( vertical: 0, horizontal: 5), filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty) { return 'Please Enter Name'; } else { return null; } }, ), ], ), ), // Email Container( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const Row( children: [ Text('Email ID', style: AppTextStyleTheme .textFormFieldLabelText), ], ), const SizedBox( height: 5, ), TextFormField( controller: signUpController.emailController.value, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( contentPadding: EdgeInsets.symmetric( vertical: 0, horizontal: 5), filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty || !value.contains('@')) { return 'Please Enter Valid Email'; } else { return null; } }, ), ], ), ), // Password Container( padding: const EdgeInsets.symmetric(vertical: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ const Row( children: [ Text('Password', style: AppTextStyleTheme .textFormFieldLabelText), ], ), const SizedBox( height: 5, ), TextFormField( controller: signUpController.passwordController.value, keyboardType: TextInputType.visiblePassword, decoration: const InputDecoration( contentPadding: EdgeInsets.symmetric( vertical: 0, horizontal: 5), filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty) { return 'Please Enter Password'; } else if (value.length < 8) { return 'Please enter password of minimum length 8'; } else { return null; } }, ), ], ), ), const SizedBox( height: 20, ), // Sign In Page Link Padding( padding: const EdgeInsets.symmetric(vertical: 12), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { Get.to(() => SignInPage()); }, child: const Text( 'Sign In', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), const SizedBox( width: 20.0, ), const Text( 'If you already have Account !', style: TextStyle(fontSize: 12), ), ], ), ), const SizedBox( height: 20, ), // Sign Up Button ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all( AppColors.mainButtonColor), ), onPressed: () async { // Checking if Form is Valid or not if (signUpController .formKeySignUp.value.currentState! .validate()) { // if Form is valid without any error // then we save the current state of form with values signUpController .formKeySignUp.value.currentState! .save(); // Saving Form Field values // Then Storing New User Account to Firebase Auth signUpController.saveFormValues( signUpController.nameController.value.text, signUpController.emailController.value.text, signUpController .passwordController.value.text); } else {} }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 14), child: Text( 'Sign Up', style: AppTextStyleTheme.buttonMainText, ), ), ), const SizedBox( height: 30, ), ], ), ), ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages/landing_page/landing_page.dart
// ignore_for_file: sized_box_for_whitespace, avoid_unnecessary_containers import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../my_services/presentation/pages/my_services_page/my_services_page.dart'; import '../../controllers/bottom_navigation/bottom_navigation_controller.dart'; import '../home_page/home_page.dart'; class LandingPage extends StatelessWidget { LandingPage({super.key}); // controller final BottomNavigationController bottomNavigationController = Get.put(BottomNavigationController()); @override Widget build(BuildContext context) { // Showing Page according to current tabIndex value return Obx(() => IndexedStack( index: bottomNavigationController.tabIndex.value, children: [ HomePage(), MyServicesPage(), ], )); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/presentation/pages/entry_point/entry_point_page.dart
import 'package:bike_service_app/app/features/client_panel/authentication/presentation/controllers/entry_point/entry_point_controller.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../admin_panel/dashboard/presentation/pages/dashboard_home_page.dart'; import '../landing_page/landing_page.dart'; import '../signup_page/signup_page.dart'; class EntryPointPage extends StatelessWidget { EntryPointPage({super.key}); // controller final EntryPointController entryPointController = Get.put(EntryPointController()); @override Widget build(BuildContext context) { return PopScope( key: key, canPop: false, onPopInvoked: (didPop) async { if (didPop) { return; } // if false then return AlertDialog Widget await showDialog( context: context, barrierDismissible: false, builder: (context) => AlertDialog( title: const Text('Do you want to EXIT ?'), actions: [ OutlinedButton( onPressed: () async { // if user click on Yes then, Get.back(); }, child: const Text('Yes'), ), OutlinedButton( onPressed: () { // if user click on No then, // Just close the dialog Get.back(); }, child: const Text('No'), ), ], ), ); }, child: StreamBuilder( // Firebase Auth Stream to detect in Realtime if a User Signed In or Not stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.hasData) { // if Signed In then show Landing Page return Obx(() => entryPointController.isAdmin.value ? const DashboardHomePage() : LandingPage()); } else { // if not Signed In then show SignUp Page return SignUpPage(); } }, ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/use_cases
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/use_cases/signup_usecases/signup_usecases.dart
import '../../entities/signup_user_entity.dart'; import '../../repositories/signup_repositories/signup_repositories.dart'; class CreateUserUseCase { final SignUpRepositories signUpRepositories; CreateUserUseCase(this.signUpRepositories); Future<void> call(SignUpUserEntity user) async { return await signUpRepositories.createUser(user); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/use_cases
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/use_cases/signin_usecase/signin_usecase.dart
import '../../entities/signin_user_entity.dart'; import '../../repositories/signin_repositories/signin_repositories.dart'; class SignInUserUseCase { final SignInRepositories signInRepositories; SignInUserUseCase(this.signInRepositories); Future<void> call(SignInUserEntity user) async { return await signInRepositories.signinUser(user); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/entities/signin_user_entity.dart
class SignInUserEntity { final String email; final String password; SignInUserEntity({ required this.email, required this.password, }); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/entities/signup_user_entity.dart
class SignUpUserEntity { final String name; final String email; final String password; SignUpUserEntity( {required this.name, required this.email, required this.password}); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/repositories
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/repositories/signup_repositories/signup_repositories.dart
import '../../entities/signup_user_entity.dart'; abstract class SignUpRepositories { Future<void> createUser(SignUpUserEntity user); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/repositories
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/authentication/domain/repositories/signin_repositories/signin_repositories.dart
import '../../entities/signin_user_entity.dart'; abstract class SignInRepositories { Future<void> signinUser(SignInUserEntity user); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/data
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/data/repositories_implement/my_services_repo_impl.dart
import 'package:bike_service_app/app/core/firebase_api_instances/firebase_api_instances.dart'; import 'package:bike_service_app/app/features/client_panel/my_services/domain/repositories/my_services_repository.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class MyServicesRepoImpl implements MyServicesRepository { @override Stream<QuerySnapshot<Map<String, dynamic>>?> getStream() { try { return FirebaseApiInstances() .firestoreInstance .value .collection('services') .doc(FirebaseAuth.instance.currentUser?.uid) .collection('myservices') .orderBy('Booking ID', descending: true) .snapshots(); } catch (e) { debugPrint( 'Error in MyServicesRepoImpl while calling getStream() method = $e'); } throw UnimplementedError( 'Unimplemented Error in MyServicesRepoImpl for getStream() method of MyServicesRepository abstract class'); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/presentation
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/presentation/controllers/my_services_controller.dart
import 'package:bike_service_app/app/features/client_panel/my_services/domain/use_cases/my_services_use_case.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:get/get.dart'; class MyServicesController extends GetxController { final MyServicesUseCase myServicesUseCase; MyServicesController(this.myServicesUseCase); @override void onInit() { super.onInit(); fetchStreamData(); } // variable to store Stream // Rx<Stream<QuerySnapshot<Map<String, dynamic>>>?> streamData = // Rx<Stream<QuerySnapshot<Map<String, dynamic>>>?>(null); // method to fetch stream Stream<QuerySnapshot<Map<String, dynamic>>?> fetchStreamData() { return myServicesUseCase.callForStream(); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/presentation
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/presentation/widgets/empty_widget.dart
import 'package:flutter/material.dart'; class EmptyWidget extends StatelessWidget { const EmptyWidget({super.key}); @override Widget build(BuildContext context) { return const Column( children: [ Text('0 Scheduled Service !'), ], ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/presentation/pages/my_services_page/my_services_page.dart
// ignore_for_file: avoid_unnecessary_containers import 'package:bike_service_app/app/features/client_panel/my_services/presentation/widgets/empty_widget.dart'; import 'package:bike_service_app/app/global/widget_components/app_bar/appbar.dart'; import 'package:bike_service_app/app/global/widget_components/drawer/drawer.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../../../core/constants/theme/colors/colors.dart'; import '../../../../../../core/constants/theme/textstyles/textstyle.dart'; import '../../../../authentication/presentation/controllers/bottom_navigation/bottom_navigation_controller.dart'; import '../../controllers/my_services_controller.dart'; class MyServicesPage extends StatelessWidget { MyServicesPage({super.key}); // for dealing with BottomNavigationBar final BottomNavigationController bottomNavigationController = Get.put(BottomNavigationController()); // for dealing with Stream<QuerySnapshot<Map<String, dynamic>>> type data final MyServicesController myServicesController = Get.find(); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, backgroundColor: AppColors.backSheetColor, appBar: appBar('My Services'), drawer: DrawerWidget(), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ // Heading const Row( children: [ Expanded( child: Text( 'Your Services', style: AppTextStyleTheme.scheduleSummaryTitleText, ), ) ], ), const SizedBox( height: 20, ), // Service Card Container( child: StreamBuilder( stream: myServicesController.fetchStreamData(), builder: (context, snapshot) { if (!snapshot.hasData) { return const Center( child: EmptyWidget(), ); } else { return ListView.builder( physics: const ClampingScrollPhysics(), shrinkWrap: true, primary: false, padding: const EdgeInsets.symmetric(vertical: 10), itemCount: snapshot.data?.docs.length, itemBuilder: (context, index) { // Getting each Document by index QueryDocumentSnapshot<Map<String, dynamic>>? docSnapshot = snapshot.data?.docs[index]; return Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: Card( margin: EdgeInsets.zero, color: AppColors.serviceCardColor, child: Padding( padding: const EdgeInsets.all(12.0), child: Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Left side Expanded( child: Container( decoration: const BoxDecoration( border: Border(right: BorderSide()), ), child: Column( children: [ // title const Row( children: [ Expanded( child: Text( 'Ganpati Motors', style: AppTextStyleTheme .myServicesCardTitleText, textAlign: TextAlign.center, ), ) ], ), const SizedBox( height: 15, ), // values Row( children: [ const Expanded( child: Text( 'Booking ID', style: AppTextStyleTheme .scheduleSummaryKeyText, ), ), Expanded( child: Text( '${docSnapshot?['Booking ID'].toString()}', style: AppTextStyleTheme .scheduleSummaryValueText, textAlign: TextAlign.center, ), ), ], ), const SizedBox( height: 5, ), const Row( children: [ Expanded( child: Text( 'Bike Number', style: AppTextStyleTheme .scheduleSummaryKeyText, ), ), ], ), Row( children: [ Expanded( child: Text( docSnapshot?[ 'Bike Number'], style: AppTextStyleTheme .scheduleSummaryValueText, ), ), ], ), const Divider(endIndent: 10), Row( children: [ Expanded( child: Text( docSnapshot?[ 'Service Date'], style: AppTextStyleTheme .myServicesCardDateText, ), ), ], ), const SizedBox( height: 5, ), Row( children: [ Expanded( child: Text( docSnapshot?[ 'Service Time'], style: AppTextStyleTheme .myServicesCardDateText, ), ), ], ), ], ), ), ), // Right side Expanded( child: Container( child: Column( children: [ // title const Row( children: [ Expanded( child: Text( 'Service Status', style: AppTextStyleTheme .myServicesCardTitleText, textAlign: TextAlign.center, ), ) ], ), const SizedBox( height: 15, ), // values Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ const Expanded( child: Text( 'Service', style: AppTextStyleTheme .scheduleSummaryKeyText, textAlign: TextAlign.center, ), ), Expanded( child: Container( padding: const EdgeInsets .all(1), color: (docSnapshot?[ 'Service Status'] [ 'service'] == 'Not Started') ? AppColors .notStartedBoxColor : (docSnapshot?['Service Status'] [ 'service'] == 'Running') ? AppColors .pendingOrRuningBoxColor : AppColors .doneOrPaidBoxColor, child: Text( docSnapshot?[ 'Service Status'] ['service'], style: AppTextStyleTheme .myServicesCardServiceStatusValueText, textAlign: TextAlign.center, ), ), ), ], ), const SizedBox( height: 10, ), Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ const Expanded( child: Text( 'Amount', style: AppTextStyleTheme .scheduleSummaryKeyText, textAlign: TextAlign.center, ), ), Expanded( child: Container( padding: const EdgeInsets .all(1), color: (docSnapshot?[ 'Service Status'] [ 'amount'] == 'Pending') ? AppColors .pendingOrRuningBoxColor : (docSnapshot?['Service Status'] [ 'amount'] == 'Paid') ? AppColors .doneOrPaidBoxColor : AppColors .notStartedBoxColor, child: Text( docSnapshot?[ 'Service Status'] ['amount'], style: AppTextStyleTheme .myServicesCardServiceStatusValueText, textAlign: TextAlign.center, ), ), ), ], ), const SizedBox( height: 10, ), const Divider(indent: 10), Row( children: [ const Expanded( child: Padding( padding: EdgeInsets.only( left: 5), child: Text( 'Total Amount', style: AppTextStyleTheme .scheduleSummaryKeyText, textAlign: TextAlign.right, ), ), ), Expanded( child: Text( docSnapshot?[ 'Total Price'], style: AppTextStyleTheme .scheduleSummaryValueText, textAlign: TextAlign.center, ), ) ], ), ], ), ), ), ], ) ], ), ), ), ); }, ); } }, ), ), ], ), ), ), bottomNavigationBar: Obx( () => BottomNavigationBar( showSelectedLabels: true, showUnselectedLabels: true, backgroundColor: AppColors.backSheetColor, currentIndex: bottomNavigationController.tabIndex.value, selectedItemColor: AppColors.frontSheetColor, unselectedItemColor: AppColors.frontSheetColor.withOpacity(0.5), onTap: (value) { bottomNavigationController.changeTabIndex(value); }, items: const [ BottomNavigationBarItem( icon: Icon( Icons.home, ), label: 'Home', ), BottomNavigationBarItem( icon: Icon( Icons.auto_awesome_motion_rounded, ), label: 'Services', ), ], ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/domain/use_cases/my_services_use_case.dart
import 'package:bike_service_app/app/features/client_panel/my_services/domain/repositories/my_services_repository.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; class MyServicesUseCase { final MyServicesRepository myServicesRepository; MyServicesUseCase(this.myServicesRepository); Stream<QuerySnapshot<Map<String, dynamic>>?> callForStream() { try { return myServicesRepository.getStream(); } catch (e) { debugPrint( 'Error in MyServicesUseCase class while calling myServicesRepository.getStream()'); } throw UnimplementedError( 'Unimplemented Error in MyServicesUseCase class while calling getStream() method of MyServicesRepository abstract class'); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/my_services/domain/repositories/my_services_repository.dart
import 'package:cloud_firestore/cloud_firestore.dart'; abstract class MyServicesRepository { Stream<QuerySnapshot<Map<String, dynamic>>?> getStream(); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/data/repositories_implement
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/data/repositories_implement/service_page_repo_impl/service_page_repo_impl.dart
import 'package:bike_service_app/app/features/client_panel/services/domain/repositories/service_page_repositories/service_page_repository.dart'; import 'package:flutter/material.dart'; import '../../../../../../core/constants/assets_path/asset_path.dart'; class ServicePageRepoImpl implements ServicePageRepository { @override List<Map<String, dynamic>> serviceList() { try { return [ { "image": AssetPaths.regularTuneUp, "name": "Regular Tune-Up", "description": "Keep your bike performing at its best with our regular tune-up service. We check and adjust essential components, including brakes, gears, and tire pressure." }, { "image": AssetPaths.oilAndLubrication, "name": "Oil and Lubrication", "description": "Ensure optimal performance and longevity with our professional oil and lubrication services. We use high-quality products to keep your bike running smoothly." }, { "image": AssetPaths.brakeInspectionAndAdjustment, "name": "Brake Inspection and Adjustment", "description": "Safety is our priority. Our experts meticulously inspect and adjust your bike's brakes to guarantee reliable stopping power." }, { "image": AssetPaths.chainMaintenance, "name": "Chain Maintenance", "description": "A well-maintained chain is crucial for a smooth ride. We clean, lubricate, and adjust your bike's chain for optimal efficiency." }, { "image": AssetPaths.wheelAlignment, "name": "Wheel Alignment", "description": "Improve handling and stability with our precise wheel alignment services. We make sure your wheels are perfectly aligned for a safer ride." } ]; } catch (e) { debugPrint('Error in ServicePageRepoImpl = $e'); } throw UnimplementedError( 'Error in ServicePageRepoImpl class for serviceList()'); } @override List<Map<String, dynamic>> customerTestimonialList() { try { return [ { "name": "Rajesh Kumar", "city": "Beawar, Rajasthan", "description": "Incredible bike service experience! Quick turnaround, fair pricing, and my bike runs like new. Highly recommend these guys for hassle-free maintenance." }, { "name": "Ananya Singh", "city": "Beawar, Rajasthan", "description": "The team here knows bikes inside out! Professional service, genuine advice, and my ride feels smoother than ever. No more worries about maintenance headaches." }, { "name": "Vikas Sahu", "city": "Beawar, Rajasthan", "description": "After service, there are no problems left in my bike. Excellent Service !" } ]; } catch (e) { debugPrint( 'Error in ServicePageRepoImpl class for customerTestimonialList() = $e'); } throw UnimplementedError( 'Error in ServicePageRepoImpl class for customerTestimonialList()'); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/presentation/controllers/service_page_controller/service_page_controller.dart
import 'package:bike_service_app/app/features/client_panel/services/domain/use_cases/service_page_usecase/service_page_usecase.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class ServicePageController extends GetxController { final ServicePageUseCase servicePageUseCase; ServicePageController(this.servicePageUseCase); // List of Maps for Featured Services List var serviceListData = [].obs; // List of Maps for Customer Testmonial List var customerTestimonialListData = [].obs; @override void onInit() { super.onInit(); fetchServiceListData(); fetchCustomerTestimonialListData(); } // Fetching List of Maps for Featured Services List List<Map<String, dynamic>> fetchServiceListData() { return serviceListData.value = servicePageUseCase.callForServiceList(); } // Fetching List of Maps for Customer Testmonial List List<Map<String, dynamic>> fetchCustomerTestimonialListData() { return customerTestimonialListData.value = servicePageUseCase.callForCustomerTestimonialList(); } /// Other Functionalities for ServicesPage // Feature [1] ( to Open/Close the BottomSheet and to update currentIndex value on "Know More" button click ) // variable to open / close the BottomSheet var isOpen = false.obs; // variable to change current selected card's index var currentIndex = 0.obs; // Method to Opoen/Close bottom sheet + to update the currentIndex value void bottomSheetShowClose(int index) { if (!isOpen.value) { currentIndex.value = index; isOpen.value = true; } else { isOpen.value = false; } } // Feature [2] ( to fetch the Total No. of Ducuments Count and store it inside the variable ) // variable to store Document Count var nextBookingId = 0.obs; // Method to Fetch and store total no. of document count Future<void> fetchNextBookingId() async { // Returns number of documents in users collection try { await FirebaseFirestore.instance .collection("services") .doc(FirebaseAuth.instance.currentUser!.uid) .collection("myservices") .count() .get() .then( (res) => nextBookingId.value = res.count!, onError: (e) => debugPrint("Error fetching total no. of document count: $e"), ); } catch (e) { debugPrint( 'error in ServicePageController in fetchNextBookingId() Method = $e'); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/presentation/pages/service_page/service_page.dart
// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace import 'package:bike_service_app/app/core/constants/theme/colors/colors.dart'; import 'package:bike_service_app/app/core/constants/theme/textstyles/textstyle.dart'; import 'package:bike_service_app/app/features/client_panel/services/presentation/controllers/service_page_controller/service_page_controller.dart'; import 'package:bike_service_app/app/global/widget_components/app_bar/appbar.dart'; import 'package:bike_service_app/app/global/widget_components/snackbar/snackbar.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../../../schedule_service/presentation/pages/schedule_service_page/schedule_service_page.dart'; class ServicePage extends StatelessWidget { ServicePage({super.key}); // controller final ServicePageController servicePageController = Get.find(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.backSheetColor, appBar: appBar('Services'), // drawer: DrawerWidget(), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, children: [ // Featured Services Part // Heading const Row( children: [ Text( 'Check Our Featured Services', style: AppTextStyleTheme.headingMainTitleText, ), ], ), const SizedBox( height: 15, ), // ListView.builder for Featured Services SizedBox( child: ListView.builder( physics: const ClampingScrollPhysics(), shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: servicePageController.serviceListData.length, itemBuilder: (context, index) { return Container( height: 150, padding: const EdgeInsets.all(0), child: Card( margin: const EdgeInsets.symmetric(vertical: 15), color: AppColors.serviceCardColor, child: Row( children: [ Expanded( child: Container( child: Image.asset( servicePageController.serviceListData[index] ["image"], scale: 1), ), ), Expanded( child: Container( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(right: 20), child: Row( children: [ Expanded( child: Text( servicePageController .serviceListData[index] ["name"], style: AppTextStyleTheme .cardTitleText, ), ), ], ), ), Padding( padding: const EdgeInsets.only(right: 20), child: Row( children: [ Expanded( child: ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all( const LinearBorder()), backgroundColor: MaterialStateProperty.all( AppColors .knowMoreButtonColor), ), onPressed: () { servicePageController .bottomSheetShowClose( index); }, child: const Text('Know More', style: AppTextStyleTheme .cardButtonText), ), ), ], ), ), ], ), ), ), ], ), ), ); }, ), ), const SizedBox( height: 35, ), // Customer Testimonial Part // Heading const Row( children: [ Text( 'What customer says about us', style: AppTextStyleTheme.headingMainTitleText, ), ], ), const SizedBox( height: 15, ), // ListView.builder for Customer Testimonials SizedBox( height: 350, child: ListView.builder( physics: const ClampingScrollPhysics(), shrinkWrap: true, scrollDirection: Axis.horizontal, itemCount: servicePageController.customerTestimonialListData.length, itemBuilder: (context, index) { return Container( // height: 300, width: 250, child: Card( elevation: 3, surfaceTintColor: AppColors.backSheetColor, shadowColor: AppColors.serviceCardColor, margin: const EdgeInsets.symmetric( horizontal: 10, vertical: 10), child: Padding( padding: const EdgeInsets.all(12.0), child: Column( children: [ const Expanded( flex: 1, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.format_quote), ], ), ), Expanded( flex: 4, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Text( servicePageController .customerTestimonialListData[ index]["description"], style: AppTextStyleTheme .customerAddressText, textAlign: TextAlign.center, ), ), ], ), ), Expanded( flex: 1, child: Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( servicePageController .customerTestimonialListData[ index]["name"], style: AppTextStyleTheme .customerNameText, textAlign: TextAlign.center, ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( servicePageController .customerTestimonialListData[ index]["city"], style: AppTextStyleTheme .customerAddressText, textAlign: TextAlign.center, ), ], ), ], ), ), ], ), )), ); }, ), ), const SizedBox( height: 45, ), // Schedule Bike Service Button ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(AppColors.mainButtonColor), ), onPressed: () async { // fetching and storing nextBookingId number | and then passing it to next page ( ScheduleServicePage ) try { await servicePageController.fetchNextBookingId(); snackbarWidget( 'New Booking ID Generated !', '[ Booking ID = ${servicePageController.nextBookingId.value} ]', AppColors.snackBarColorSuccess); await Get.to(() => ScheduleServicePage( bookingId: servicePageController.nextBookingId.value, )); } catch (e) { debugPrint( 'error in ServicePage while Fetching Next BookingID & Navigating to ScheduleServicePage = $e'); } }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 16), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Schedule Bike Service', style: AppTextStyleTheme.buttonMainText, ), SizedBox( width: 5, ), Icon(Icons.arrow_right_alt_sharp, color: Colors.white), ], ), ), ), const SizedBox( height: 45, ), ], ), ), ), // BottomSheet // This BottomSheet will Open / Close according to current value of ( isOpen ) Bool variable bottomSheet: Obx( () => servicePageController.isOpen.value ? BottomSheet( showDragHandle: false, enableDrag: false, onClosing: () {}, builder: (context) { return Padding( padding: const EdgeInsets.all(24.0), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Padding( padding: const EdgeInsets.symmetric(vertical: 15), child: Text( servicePageController.serviceListData[ servicePageController .currentIndex.value]["name"], style: AppTextStyleTheme.cardTitleText, textAlign: TextAlign.center, ), ), ), ], ), Flexible( fit: FlexFit.loose, child: Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.symmetric(vertical: 20), child: Text( servicePageController.serviceListData[ servicePageController .currentIndex.value]["description"], style: AppTextStyleTheme.descriptionText, textAlign: TextAlign.center, ), ), ) ], ), ), const SizedBox(height: 20), ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all( AppColors.mainButtonColor), ), onPressed: () { servicePageController.bottomSheetShowClose(0); }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text( 'Close', style: AppTextStyleTheme.closeButtonText, ), ), ), const SizedBox(height: 20), ], ), ); }, ) : const SizedBox(), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/domain/use_cases
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/domain/use_cases/service_page_usecase/service_page_usecase.dart
import 'package:bike_service_app/app/features/client_panel/services/domain/repositories/service_page_repositories/service_page_repository.dart'; class ServicePageUseCase { final ServicePageRepository servicePageRepository; ServicePageUseCase(this.servicePageRepository); List<Map<String, dynamic>> callForServiceList() { return servicePageRepository.serviceList(); } List<Map<String, dynamic>> callForCustomerTestimonialList() { return servicePageRepository.customerTestimonialList(); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/domain/repositories
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/services/domain/repositories/service_page_repositories/service_page_repository.dart
abstract class ServicePageRepository { List<Map<String, dynamic>> serviceList(); List<Map<String, dynamic>> customerTestimonialList(); }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/data
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/data/repositories_implement/schedule_service_repo_impl.dart
import 'package:bike_service_app/app/features/client_panel/schedule_service/domain/repositories/schedule_service_repositories.dart'; import 'package:flutter/material.dart'; import '../../../../../core/constants/assets_path/asset_path.dart'; class ScheduleServiceRepoImpl implements ScheduleServiceRepositories { @override List<Map<String, dynamic>> servicesList() { try { return [ { "image": AssetPaths.regularTuneUp, "name": "Regular Tune-Up", "price": 150 }, { "image": AssetPaths.oilAndLubrication, "name": "Oil and Lubrication", "price": 250 }, { "image": AssetPaths.brakeInspectionAndAdjustment, "name": "Brake Inspection and Adjustment", "price": 180 }, { "image": AssetPaths.chainMaintenance, "name": "Chain Maintenance", "price": 120 }, { "image": AssetPaths.wheelAlignment, "name": "Wheel Alignment", "price": 350 } ]; } catch (e) { debugPrint('Error in ScheduleServiceRepoImpl = $e'); } throw UnimplementedError( 'Error in ScheduleServiceRepoImpl class for servicesList()'); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/presentation/controllers
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/presentation/controllers/schedule_service_page_controller/schedule_service_page_controller.dart
// ignore_for_file: use_build_context_synchronously import 'package:bike_service_app/app/features/client_panel/schedule_service/domain/use_cases/schedule_service_usecase.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; class ScheduleServicePageController extends GetxController { final ScheduleServicePageUseCase scheduleServicePageUseCase; ScheduleServicePageController(this.scheduleServicePageUseCase); /// Form // Form Global Key final formKey = GlobalKey<FormState>().obs; // TextFormField Controllers final bikeNameController = TextEditingController().obs; final bikeNumberPlateController = TextEditingController().obs; final mobileNumberController = TextEditingController().obs; final fullAdressController = TextEditingController().obs; final describeHereController = TextEditingController().obs; final serviceDateController = TextEditingController( text: DateFormat.yMMMEd().format(DateTime.now()).toString()) .obs; final serviceTimeController = TextEditingController(text: DateFormat.jm().format(DateTime.now())).obs; /// List of Maps with Checkbox Logic // List of Maps Variable for Fetching Services List var servicesListData = [].obs; @override void onInit() { super.onInit(); fetchServicesListData(); } // List of Maps Variable for Storing Selected Services List Data var selectedServicesListData = [].obs; // unique index for each Checkbox List<bool> isChecked = [false, false, false, false, false].obs; // Fetching List of Maps for Services List List<Map<String, dynamic>> fetchServicesListData() { return servicesListData.value = scheduleServicePageUseCase.callForServicesList(); } /// Other Functionalities // Date picker Future selectDate(BuildContext context) async { DateTime? picked = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2024), lastDate: DateTime(2034)); if (picked != null) { serviceDateController.value.text = DateFormat.yMMMEd().format(picked).toString(); } } // Time picker Future selectTime(BuildContext context) async { TimeOfDay? picked = await showTimePicker( context: context, initialTime: TimeOfDay.now(), ); if (picked != null) { serviceTimeController.value.text = picked.format(context); } } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/presentation/pages
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/presentation/pages/schedule_service_page/schedule_service_page.dart
// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace import 'package:bike_service_app/app/core/constants/theme/colors/colors.dart'; import 'package:bike_service_app/app/core/constants/theme/textstyles/textstyle.dart'; import 'package:bike_service_app/app/global/widget_components/snackbar/snackbar.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import '../../../../../../global/widget_components/app_bar/appbar.dart'; import '../../../../schedule_summary/presentation/pages/schedule_summary_page/schedule_summary_page.dart'; import '../../controllers/schedule_service_page_controller/schedule_service_page_controller.dart'; class ScheduleServicePage extends StatelessWidget { // next Unique Booking ID stored inside this variable final int? bookingId; ScheduleServicePage({super.key, this.bookingId}); // controller final ScheduleServicePageController scheduleServicePageController = Get.find(); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, backgroundColor: AppColors.backSheetColor, appBar: appBar('Schedule Service'), // drawer: DrawerWidget(), body: Container( height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 24.0), decoration: const BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(32.0)), color: AppColors.frontSheetColor, ), child: SingleChildScrollView( // Form ( Bike Details for Scheduling the Service ) child: Form( key: scheduleServicePageController.formKey.value, autovalidateMode: AutovalidateMode.onUserInteraction, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Heading [1] const Row( children: [ Expanded( child: Text( 'Your bike details', style: AppTextStyleTheme.headingMainTitleText, ), ), ], ), const SizedBox( height: 15, ), // bike name/model TextFormField( controller: scheduleServicePageController.bikeNameController.value, keyboardType: TextInputType.text, decoration: const InputDecoration( labelText: 'Enter Bike Name / Model', hintText: 'Example = Pulsar 150cc', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty) { return 'Please Enter Bike Name/Model'; } else { return null; } }, ), const SizedBox( height: 15, ), // bike plate number TextFormField( controller: scheduleServicePageController .bikeNumberPlateController.value, keyboardType: TextInputType.text, decoration: const InputDecoration( labelText: 'Enter Bike Number Plate Detail', hintText: 'Example = RJ-36-4042', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty) { return 'Please Enter Bike Number Plate Details'; } else { return null; } }, ), const SizedBox( height: 50, ), // Heading [2] const Row( children: [ Text( 'Contact Information', style: AppTextStyleTheme.headingMainTitleText, ), ], ), const SizedBox( height: 15, ), // Mobile number TextFormField( controller: scheduleServicePageController .mobileNumberController.value, keyboardType: TextInputType.number, decoration: const InputDecoration( labelText: 'Enter your Mobile Number', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty || value.length < 10) { return 'Please Enter your Mobile Number'; } else if (value.length > 10) { return '10 Digit Mobile Number only'; } else { return null; } }, ), const SizedBox( height: 15, ), // Full Address TextFormField( controller: scheduleServicePageController.fullAdressController.value, keyboardType: TextInputType.text, decoration: const InputDecoration( labelText: 'Enter your Full Address', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), validator: (value) { if (value!.isEmpty) { return 'Please Enter your Full Address'; } else { return null; } }, ), const SizedBox( height: 50, ), // Heading [3] const Row( children: [ Expanded( child: Text( 'Select services for your bike', style: AppTextStyleTheme.headingMainTitleText, ), ), ], ), const Row( children: [ Expanded( child: Text( 'To choose the service, just check the Box', style: AppTextStyleTheme.descriptionText, ), ), ], ), const SizedBox( height: 15, ), // Services List with Checkbox SizedBox( child: ListView.builder( physics: const ClampingScrollPhysics(), shrinkWrap: true, primary: false, scrollDirection: Axis.vertical, itemCount: scheduleServicePageController.servicesListData.length, itemBuilder: (context, index) { return Container( height: 150, padding: const EdgeInsets.all(0), child: Card( margin: const EdgeInsets.symmetric(vertical: 15), color: AppColors.serviceCardColor, elevation: 4, child: Row( children: [ Expanded( flex: 2, child: Container( child: Image.asset( scheduleServicePageController .servicesListData[index]["image"]), ), ), Expanded( flex: 2, child: Container( child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Padding( padding: const EdgeInsets.only(left: 15), child: Text( scheduleServicePageController .servicesListData[index] ["name"], style: AppTextStyleTheme.cardTitleText, ), ), ), ], ), ), ), Expanded( flex: 1, child: Container( child: Obx( () => Checkbox( value: scheduleServicePageController .isChecked[index], onChanged: (bool? value) { scheduleServicePageController .isChecked[index] = value!; if (scheduleServicePageController .isChecked[index]) { debugPrint('true'); scheduleServicePageController .selectedServicesListData .add(scheduleServicePageController .servicesListData[index]); debugPrint( '${scheduleServicePageController.selectedServicesListData}'); } else { debugPrint('false'); scheduleServicePageController .selectedServicesListData .removeWhere( (element) => element['name'] == scheduleServicePageController .servicesListData[index] ['name'], ); debugPrint( '${scheduleServicePageController.selectedServicesListData}'); } }, ), ), ), ), ], ), ), ); }, ), ), const SizedBox( height: 50, ), // const Row( children: [ Expanded( child: Text( 'Any additional issues in your bike ?', style: AppTextStyleTheme.descriptionText, ), ), ], ), const Row( children: [ Expanded( child: Text( 'Describe Here - ', style: AppTextStyleTheme.descriptionText, ), ), ], ), const SizedBox( height: 10, ), // Additional Issues TextFormField( maxLines: 4, controller: scheduleServicePageController .describeHereController.value, keyboardType: TextInputType.multiline, decoration: const InputDecoration( labelText: 'Describe here [ Optional ]', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), ), const SizedBox( height: 50, ), // Heading [4] const Row( children: [ Expanded( child: Text( 'Schedule Service Timing', style: AppTextStyleTheme.headingMainTitleText, ), ), ], ), const Row( children: [ Expanded( child: Text( '[ Between 9:00 AM - 4:00 PM ]', style: AppTextStyleTheme.descriptionText, ), ), ], ), const SizedBox( height: 20, ), // service date Obx( () => TextFormField( showCursor: false, enableInteractiveSelection: false, controller: scheduleServicePageController .serviceDateController.value, keyboardType: TextInputType.none, decoration: const InputDecoration( labelText: 'Select Date', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), onTap: () async { // Below line stops keyboard from appearing FocusScope.of(context).requestFocus(FocusNode()); // Show Date Picker Here try { await scheduleServicePageController.selectDate(context); } catch (e) { debugPrint('error in date picker = $e'); } }, validator: (value) { if (value!.isEmpty) { return 'Please Select Service Date'; } else { return null; } }, ), ), // const SizedBox( height: 15, ), // service Time Obx( () => TextFormField( showCursor: false, enableInteractiveSelection: false, controller: scheduleServicePageController .serviceTimeController.value, keyboardType: TextInputType.none, decoration: const InputDecoration( labelText: 'Select Time', filled: true, fillColor: AppColors.inputTextBoxInnerColor, border: OutlineInputBorder(), ), onTap: () async { // Below line stops keyboard from appearing FocusScope.of(context).requestFocus(FocusNode()); // Show Time Picker Here try { await scheduleServicePageController.selectTime(context); } catch (e) { debugPrint('error in time picker = $e'); } }, validator: (value) { if (value!.isEmpty) { return 'Please Select Service Time'; } else if (value == DateFormat.jm().format(DateTime.now()).toString()) { return 'Please Select New Service Time'; } else { return null; } }, ), ), const SizedBox( height: 50, ), // Button for navigating to ScheduleSummaryPage ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(AppColors.mainButtonColor), ), onPressed: () { // Checking if Form is Valid or not if (scheduleServicePageController .formKey.value.currentState! .validate()) { // if Form is valid without any error // then we save the current state of form with values scheduleServicePageController.formKey.value.currentState! .save(); // Passing field values to next ScheduleSummaryPage if (scheduleServicePageController .selectedServicesListData.isEmpty) { snackbarWidget('Alert', 'Select Desired Service !', AppColors.snackBarColorWarning); } else { // creating new serviceStatus variable of type Map // to store Default Service Status values // we also pass this value to the ScheduleSummaryPage var serviceStatus = { "Service Status": { "service": "Not Started", "amount": "Pending" } }; // Navigating to ScheduleSummaryPage with valid Form field values Get.to( () => ScheduleSummaryPage( bookingId: bookingId, bikeName: scheduleServicePageController .bikeNameController.value.text, bikeNumber: scheduleServicePageController .bikeNumberPlateController.value.text, mobileNumber: scheduleServicePageController .mobileNumberController.value.text, fullAddress: scheduleServicePageController .fullAdressController.value.text, selectedServiceList: scheduleServicePageController .selectedServicesListData .toList(), serviceDate: scheduleServicePageController .serviceDateController.value.text, serviceTime: scheduleServicePageController .serviceTimeController.value.text, serviceStatus: serviceStatus, ), ); } // Debuging // Checking saved Values debugPrint('Form Saved'); debugPrint( 'bikeName = ${scheduleServicePageController.bikeNameController.value.text}'); debugPrint( 'bikeNumber = ${scheduleServicePageController.bikeNumberPlateController.value.text}'); debugPrint( 'mobileNumber = ${scheduleServicePageController.mobileNumberController.value.text}'); debugPrint( 'fullAddress = ${scheduleServicePageController.fullAdressController.value.text}'); debugPrint( 'selectedServiceList = ${scheduleServicePageController.selectedServicesListData.toList()}'); debugPrint( 'serviceDate = ${scheduleServicePageController.serviceDateController.value.text}'); debugPrint( 'serviceTime = ${scheduleServicePageController.serviceTimeController.value.text}'); } else { // Showing Snackbar for user, so that they know that fields are Empty snackbarWidget('Alert', 'Fill the Information !', AppColors.snackBarColorWarning); // Debuging // Checking saved invalid Values debugPrint('Current Form State is not valid'); debugPrint( 'bikeName = ${scheduleServicePageController.bikeNameController.value.text}'); debugPrint( 'bikeNumber = ${scheduleServicePageController.bikeNumberPlateController.value.text}'); debugPrint( 'mobileNumber = ${scheduleServicePageController.mobileNumberController.value.text}'); debugPrint( 'fullAddress = ${scheduleServicePageController.fullAdressController.value.text}'); debugPrint( 'selectedServiceList = ${scheduleServicePageController.selectedServicesListData.toList()}'); debugPrint( 'serviceDate = ${scheduleServicePageController.serviceDateController.value.text}'); debugPrint( 'serviceTime = ${scheduleServicePageController.serviceTimeController.value.text}'); } }, child: const Padding( padding: EdgeInsets.symmetric(vertical: 16), child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'View Receipt Summary', style: AppTextStyleTheme.buttonMainText, ), SizedBox( width: 5, ), Icon(Icons.arrow_right_alt_sharp, color: Colors.white), ], ), ), ), const SizedBox( height: 50, ), ], ), ), ), ), ); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/domain/use_cases/schedule_service_usecase.dart
import 'package:bike_service_app/app/features/client_panel/schedule_service/domain/repositories/schedule_service_repositories.dart'; class ScheduleServicePageUseCase { final ScheduleServiceRepositories scheduleServiceRepositories; ScheduleServicePageUseCase(this.scheduleServiceRepositories); List<Map<String, dynamic>> callForServicesList() { return scheduleServiceRepositories.servicesList(); } }
0
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/domain
mirrored_repositories/Bike-Service-App/lib/app/features/client_panel/schedule_service/domain/repositories/schedule_service_repositories.dart
abstract class ScheduleServiceRepositories { List<Map<String, dynamic>> servicesList(); }
0
mirrored_repositories/Bike-Service-App/lib/app/core
mirrored_repositories/Bike-Service-App/lib/app/core/app_bindings/app_bindings.dart
import 'package:bike_service_app/app/features/client_panel/authentication/data/repositories_implement/signup_repositories_impl/signup_repositories_impl.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/domain/repositories/signup_repositories/signup_repositories.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/domain/use_cases/signin_usecase/signin_usecase.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/domain/use_cases/signup_usecases/signup_usecases.dart'; import 'package:bike_service_app/app/features/client_panel/authentication/presentation/controllers/signup_page/signup_controller.dart'; import 'package:bike_service_app/app/features/client_panel/my_services/domain/repositories/my_services_repository.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_service/data/repositories_implement/schedule_service_repo_impl.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_service/domain/repositories/schedule_service_repositories.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_service/domain/use_cases/schedule_service_usecase.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_service/presentation/controllers/schedule_service_page_controller/schedule_service_page_controller.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/data/repositories_implement/schedule_summary_repo_impl.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/repositories/schedule_summary_repositories.dart'; import 'package:bike_service_app/app/features/client_panel/schedule_summary/domain/use_cases/schedule_summary_use_case.dart'; import 'package:bike_service_app/app/features/client_panel/services/data/repositories_implement/service_page_repo_impl/service_page_repo_impl.dart'; import 'package:bike_service_app/app/features/client_panel/services/domain/repositories/service_page_repositories/service_page_repository.dart'; import 'package:bike_service_app/app/features/client_panel/services/domain/use_cases/service_page_usecase/service_page_usecase.dart'; import 'package:bike_service_app/app/features/client_panel/services/presentation/controllers/service_page_controller/service_page_controller.dart'; import 'package:bike_service_app/app/global/widget_components/drawer/drawer_controller.dart'; import 'package:get/get.dart'; import '../../features/client_panel/authentication/data/repositories_implement/signin_repositories_impl/signin_repositories_impl.dart'; import '../../features/client_panel/authentication/domain/repositories/signin_repositories/signin_repositories.dart'; import '../../features/client_panel/authentication/presentation/controllers/signin_page/signin_controller.dart'; import '../../features/client_panel/my_services/data/repositories_implement/my_services_repo_impl.dart'; import '../../features/client_panel/my_services/domain/use_cases/my_services_use_case.dart'; import '../../features/client_panel/my_services/presentation/controllers/my_services_controller.dart'; import '../../features/client_panel/schedule_summary/presentation/controllers/schedule_summary_controller/schedule_summary_controller.dart'; class AppBindings extends Bindings { @override void dependencies() { /// authentication feature Bindings // Bindings for SignUp a User Get.lazyPut<SignUpRepositories>(() => SignUpRepositoryImpl()); Get.lazyPut(() => CreateUserUseCase(Get.find())); Get.put(SignUpController(Get.find())); // Bindings for SignIn a User Get.lazyPut<SignInRepositories>(() => SignInRepositoryImpl()); Get.lazyPut(() => SignInUserUseCase(Get.find())); Get.put(SignInController(Get.find())); /// my_services feature bindings Get.lazyPut<ServicePageRepository>(() => ServicePageRepoImpl()); Get.lazyPut(() => ServicePageUseCase(Get.find())); Get.put(ServicePageController(Get.find())); /// schedule_service feature Bindings Get.lazyPut<ScheduleServiceRepositories>(() => ScheduleServiceRepoImpl()); Get.lazyPut(() => ScheduleServicePageUseCase(Get.find())); Get.put(ScheduleServicePageController(Get.find())); /// schedule_summary feature Bindings Get.lazyPut<ScheduleSummaryRepository>(() => ScheduleSummaryRepoImpl()); Get.lazyPut(() => CreateServiceUseCase(Get.find())); Get.put(ScheduleSummaryController(Get.find())); /// my_services feature Bindings Get.lazyPut<MyServicesRepository>(() => MyServicesRepoImpl()); Get.lazyPut(() => MyServicesUseCase(Get.find())); Get.put(MyServicesController(Get.find())); // DrawerController Binding Get.lazyPut(() => DrawerControllerCommon()); } }
0
mirrored_repositories/Bike-Service-App/lib/app/core/constants
mirrored_repositories/Bike-Service-App/lib/app/core/constants/assets_path/asset_path.dart
class AssetPaths { // Welcome Page Assets Path static const String bikeImage = 'lib/app/core/constants/assets/IntroPage/bike/bike.jpg'; // Services Page Assets Path static const String brakeInspectionAndAdjustment = 'lib/app/core/constants/assets/ServicesPage/Brake_Inspection_and_Adjustment.png'; static const String chainMaintenance = 'lib/app/core/constants/assets/ServicesPage/Chain_Maintenance.png'; static const String oilAndLubrication = 'lib/app/core/constants/assets/ServicesPage/Oil_and_Lubrication.png'; static const String regularTuneUp = 'lib/app/core/constants/assets/ServicesPage/Regular_Tune_Up.png'; static const String wheelAlignment = 'lib/app/core/constants/assets/ServicesPage/Wheel_Alignment.png'; }
0
mirrored_repositories/Bike-Service-App/lib/app/core/constants/theme
mirrored_repositories/Bike-Service-App/lib/app/core/constants/theme/colors/colors.dart
import 'package:flutter/material.dart'; class AppColors { // Sheet Colors static const Color backSheetColor = Color(0xff3C3B3B); static const Color frontSheetColor = Color(0xffFFFFFF); static const Color scheduleSummarySheetColor = Color(0xffD9D9D9); // Input Text Box Colors static const Color inputTextBoxLabelColor = Color(0xff000000); static const Color inputTextBoxInnerColor = Color(0xffF4EFEF); // Button Color static const Color mainButtonColor = Color(0xff343434); static const knowMoreButtonColor = Color(0xff737475); // Card Colors static const Color serviceCardColor = Color(0xffE3E6E9); // Service Status Color static const Color notStartedBoxColor = Color(0xff737475); static const Color pendingOrRuningBoxColor = Color(0xffF4A227); static const Color doneOrPaidBoxColor = Color(0xff3EBF01); // Snackbar Color static const Color snackBarColorSuccess = Color(0xff3EBF01); static const Color snackBarColorWarning = Color(0xffF0952B); static const Color snackBarColorNormal = Color(0xff3C3B3B); }
0
mirrored_repositories/Bike-Service-App/lib/app/core/constants/theme
mirrored_repositories/Bike-Service-App/lib/app/core/constants/theme/textstyles/textstyle.dart
import 'package:flutter/material.dart'; class AppTextStyleTheme { // TextStyles for Welcome Page static const TextStyle welcomeHeadingTitleText = TextStyle( color: Color(0xffFFFFFF), fontSize: 28, fontWeight: FontWeight.bold, ); static const TextStyle welcomeHeadingSubtitleText = TextStyle( color: Color(0xffFFFFFF), fontSize: 24, fontWeight: FontWeight.w600, ); static const TextStyle welcomeHeadingSubtitleDescriptionText = TextStyle( color: Color(0xffFFFFFF), fontSize: 16, fontWeight: FontWeight.w400, ); // TextStyles for TextFormField Label static const TextStyle textFormFieldLabelText = TextStyle( color: Color(0xff000000), fontSize: 14, fontWeight: FontWeight.w400, ); // TextStyles for Page Heading static const TextStyle headingMainTitleText = TextStyle( color: Color(0xff000000), fontSize: 18, fontWeight: FontWeight.w500, ); static const TextStyle headingSecondaryTitleText = TextStyle( color: Color(0xff3B3B3B), fontSize: 16, fontWeight: FontWeight.bold, ); // TextStyles for Card Text static const TextStyle cardTitleText = TextStyle( color: Color(0xff000000), fontSize: 14, fontWeight: FontWeight.w600, ); static const TextStyle cardButtonText = TextStyle( color: Color(0xffFFFFFF), fontSize: 12, fontWeight: FontWeight.w500, ); // TextStyles for Customer Feedback Card static const TextStyle customerNameText = TextStyle( color: Color(0xff000000), fontSize: 16, fontWeight: FontWeight.bold, ); static const TextStyle customerAddressText = TextStyle( color: Color(0xff000000), fontSize: 14, fontWeight: FontWeight.normal, ); // TextStyles for Button Text static const TextStyle buttonMainText = TextStyle( color: Color(0xffFFFFFF), fontSize: 18, fontWeight: FontWeight.normal, ); // TextStyles for Button Text static const TextStyle closeButtonText = TextStyle( color: Color(0xffFFFFFF), fontSize: 18, fontWeight: FontWeight.normal, ); // TextStyles for ScheduleSummary Page static const TextStyle scheduleSummaryTitleText = TextStyle( color: Color(0xff000000), fontSize: 16, fontWeight: FontWeight.bold, ); static const TextStyle scheduleSummarySubTitleText = TextStyle( color: Color(0xff000000), fontSize: 14, fontWeight: FontWeight.w500, ); static const TextStyle scheduleSummaryKeyText = TextStyle( color: Color(0xff000000), fontSize: 13, fontWeight: FontWeight.normal, ); static const TextStyle scheduleSummaryValueText = TextStyle( color: Color(0xff000000), fontSize: 13, fontWeight: FontWeight.w500, ); // TextStyles for MyServicesPage static const TextStyle myServicesCardTitleText = TextStyle( color: Color(0xff000000), fontSize: 15, fontWeight: FontWeight.w700, ); static const TextStyle myServicesCardServiceStatusValueText = TextStyle( color: Color(0xffFFFFFF), fontSize: 13, fontWeight: FontWeight.w500, ); static const TextStyle myServicesCardDateText = TextStyle( color: Color(0xff000000), fontSize: 13, fontWeight: FontWeight.w600, ); // Global usecase TextStyles // TextStyles for App Bar Text static const TextStyle appBarText = TextStyle( color: Color(0xffFFFFFF), fontSize: 20, fontWeight: FontWeight.w500, ); // TextStyles for Description Text static const TextStyle descriptionText = TextStyle( color: Color(0xff000000), fontSize: 14, fontWeight: FontWeight.normal, ); // TextStyles for AlertDialog Title Text static const TextStyle alertDialogTitleText = TextStyle( color: Color(0xff000000), fontSize: 18, fontWeight: FontWeight.normal, ); }
0
mirrored_repositories/Bike-Service-App/lib/app/core
mirrored_repositories/Bike-Service-App/lib/app/core/firebase_api_instances/firebase_api_instances.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:get/get.dart'; class FirebaseApiInstances extends GetxController { // FirebaseAuth Instance for Authentication Operations var authInstance = FirebaseAuth.instance.obs; // FirebaseFirestore Instance for Firestore Database Operations var firestoreInstance = FirebaseFirestore.instance.obs; }
0
mirrored_repositories/Bike-Service-App
mirrored_repositories/Bike-Service-App/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:bike_service_app/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/wanandroid
mirrored_repositories/wanandroid/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flyandroid/SelfWidge/MyScaffold.dart'; import 'package:flyandroid/Pages/HomePage.dart'; import 'package:flyandroid/Pages/GuidePage.dart'; import 'package:flyandroid/Pages/CategoryPage.dart'; import 'package:flyandroid/Pages/MinePage.dart'; import 'package:flyandroid/Api/Constant.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Fly Android 你的玩Android', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(), routes: <String, WidgetBuilder>{ }, ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); final titles = ['首页', '分类', '导航', '我的']; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { var _index = 0; @override Widget build(BuildContext context) { return MaterialScaffod( appBar: AppBar(title: Text(widget.titles[_index]), /*actions: _index < 2 ? <Widget>[ new FlatButton.icon(icon: Icon(Icons.search,color: Colors.white,),label: Text('搜索',style: TextStyle(color: Colors.white),), onPressed: _jumpSearch) ] : null,*/), materialScaffodType: MaterialScaffodType.STACK, childrenContent: <Widget>[ HomePage(), CategoryPage(), GuidePage(), MinePage() ], itembars: <BottomNavigationBarItem>[ BottomNavigationBarItem( title: Text(widget.titles[0]), icon: Icon(Icons.home)), BottomNavigationBarItem( title: Text(widget.titles[1]), icon: Icon(Icons.category)), BottomNavigationBarItem( title: Text(widget.titles[2]), icon: Icon(Icons.blur_circular)), BottomNavigationBarItem( title: Text(widget.titles[3]), icon: Icon(Icons.account_circle)) ], onIndexChanged: (index) { setState(() { Constanct.SELECT_PAGER=index; this._index = index; }); }, ); } void _jumpSearch() { Navigator.of(context).pushNamed("/search"); } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/SelfWidge/MyScaffold.dart
import 'package:flutter/material.dart'; import 'package:flutter/src/scheduler/ticker.dart'; /** * ________________ * |______888_____ | * || || * || || * || || * ||____________|| * |___|__|___|___| * * * */ class MaterialScaffod extends StatefulWidget { final int index; final double iconSize; final AppBar appBar; final itembars; final Key key; final List<Widget> childrenContent; final ValueChanged<int> onIndexChanged; final MaterialScaffodType materialScaffodType; const MaterialScaffod( {this.appBar, this.iconSize = 24.0, this.materialScaffodType = MaterialScaffodType .STACK, this.index, this.onIndexChanged, @required this.childrenContent, @required this.itembars, this.key}) :super(key: key); @override State<StatefulWidget> createState() { switch (materialScaffodType) { case MaterialScaffodType.STACK: return _MaterialScaffodStack(); case MaterialScaffodType.PAGE: return _MaterialPagerState(); case MaterialScaffodType.INDICATED: return _MaterialIndicateState(); default: return _MaterialScaffodStack(); } } } enum MaterialScaffodType { /** * 只绘制一页不能滑动 */ STACK, /** * 绘制多页可以滑动 */ PAGE, /** * 在上面 */ INDICATED } class _MaterialScaffodStack extends State<MaterialScaffod> { int _index; @override void initState() { super.initState(); _index = (widget.index == null ? 0 : widget.index); } @override Widget build(BuildContext context) { return new Scaffold( appBar: widget.appBar, bottomNavigationBar: BottomNavigationBar(iconSize: widget.iconSize, currentIndex: _index, items: widget.itembars, onTap: (index) { if (widget.onIndexChanged != null) { widget.onIndexChanged(index); } setState(() { _index = index; }); }, type: BottomNavigationBarType.fixed), body: IndexedStack( index: _index, children: widget.childrenContent,)); } } class _MaterialPagerState extends State<MaterialScaffod> { int _index; PageController _controller; @override void initState() { super.initState(); _index = (widget.index == null ? 0 : widget.index); _controller = new PageController(initialPage: _index); } @override Widget build(BuildContext context) { return new Scaffold( appBar: widget.appBar, bottomNavigationBar: BottomNavigationBar(key: widget.key, iconSize: widget.iconSize, currentIndex: _index, items: widget.itembars, onTap: (index) { _controller.jumpToPage(index); }, type: BottomNavigationBarType.fixed), body: PageView(key: GlobalKey(), controller: _controller, children: widget.childrenContent, onPageChanged: (page) { widget.onIndexChanged(page); setState(() { _index = page; }); },)); } } class _MaterialIndicateState extends State<MaterialScaffod> implements TickerProvider { TabController _tabController; @override void initState() { // TODO: implement initState super.initState(); _tabController = new TabController(length: widget.itembars.length, vsync: this); _tabController.addListener(call); } @override void dispose() { _tabController.removeListener(call); } void call() { if (widget.onIndexChanged != null) { widget.onIndexChanged(_tabController.index); } } @override Widget build(BuildContext context) { return new Scaffold(appBar: widget.appBar, body: new Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ TabBar( indicatorSize: TabBarIndicatorSize.label, isScrollable: true, tabs: widget.itembars, labelColor: Theme .of(context) .primaryColor, controller: _tabController,), new Expanded(child: new TabBarView( controller: _tabController, children: widget.childrenContent),) ], )); } @override Ticker createTicker(TickerCallback onTick) { return new Ticker(onTick); } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/SelfWidge/carousel_slider.dart
library carousel_slider; import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; int _remander(int input, int source) { final int result = input % source; return result < 0 ? source + result : result; } int _getRealIndex(int position, int base, int length) { final int offset = position - base; return _remander(offset, length); } class CarouselSlider extends StatefulWidget { final List<Widget> items; final num viewportFraction; final num initialPage; final double aspectRatio; final double height; final PageController pageController; final num realPage; final bool autoPlay; final Duration autoPlayDuration; final Curve autoPlayCurve; final Duration interval; final bool reverse; CarouselSlider({ @required this.items, this.viewportFraction: 0.8, this.initialPage: 0, this.aspectRatio: 16/9, this.height, this.realPage: 10000, this.autoPlay: false, this.interval: const Duration(seconds: 4), this.reverse: false, this.autoPlayCurve: Curves.fastOutSlowIn, this.autoPlayDuration: const Duration(milliseconds: 800) }) : pageController = new PageController( viewportFraction: viewportFraction, initialPage: realPage ); @override _CarouselSliderState createState() { return new _CarouselSliderState(); } Future<Null> nextPage({Duration duration, Curve curve}) { return pageController.nextPage(duration: duration, curve: curve); } Future<Null> previousPage({Duration duration, Curve curve}) { return pageController.previousPage(duration: duration, curve: curve); } jumpToPage(int page) { final index = _getRealIndex(pageController.page.toInt(), realPage, items.length); return pageController.jumpToPage(pageController.page.toInt() + page - index); } animateToPage(int page, {Duration duration, Curve curve}) { final index = _getRealIndex(pageController.page.toInt(), realPage, items.length); return pageController.animateToPage( pageController.page.toInt() + page - index, duration: duration, curve: curve ); } } class _CarouselSliderState extends State<CarouselSlider> with TickerProviderStateMixin { int currentPage; @override void initState() { super.initState(); currentPage = widget.initialPage; if (widget.autoPlay) { new Timer.periodic(widget.interval, (_) { widget.pageController.nextPage( duration: widget.autoPlayDuration, curve: widget.autoPlayCurve ); }); } } getWrapper(Widget child) { if (widget.height != null) { return new Container( height: widget.height, child: child ); } else { return new AspectRatio( aspectRatio: widget.aspectRatio, child: child ); } } @override Widget build(BuildContext context) { return getWrapper( new PageView.builder( onPageChanged: (int index) { currentPage = _getRealIndex(index, widget.realPage, widget.items.length); }, controller: widget.pageController, reverse: widget.reverse, itemBuilder: (BuildContext context, int i) { final int index = _getRealIndex(i, 1000, widget.items.length); return new AnimatedBuilder( animation: widget.pageController, builder: (BuildContext context, child) { // on the first render, the pageController.page is null, // this is a dirty hack if (widget.pageController.position.minScrollExtent == null || widget.pageController.position.maxScrollExtent == null) { new Future.delayed(new Duration(microseconds: 1), () { setState(() {}); }); return new Container(); } double value = widget.pageController.page - i; value = (1 - (value.abs() * 0.2)).clamp(0.0, 1.0); final double height = widget.height ?? MediaQuery.of(context).size.width * (1 / widget.aspectRatio); return new Center( child: new SizedBox( height: Curves.easeOut.transform(value) * height, child: child ) ); }, child: widget.items[index] ); }, ) ); } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/SelfWidge/Refresh.dart
// Copyright 2016 The Chromium Authors. 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:async'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; // The over-scroll distance that moves the indicator to its maximum // displacement, as a percentage of the scrollable's container extent. const double _kDragContainerExtentPercentage = 0.25; // How much the scroll's drag gesture can overshoot the RefreshLayout's // displacement; max displacement = _kDragSizeFactorLimit * displacement. const double _kDragSizeFactorLimit = 1.5; // When the scroll ends, the duration of the refresh indicator's animation // to the RefreshLayout's displacement. const Duration _kIndicatorSnapDuration = const Duration(milliseconds: 150); // The duration of the ScaleTransition that starts when the refresh action // has completed. const Duration _kIndicatorScaleDuration = const Duration(milliseconds: 200); /// The signature for a function that's called when the user has dragged a /// [RefreshLayout] far enough to demonstrate that they want the app to /// refresh. The returned [Future] must complete when the refresh operation is /// finished. /// /// Used by [RefreshLayout.onRefresh]. typedef Future<Null> RefreshCallback(bool refresh); typedef LoadingWidgeBuilder(BuildContext context); // The state machine moves through these modes only when the scrollable // identified by scrollableKey has been scrolled to its min or max limit. enum _RefreshLayoutMode { drag, // Pointer is down. armed, // Dragged far enough that an up event will run the onRefresh callback. snap, // Animating to the indicator's final "displacement". refresh, // Running the refresh callback. done, // Animating the indicator's fade-out after refreshing. canceled, // Animating the indicator's fade-out after not arming. } /// A widget that supports the Material "swipe to refresh" idiom. /// /// When the child's [Scrollable] descendant overscrolls, an animated circular /// progress indicator is faded into view. When the scroll ends, if the /// indicator has been dragged far enough for it to become completely opaque, /// the [onRefresh] callback is called. The callback is expected to update the /// scrollable's contents and then complete the [Future] it returns. The refresh /// indicator disappears after the callback's [Future] has completed. /// /// If the [Scrollable] might not have enough content to overscroll, consider /// settings its `physics` property to [AlwaysScrollableScrollPhysics]: /// /// ```dart /// new ListView( /// physics: const AlwaysScrollableScrollPhysics(), /// children: ... // ) /// ``` /// /// Using [AlwaysScrollableScrollPhysics] will ensure that the scroll view is /// always scrollable and, therefore, can trigger the [RefreshLayout]. /// /// A [RefreshLayout] can only be used with a vertical scroll view. /// /// See also: /// /// * <https://material.google.com/patterns/swipe-to-refresh.html> /// * [RefreshLayoutState], can be used to programmatically show the refresh indicator. /// * [RefreshProgressIndicator], widget used by [RefreshLayout] to show /// the inner circular progress spinner during refreshes. /// * [CupertinoRefreshControl], an iOS equivalent of the pull-to-refresh pattern. /// Must be used as a sliver inside a [CustomScrollView] instead of wrapping /// around a [ScrollView] because it's a part of the scrollable instead of /// being overlaid on top of it. class RefreshLayout extends StatefulWidget { /// Creates a refresh indicator. /// /// The [onRefresh], [child], and [notificationPredicate] arguments must be /// non-null. The default /// [displacement] is 40.0 logical pixels. const RefreshLayout({ Key key, @required this.child, this.canrefresh: true, this.canloading: true, this.displacement: 20.0, @required this.onRefresh, this.loadingBuilder, this.color, this.backgroundColor, this.notificationPredicate: defaultScrollNotificationPredicate, }) : assert(child != null), assert(onRefresh != null), assert(onRefresh != null), assert(notificationPredicate != null), super(key: key); /// The widget below this widget in the tree. /// /// The refresh indicator will be stacked on top of this child. The indicator /// will appear when child's Scrollable descendant is over-scrolled. /// /// Typically a [ListView] or [CustomScrollView]. final Widget child; /// The distance from the child's top or bottom edge to where the refresh /// indicator will settle. During the drag that exposes the refresh indicator, /// its actual displacement may significantly exceed this value. final double displacement; /// A function that's called when the user has dragged the refresh indicator /// far enough to demonstrate that they want the app to refresh. The returned /// [Future] must complete when the refresh operation is finished. final RefreshCallback onRefresh; /// The progress indicator's foreground color. The current theme's /// [ThemeData.accentColor] by default. final Color color; /// The progress indicator's background color. The current theme's /// [ThemeData.canvasColor] by default. final Color backgroundColor; /// A check that specifies whether a [ScrollNotification] should be /// handled by this widget. /// /// By default, checks whether `notification.depth == 0`. Set it to something /// else for more complicated layouts. final ScrollNotificationPredicate notificationPredicate; final LoadingWidgeBuilder loadingBuilder; final bool canloading; final bool canrefresh; // void dissmiss() { // if(state!=null) // state._dismiss(_RefreshLayoutMode.canceled); // } // // void show(bool attop) { // if(state!=null) // state.show(atTop: attop); // } // // void setNomore(bool nomore) { // this.nomore = nomore; // } @override RefreshLayoutState createState() => new RefreshLayoutState(); } /// Contains the state for a [RefreshLayout]. This class can be used to /// programmatically show the refresh indicator, see the [show] method. class RefreshLayoutState extends State<RefreshLayout> with TickerProviderStateMixin { AnimationController _positionController; AnimationController _scaleController; Animation<double> _positionFactor; Animation<double> _scaleFactor; Animation<double> _value; Animation<Color> _valueColor; _RefreshLayoutMode _mode; Future<Null> _pendingRefreshFuture; bool _isIndicatorAtTop; double _dragOffset; @override void initState() { super.initState(); _positionController = new AnimationController(vsync: this); _positionFactor = new Tween<double>( begin: 0.0, end: _kDragSizeFactorLimit, ).animate(_positionController); _value = new Tween< double>( // The "value" of the circular progress indicator during a drag. begin: 0.0, end: 0.75, ).animate(_positionController); _scaleController = new AnimationController(vsync: this); _scaleFactor = new Tween<double>( begin: 1.0, end: 0.0, ).animate(_scaleController); initBuilder(); } @override void didChangeDependencies() { final ThemeData theme = Theme.of(context); _valueColor = new ColorTween( begin: (widget.color ?? theme.accentColor).withOpacity(0.0), end: (widget.color ?? theme.accentColor).withOpacity(1.0) ).animate(new CurvedAnimation( parent: _positionController, curve: const Interval(0.0, 1.0 / _kDragSizeFactorLimit) )); super.didChangeDependencies(); } @override void dispose() { _positionController.dispose(); _scaleController.dispose(); super.dispose(); } bool _handleScrollNotification(ScrollNotification notification) { if (!widget.notificationPredicate(notification)) { return false; } if (notification is ScrollStartNotification && notification.metrics.extentBefore == 0.0 && _mode == null && _start(notification.metrics.axisDirection)) { setState(() { _mode = _RefreshLayoutMode.drag; }); return false; } bool indicatorAtTopNow; switch (notification.metrics.axisDirection) { case AxisDirection.down: indicatorAtTopNow = true; break; case AxisDirection.up: indicatorAtTopNow = false; break; case AxisDirection.left: case AxisDirection.right: indicatorAtTopNow = null; break; } if (indicatorAtTopNow != _isIndicatorAtTop) { if (_mode == _RefreshLayoutMode.drag || _mode == _RefreshLayoutMode.armed) { _dismiss(_RefreshLayoutMode.canceled); } /** * ---------------------------------------- */ if (widget.canloading && notification is UserScrollNotification && notification.metrics.extentAfter == 0.0 && notification.direction == ScrollDirection.idle) { show(atTop: false); } } else if (notification is ScrollUpdateNotification) { if (_mode == _RefreshLayoutMode.drag || _mode == _RefreshLayoutMode.armed) { if (notification.metrics.extentBefore > 0.0) { _dismiss(_RefreshLayoutMode.canceled); } else { _dragOffset -= notification.scrollDelta; _checkDragOffset(notification.metrics.viewportDimension); } } } else if (notification is OverscrollNotification) { if (_mode == _RefreshLayoutMode.drag || _mode == _RefreshLayoutMode.armed) { _dragOffset -= notification.overscroll / 2.0; _checkDragOffset(notification.metrics.viewportDimension); } } else if (notification is ScrollEndNotification) { switch (_mode) { case _RefreshLayoutMode.armed: if (widget.canrefresh) _show(); break; case _RefreshLayoutMode.drag: _dismiss(_RefreshLayoutMode.canceled); break; default: // do nothing break; } } return false; } bool _handleGlowNotification(OverscrollIndicatorNotification notification) { if (notification.depth != 0 || !notification.leading) return false; if (_mode == _RefreshLayoutMode.drag) { notification.disallowGlow(); return true; } return false; } bool _start(AxisDirection direction) { assert(_mode == null); assert(_isIndicatorAtTop == null); assert(_dragOffset == null); switch (direction) { case AxisDirection.down: _isIndicatorAtTop = true; break; case AxisDirection.up: _isIndicatorAtTop = false; break; case AxisDirection.left: case AxisDirection.right: _isIndicatorAtTop = null; // we do not support horizontal scroll views. return false; } _dragOffset = 0.0; _scaleController.value = 0.0; _positionController.value = 0.0; return true; } void _checkDragOffset(double containerExtent) { assert(_mode == _RefreshLayoutMode.drag || _mode == _RefreshLayoutMode.armed); double newValue = _dragOffset / (containerExtent * _kDragContainerExtentPercentage); if (_mode == _RefreshLayoutMode.armed) newValue = math.max(newValue, 1.0 / _kDragSizeFactorLimit); _positionController.value = newValue.clamp(0.0, 1.0); // this triggers various rebuilds if (_mode == _RefreshLayoutMode.drag && _valueColor.value.alpha == 0xFF) _mode = _RefreshLayoutMode.armed; } // Stop showing the refresh indicator. Future<Null> _dismiss(_RefreshLayoutMode newMode) async { // This can only be called from _show() when refreshing and // _handleScrollNotification in response to a ScrollEndNotification or // direction change. assert(newMode == _RefreshLayoutMode.canceled || newMode == _RefreshLayoutMode.done); setState(() { _mode = newMode; }); switch (_mode) { case _RefreshLayoutMode.done: await _scaleController.animateTo( 1.0, duration: _kIndicatorScaleDuration); break; case _RefreshLayoutMode.canceled: await _positionController.animateTo( 0.0, duration: _kIndicatorScaleDuration); break; default: assert(false); } if (mounted && _mode == newMode) { _dragOffset = null; _isIndicatorAtTop = null; setState(() { _mode = null; }); } } void _show() { assert(_mode != _RefreshLayoutMode.refresh); assert(_mode != _RefreshLayoutMode.snap); final Completer<Null> completer = new Completer<Null>(); _pendingRefreshFuture = completer.future; _mode = _RefreshLayoutMode.snap; _positionController .animateTo( 1.0 / _kDragSizeFactorLimit, duration: _kIndicatorSnapDuration) .then < void > ( ( Null value ) { if (mounted && _mode == _RefreshLayoutMode.snap) { assert(widget.onRefresh != null); setState(() { // Show the indeterminate progress indicator. _mode = _RefreshLayoutMode.refresh; }); final Future<Null> refreshResult = widget.onRefresh(_isIndicatorAtTop); assert(() { if (refreshResult == null) FlutterError.reportError(new FlutterErrorDetails( exception: new FlutterError( 'The onRefresh callback returned null.\n' 'The RefreshLayout onRefresh callback must return a Future.' ), context: 'when calling onRefresh', library: 'material library', )); return true; }()); if (refreshResult == null) return; refreshResult.whenComplete(() { if (mounted && _mode == _RefreshLayoutMode.refresh) { completer.complete(); _dismiss(_isIndicatorAtTop?_RefreshLayoutMode.done:_RefreshLayoutMode.canceled); } }); } } ); } /// Show the refresh indicator and run the refresh callback as if it had /// been started interactively. If this method is called while the refresh /// callback is running, it quietly does nothing. /// /// Creating the [RefreshLayout] with a [GlobalKey<RefreshLayoutState>] /// makes it possible to refer to the [RefreshLayoutState]. /// /// The future returned from this method completes when the /// [RefreshLayout.onRefresh] callback's future completes. /// /// If you await the future returned by this function from a [State], you /// should check that the state is still [mounted] before calling [setState]. /// /// When initiated in this manner, the refresh indicator is independent of any /// actual scroll view. It defaults to showing the indicator at the top. To /// show it at the bottom, set `atTop` to false. Future<Null> show({ bool atTop: true }) { if (_mode != _RefreshLayoutMode.refresh && _mode != _RefreshLayoutMode.snap) { if (_mode == null) _start(atTop ? AxisDirection.down : AxisDirection.up); _show(); } return _pendingRefreshFuture; } final GlobalKey _key = new GlobalKey(); @override Widget build(BuildContext context) { final Widget child = new NotificationListener<ScrollNotification>( key: _key, onNotification: _handleScrollNotification, child: new NotificationListener<OverscrollIndicatorNotification>( onNotification: _handleGlowNotification, child: widget.child, ), ); if (_mode == null) { assert(_dragOffset == null); assert(_isIndicatorAtTop == null); return child; } assert(_dragOffset != null); assert(_isIndicatorAtTop != null); final bool showIndeterminateIndicator = _mode == _RefreshLayoutMode.refresh || _mode == _RefreshLayoutMode.done; return new Stack( children: <Widget>[ child, new Positioned( top: _isIndicatorAtTop ? 0.0 : null, bottom: !_isIndicatorAtTop ? 0.0 : null, left: 0.0, right: 0.0, child: new SizeTransition( axisAlignment: _isIndicatorAtTop ? 1.0 : -1.0, sizeFactor: _positionFactor, // this is what brings it down child: new Container( padding: _isIndicatorAtTop ? new EdgeInsets.only(top: widget.displacement) : new EdgeInsets.only(bottom: 0.0), alignment: _isIndicatorAtTop ? Alignment.topCenter : Alignment.bottomCenter, child: _isIndicatorAtTop ? (widget.canrefresh ? new ScaleTransition( scale: _scaleFactor, child: new AnimatedBuilder( animation: _positionController, builder: (BuildContext context, Widget child) { return new RefreshProgressIndicator( value: showIndeterminateIndicator ? null : _value.value, valueColor: _valueColor, backgroundColor: widget.backgroundColor, ); }, ), ) : null) : new AnimatedBuilder( animation: _positionController, builder: widget.loadingBuilder==null?defaultLoadingBuilder:(context, widge){ return widget.loadingBuilder(context); } ), ), ), ), ], ); } TransitionBuilder defaultLoadingBuilder; void initBuilder() { defaultLoadingBuilder = (BuildContext context, Widget cc) { return new Container(decoration: new BoxDecoration( gradient: new LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: <Color>[ Color(0x40ffffff), Color(0x99ffffff), Color(0xBBffffff), Color(0xDDffffff), Colors.white ])), child: SizedBox(height: 60.0, child: Center(child: new Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ new SizedBox(width: 16.0, height: 16.0, child: CircularProgressIndicator(strokeWidth: 1.3, valueColor: _valueColor, backgroundColor: widget.backgroundColor,),), Padding(padding: EdgeInsets.all(3.0)), Text('正在加载中...') ],)),),); }; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/SelfWidge/Progress.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/src/scheduler/ticker.dart'; import 'package:flutter/widgets.dart'; class MyProgress extends StatefulWidget { final Size size; final Color color; final int count; final int milliseconds; const MyProgress({@required this.size, this.milliseconds: 300, this.color: Colors .green, this.count: 4}); @override State<StatefulWidget> createState() => _ProgressState(); } class _ProgressState extends State<MyProgress> implements TickerProvider { List<Animation<double>>animators = []; List<AnimationController>_animationControllers = []; @override void initState() { super.initState(); for (int i = 0; i < widget.count; i++) { var animationController = new AnimationController(vsync: this, duration: Duration(milliseconds: widget.milliseconds * widget.count)); animationController.value=0.8*i/widget.count; _animationControllers.add(animationController); Animation<double> animation = new Tween(begin: 0.1, end: 1.9).animate( animationController); animators.add(animation); } animators[0].addListener(_change); try { var mi = (widget.milliseconds~/(2*animators.length-2)); for (int i = 0; i < animators.length; i++) { print(( mi*i).toString()); dodelay(_animationControllers[i], mi*i); } } on Exception { } } void dodelay(AnimationController _animationControllers, int delay) async{ Future.delayed(Duration(milliseconds: delay),(){ _animationControllers..repeat().orCancel; }); } void _change() { setState(() {}); } @override Widget build(BuildContext context) { return new CustomPaint(painter: _Progress( animators: animators, color: widget.color, count: widget.count), size: widget.size,); } @override void dispose() { super.dispose(); animators[0].removeListener(_change); _animationControllers[0].dispose(); } @override Ticker createTicker(TickerCallback onTick) { return Ticker(onTick); } } class _Progress extends CustomPainter { final Color color; final int count; final List<Animation<double>>animators; const _Progress({this.animators, this.color, this.count}); @override void paint(Canvas canvas, Size size) { var radius = size.width / (3 * count + 1); var paint = new Paint() ..color = color ..style = PaintingStyle.fill; for (int i = 1; i < count + 1; i++) { double value = animators[i - 1].value; canvas.drawCircle( new Offset(radius * i * 3 - radius, size.height / 2), radius * (value > 1 ? (2 - value) : value), paint); } } @override bool shouldRepaint(CustomPainter oldDelegate) { return oldDelegate != this; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Utils/CookieUtil.dart
import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; class CookieUtil{ static Future<Map<String,String>> getCookie()async{ Map<String,String> headers={}; SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); String cookie=sharedPreferences.getString("cookie"); if(cookie!=null&&cookie.isNotEmpty){ headers["Cookie"]=cookie; } return headers; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/MinePage.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flyandroid/Api/Api.dart'; import 'package:flyandroid/Api/Constant.dart'; import 'package:flyandroid/Model/Artical.dart'; import 'package:flyandroid/Model/HomeModel.dart'; import 'package:flyandroid/Model/UserModel.dart'; import 'package:flyandroid/Pages/Item/ArticalItem.dart'; import 'package:flyandroid/Pages/LoginAndRegisterPage.dart'; import 'package:flyandroid/SelfWidge/Refresh.dart'; import 'package:flyandroid/Utils/CookieUtil.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; class MinePage extends StatefulWidget { @override State<StatefulWidget> createState() => _MinePageState(); } class _MinePageState extends State<MinePage> { List<Artical> _articals = []; UserModel model; ShowState showState; int _page = 0; bool _isnomore = false; @override void initState() { // TODO: implement initState super.initState(); showState = ShowState.LOGIN; } @override void didUpdateWidget(MinePage oldWidget) { // TODO: implement didUpdateWidget super.didUpdateWidget(oldWidget); if (Constanct.SELECT_PAGER == Page.MINE_PAGE.index && model == null) { asyncInit(); } } @override Widget build(BuildContext context) { switch (showState) { case ShowState.LOGIN: return Center( child: new InkWell( child: Padding(padding: EdgeInsets.all(50.0), child: Text("点击登录!")), onTap: () async { var result = await Navigator .of(context) .push(MaterialPageRoute(builder: (c) { return LoginAndRegisterPage(LoginAndRegister.LOGIN); })); if (result) { asyncInit(); } }, ), ); default: return RefreshLayout( canrefresh: false, canloading: !_isnomore, child: ListView.builder( itemBuilder: listBuilder, itemCount: _articals.length + 1, ), onRefresh: (onrefresh) { if (!onrefresh) { _page++; return doLoading(); } }, ); } } Widget listBuilder(BuildContext b, int position) { if (position == 0) { return headerBuilder(b); } return ArticalItem(_articals[position - 1]); } Widget headerBuilder(BuildContext b) { return Card( margin: EdgeInsets.all(12.0), child: Row(children: <Widget>[ Image.network(model.data.icon), Padding( padding: EdgeInsets.all(12.0), child: Text( "ID:" + model.data.id.toString() + "\n用户名:" + model.data.username + "\nEmail:" + model.data.email, style: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold), ), ) ])); } void asyncInit() async { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); var user = sharedPreferences.getString("user"); if (user != null) { model = UserModel.fromJson(json.decode(user)); doLoading(); } } Future<Null> doLoading() async { if (_page == 0) { _articals.clear(); } http.Response response = await http.get(Api.getCollectList(_page), headers: await CookieUtil.getCookie()); print(response.body); var homeData = HomeData.fromJson(json.decode(response.body)); if (homeData.errorCode == 0) { _articals += homeData.data.datas; if (homeData.data.datas.length < homeData.data.size) { _isnomore = true; } setState(() { showState = ShowState.CONTENT; }); } else { print(homeData.errorMsg); } return new Future<Null>.value(null); } } enum ShowState { LOGIN, CONTENT }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/GuidePage.dart
import 'dart:async'; import 'package:flyandroid/Model/Artical.dart'; import 'package:flyandroid/Model/GuideModel.dart'; import 'package:flyandroid/Pages/WebPage.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:flyandroid/Api/Api.dart'; import 'package:flyandroid/Api/Constant.dart'; import 'package:flutter/material.dart'; class GuidePage extends StatefulWidget { @override State<StatefulWidget> createState() => _GuidePageState(); } class _GuidePageState extends State<GuidePage> { bool _showloading = true; GuideData guideData; int _selectIndex = 0; @override Widget build(BuildContext context) { if (_showloading) return Center( child: SizedBox(height: 8.0,child:Theme(data: ThemeData(accentColor: Colors.amber), child: CircularProgressIndicator()),), ); return Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ LimitedBox( maxWidth: 100.0, child: Card(child: ListView.builder( itemCount: guideData.data.length, itemBuilder: _buildFirst))), Expanded( child:Wrap(children: _buildSecond()), ) ], ); } Widget _buildFirst(BuildContext context, int index) { Guide tree = guideData.data[index]; return InkResponse( onTap: () { setState(() { _selectIndex = index; }); }, child: Container( color: _selectIndex == index ? Colors.grey[300] : Colors.transparent, child: Padding(padding: EdgeInsets.all(8.0),child:Text(tree.name, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 18.0, color: Colors.grey[700]))), ), ); } List<Widget> _buildSecond() { List<Widget> widgets = []; Guide tree = guideData.data[_selectIndex]; tree.articles.map((childtree) { widgets.add(Card( child: InkWell( onTap: () { _click(childtree); // Navigator.push(context, new MaterialPageRoute(builder: (context) => // GuideChildPage(artical.name, artical))); }, child: Padding( padding: EdgeInsets.all(8.0), child: Text( childtree.title, style: TextStyle(fontSize: 16.0), ), ), ))); }).toList(); return widgets; } @override void didUpdateWidget(GuidePage oldWidget) { if(guideData==null&&Constanct.SELECT_PAGER==Page.GUIDE_PAGE.index){ _request(); } } void _click(Artical artical) { Navigator.push(context, new MaterialPageRoute(builder: (context) => MyWebPage(artical.link, artical.title))); } Future<Null> _request() async { http.Response response = await http.get(Api.NAVIGATION); print(response); guideData = GuideData.fromJson(json.decode(response.body)); setState(() { _showloading = false; }); return null; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/CategoryPage.dart
import 'dart:async'; import 'dart:convert'; import 'package:flyandroid/Model/Artical.dart'; import 'package:flyandroid/Model/HomeModel.dart'; import 'package:flyandroid/Pages/Item/ArticalItem.dart'; import 'package:flyandroid/Utils/CookieUtil.dart'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; import 'package:flyandroid/Api/Api.dart'; import 'package:flyandroid/Api/Constant.dart'; import 'package:flyandroid/Model/TreeModel.dart'; import 'package:flyandroid/SelfWidge/Refresh.dart'; class CategoryPage extends StatefulWidget { @override State<StatefulWidget> createState() => _CategoryPageState(); } class _CategoryPageState extends State<CategoryPage> { bool _showloading = true; TreeBean treeBean; //分类数据 int _selectIndex = 0; ChildTree _child; //选中的child int page = 0; HomeData homeData; //文章数据 bool _isnomore = false; List<Artical> _articals = []; @override Widget build(BuildContext context) { if (_showloading) return Center( child: SizedBox( height: 8.0, child: Theme( data: ThemeData(accentColor: Colors.amber), child: CircularProgressIndicator()), ), ); return Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ LimitedBox( maxWidth: 100.0, child: Card( child: ListView.builder( itemCount: treeBean.data.length, itemBuilder: _buildFirst))), Expanded( child: RefreshLayout( child: ListView.builder( itemBuilder: _buildThird, itemCount: (_isnomore ? 1 : 0) + _articals.length + 1, ), onRefresh: (isrefresh) { return _requestArtical(isrefresh); }, canloading: !_isnomore, ), ) ], ); } @override void didUpdateWidget(CategoryPage oldWidget) { if (treeBean == null && Constanct.SELECT_PAGER == Page.CATEGORY_PAGE.index) { _request(); } } /** * 构建分类 */ Widget _buildFirst(BuildContext context, int index) { Tree tree = treeBean.data[index]; return InkResponse( onTap: () { if (_selectIndex != index) { _selectIndex = index; _child = tree.children[0]; _requestArtical(true); } }, child: Container( color: _selectIndex == index ? Colors.grey[300] : Colors.transparent, child: Padding( padding: EdgeInsets.all(8.0), child: Text(tree.name, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 18.0, color: Colors.grey[700]))), ), ); } /** * 构建子分类 */ List<Widget> _buildSecond() { List<Widget> widgets = []; Tree tree = treeBean.data[_selectIndex]; tree.children.map((childtree) { widgets.add(Card( child: InkWell( onTap: () { if (_child != childtree) { _child = childtree; _requestArtical(true); } // Navigator.push(context, new MaterialPageRoute(builder: (context) => // GuideChildPage(artical.name, artical))); }, child: Container( color: _child == childtree ? Colors.grey[300] : Colors.transparent, child: Padding( padding: EdgeInsets.all(4.0), child: Text( childtree.name, ), ), )))); }).toList(); return widgets; } /** * 构建文章列表 */ Widget _buildThird(BuildContext context, int index) { if (index == 0) return Wrap(children: _buildSecond()); int acturalindex = index - 1; if (acturalindex <= _articals.length - 1) { return ArticalItem(_articals[acturalindex]); } return Center( child: Padding( padding: EdgeInsets.all(4.0), child: Text("没有更多了"), ), ); } /** * 请求分类数据 */ Future<Null> _request() async { try { http.Response response = await http.get(Api.TREE); treeBean = TreeBean.fromJson(json.decode(response.body)); _child = treeBean.data[0].children[0]; _showloading = false; _requestArtical(true); } catch (e) { print(e); } return null; } /** * 请求文章 */ Future<Null> _requestArtical(bool isrefresh) async { if (isrefresh) { _articals.clear(); _isnomore = false; page = 0; } else { page += 1; } http.Response response = await http.get(Api.getTreeArtical(page, _child.id),headers: await CookieUtil.getCookie()); var homeData = HomeData.fromJson(json.decode(response.body)); if (homeData.errorCode < 0) { //TODO } else { var articals = homeData.data.datas; if (articals.length < homeData.data.size) { _isnomore = true; } _articals += articals; if (articals.length != 0) { setState(() { }); } } return null; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/SearchPage.dart
import 'package:flutter/material.dart'; class SearchPage extends StatefulWidget { @override State<StatefulWidget> createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { @override Widget build(BuildContext context) { return new Scaffold( appBar: AppBar(title: Text("搜索"),), body: Center(child: Text("SearchPage")), ); } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/HomePage.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flyandroid/Api/Api.dart'; import 'package:flyandroid/Model/Artical.dart'; import 'package:flyandroid/Model/HomeModel.dart'; import 'package:flyandroid/SelfWidge/Refresh.dart'; import 'package:flyandroid/Pages/Item/ArticalItem.dart'; import 'package:flyandroid/Pages/WebPage.dart'; import 'package:flyandroid/SelfWidge/carousel_slider.dart'; import 'package:flyandroid/Utils/CookieUtil.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; class HomePage extends StatefulWidget { @override State<StatefulWidget> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { List<Artical> _articals = []; BannerData _banner; int _page = 0; bool _isnomore = false; ShowState _state = ShowState.LOADING; String _error; @override void initState() { super.initState(); _request(_page); } @override Widget build(BuildContext context) { switch (_state) { case ShowState.LOADING: return Center( child: SizedBox( height: 8.0, child: Theme( data: ThemeData(accentColor: Colors.amber), child: CircularProgressIndicator()), ), ); case ShowState.EMPTY: return new Center( child: Text('没有相关信息'), ); case ShowState.ERROR: return new Center( child: Text(_error), ); case ShowState.CONTENT: return RefreshLayout( onRefresh: (isrefresh) { if (isrefresh) { _page = 0; } else { _page++; } return _request(_page); }, canloading: !_isnomore, child: ListView.builder( itemCount: _banner == null ? _articals.length : _articals.length + 1, itemBuilder: _itemBuild, ), ); } return null; } Future<Null> _request(int page) async { http.Response response = await http.get(Api.getHomePageUrl(_page),headers:await CookieUtil.getCookie()); http.Response bannerResponse = await http.get(Api.BANNER); _banner = BannerData.fromJson(json.decode(bannerResponse.body)); var homeData = HomeData.fromJson(json.decode(response.body)); if (homeData.errorCode < 0) { _state = ShowState.ERROR; _error = homeData.errorMsg; } else { if (page == 0) { _articals.clear(); } _articals += homeData.data.datas; if (page == 0 && _articals.isEmpty) { _state = ShowState.EMPTY; } else { _state = ShowState.CONTENT; if (homeData.data.datas.length < homeData.data.size) { _isnomore = true; } } } setState(() {}); return null; } Widget _itemBuild(BuildContext context, int index) { if (index == 0 && _banner != null) { return new CarouselSlider( items: _banner.data.map((banner) { return new Builder( builder: (BuildContext context) { return new Container( width: MediaQuery.of(context).size.width, margin: new EdgeInsets.symmetric( vertical: 2.0, horizontal: 5.0), child: GestureDetector( onTap: () { _bannerClick(banner.url, banner.title); }, child: Stack( children: <Widget>[ new Container( margin: new EdgeInsets.symmetric(horizontal: 5.0), decoration: new BoxDecoration( borderRadius: new BorderRadius.all( new Radius.circular(15.0)), image: new DecorationImage( image: new NetworkImage(banner.imagePath), fit: BoxFit.cover)), ), Align( child: DecoratedBox( decoration: BoxDecoration(color: Color(0xAAffffff)), child: Text(banner.title), ), alignment: Alignment.bottomCenter, ) ], ), )); }, ); }).toList(), viewportFraction: 0.9, aspectRatio: 2.0, autoPlay: true); } return ArticalItem(_articals[_banner == null ? index : index - 1]); } void _bannerClick(String link, String title) { Navigator .of(context) .push(MaterialPageRoute(builder: (context) => MyWebPage(link, title))); } } enum ShowState { ERROR, LOADING, EMPTY, CONTENT }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/LoginAndRegisterPage.dart
import 'dart:async'; import 'dart:convert'; import 'package:flyandroid/Api/Api.dart'; import 'package:http/http.dart' as http; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:flyandroid/Model/UserModel.dart'; class LoginAndRegisterPage extends StatefulWidget { final LoginAndRegister type; LoginAndRegisterPage(this.type); @override State<StatefulWidget> createState()=>_state(); } class _state extends State<LoginAndRegisterPage>{ TextEditingController _account; TextEditingController _pass; TextEditingController _confirmPass; @override void initState() { super.initState(); _account=new TextEditingController(); _pass=new TextEditingController(); _confirmPass=new TextEditingController(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.type == LoginAndRegister.LOGIN ? "登录" : "注册"), ), body: SingleChildScrollView( reverse: true, padding: EdgeInsets.only(left: 32.0, right: 32.0), child: widget.type == LoginAndRegister.LOGIN ? buildLogin() : buildRegister())); } Widget buildLogin() { return Column(children: <Widget>[ Padding( padding: EdgeInsets.only(top: 10.0), child: Image.asset("assets/pic/logo.png")), TextField( controller: _account, decoration: InputDecoration( hintText: "请输入账号", labelText: "账号:", icon: Icon(Icons.account_box)), keyboardType: TextInputType.emailAddress, ), TextField( controller: _pass, decoration: InputDecoration( hintText: "请输入密码", labelText: "密码:", icon: Icon(Icons.enhanced_encryption)), keyboardType: TextInputType.emailAddress), Padding( padding: EdgeInsets.only(top: 16.0, bottom: 16.0), child: MaterialButton( onPressed: _login, child: Text("登录", style: TextStyle(color: Colors.white)), color: Colors.blue, padding: EdgeInsets.all(8.0), ), ), Container( alignment: AlignmentDirectional.bottomEnd, child: InkWell( onTap: () async { bool isok = await Navigator.push(context, MaterialPageRoute(builder: (c) { return LoginAndRegisterPage(LoginAndRegister.REGISTER); })); if (isok) { Navigator.pop(context,true); } }, child: Padding( padding: EdgeInsets.all(8.0), child: Text("没有账号?点击注册"), ), ), ) ]); } Widget buildRegister() { return Column(children: <Widget>[ Padding( padding: EdgeInsets.only(top: 10.0), child: Image.asset("assets/pic/logo.png")), TextField( controller: _account, decoration: InputDecoration( hintText: "请输入账号", labelText: "账号:", icon: Icon(Icons.account_box)), keyboardType: TextInputType.emailAddress, ), TextField( decoration: InputDecoration( hintText: "请输入密码", labelText: "密码:", icon: Icon(Icons.enhanced_encryption)), controller: _pass, keyboardType: TextInputType.emailAddress, ), TextField( decoration: InputDecoration( hintText: "请再次输入密码", labelText: "确认密码:", icon: Icon(Icons.enhanced_encryption)), controller: _confirmPass, keyboardType: TextInputType.emailAddress), Padding( padding: EdgeInsets.only(top: 16.0, bottom: 16.0), child: MaterialButton( onPressed:_register, child: Text( "注册", style: TextStyle(color: Colors.white), ), color: Colors.blue, padding: EdgeInsets.all(8.0))), ]); } Future<Null> _showMessage(String name) async { return showDialog<Null>( context: context, builder: (c) { return new AlertDialog(content: new Text(name), actions: <Widget>[ new FlatButton( onPressed: () { Navigator.pop(c); }, child: new Text('确定')) ]); }); } void _login() async { if (_account.text.isNotEmpty && _pass.text.isNotEmpty) { http.Response response = await http .post(Api.LOGIN, body: {"username": _account.text, "password": _pass.text}); UserModel model = UserModel.fromJson(json.decode(response.body)); if (model.errorCode < 0) { await _showMessage(model.errorMsg); } else { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); sharedPreferences.setString("cookie", response.headers['set-cookie']); sharedPreferences.setString("user", response.body); await _showMessage("登录成功"); Navigator.pop(context,true); } } else { await _showMessage("账号或密码不能为空"); } } void _register() async { if (_account.text.isNotEmpty && _pass.text.isNotEmpty && _confirmPass.text.isNotEmpty) { if (_pass.text != _confirmPass.text) { _showMessage("两次密码不一致"); } else { http.Response response = await http.post(Api.REGIDTER, body: { "username": _account.text, "password": _pass.text, "repassword": _confirmPass.text }); UserModel model = UserModel.fromJson(json.decode(response.body)); if (model.errorCode < 0) { await _showMessage(model.errorMsg); } else { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); sharedPreferences.setString("user", response.body); sharedPreferences.setString("cookie", response.headers['set-cookie']); await _showMessage("注册成功"); Navigator.pop(context, true); } } } else { await _showMessage("账号或密码不能为空"); } } } enum LoginAndRegister { LOGIN, REGISTER }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Pages/WebPage.dart
import 'dart:async'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; import 'package:flutter/material.dart'; class MyWebPage extends StatefulWidget { final String url; final String title; MyWebPage(this.url, this.title); @override State<StatefulWidget> createState() => _WebState(); } class _WebState extends State<MyWebPage> { final flutterWebViewPlugin = new FlutterWebviewPlugin(); bool isloading = true; @override void initState() { // TODO: implement initState super.initState(); flutterWebViewPlugin.onDestroy.listen((onDestroy){ Navigator.pop(context); }); flutterWebViewPlugin.onStateChanged.listen((state) { if (state.type == WebViewState.finishLoad&&isloading) { setState(() { isloading = false; }); } }); } @override Widget build(BuildContext context) { var _toppadding = MediaQuery.of(context).padding.top; return Stack( alignment: AlignmentDirectional.topCenter, children: <Widget>[ WebviewScaffold( url: widget.url, appBar: AppBar( title: Text( widget.title, style: TextStyle(fontSize: 15.0), ), ), withJavascript: true, withLocalStorage: true, withZoom: true, ), Offstage( offstage: !isloading, child: Padding( padding: EdgeInsets.only(top: (kToolbarHeight + _toppadding - 2)), child: new LinearProgressIndicator( backgroundColor: Colors.amber, ), ), ) ], ); } }
0
mirrored_repositories/wanandroid/lib/Pages
mirrored_repositories/wanandroid/lib/Pages/Item/ArticalItem.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flyandroid/Api/Api.dart'; import 'package:flyandroid/Model/Artical.dart'; import 'package:flyandroid/Pages/LoginAndRegisterPage.dart'; import 'package:flyandroid/Pages/WebPage.dart'; import 'package:flyandroid/Utils/CookieUtil.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:http/http.dart' as http; class ArticalItem extends StatefulWidget { final Artical artical; ArticalItem(this.artical); @override State<StatefulWidget> createState() => ArticalState(); } class ArticalState extends State<ArticalItem> { String escapeFromHtml(String html) { String temp = html.replaceAll("&mdash;", "-").replaceAll("&ndash;", "-"); String temp2 = temp.replaceAll("&ldquo;", "“"); String temp3 = temp2.replaceAll("&rdquo;", "”"); return temp3; } @override Widget build(BuildContext context) { return Card( child: InkWell( onTap: _onTap, child: Stack( children: <Widget>[ Padding( padding: EdgeInsets.all(16.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(right: 32.0), child: Hero( tag: widget.artical.title, child: Text(escapeFromHtml(widget.artical.title), softWrap: true, maxLines: 2, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 20.0, color: Colors.grey[700])), )), widget.artical.envelopePic == "" ? Padding( padding: EdgeInsets.all(1.0), ) : Image.network( widget.artical.envelopePic, height: 200.0, ), Padding( padding: EdgeInsets.only(top: 12.0), child: Wrap( spacing: 8.0, crossAxisAlignment: WrapCrossAlignment.center, children: _buildWidge(), ), ) ], )), Align( alignment: Alignment.topRight, child: IconButton( onPressed: _collect, icon: Icon( widget.artical.collect ? Icons.favorite : Icons.favorite_border, color: widget.artical.collect ? Colors.redAccent : Colors.grey, ), ), ) ], ), )); } List<Widget> _buildWidge() { var widges = <Widget>[]; if (widget.artical.fresh) { widges.add(DecoratedBox( child: Padding( padding: EdgeInsets.all(1.0), child: Text( "新", style: TextStyle(fontSize: 12.0), ), ), decoration: new ShapeDecoration( shape: RoundedRectangleBorder( side: BorderSide(color: Colors.red))))); } widget.artical.tags.map((tag) { widges.add(GestureDetector( child: DecoratedBox( child: Padding( padding: EdgeInsets.all(1.0), child: Text(tag.name), ), decoration: new ShapeDecoration( shape: RoundedRectangleBorder( side: BorderSide(color: Colors.green)))), onTap: () { _onClickTag(tag); }, )); }); widges.add(Text("作者:" + widget.artical.author, style: TextStyle(fontSize: 13.0, color: Colors.grey))); widges.add(GestureDetector( child: Text( widget.artical.superChapterName??"", style: TextStyle( color: Colors.blueGrey, fontStyle: FontStyle.italic, fontSize: 12.0), ), onTap: _onCategoryClick, )); widges.add(GestureDetector( child: Text(widget.artical.chapterName??"", style: TextStyle( color: Colors.blueGrey, fontStyle: FontStyle.italic, fontSize: 12.0)), onTap: _onCategoryClick2, )); widges.add(Text(widget.artical.niceDate, style: TextStyle(fontSize: 13.0, color: Colors.grey))); return widges; } void _onTap() { Navigator.of(context).push(MaterialPageRoute( builder: (context) => MyWebPage(widget.artical.link, widget.artical.title))); } void _onCategoryClick() { Scaffold.of(context).showSnackBar(SnackBar( content: Text("还未实现该功能"), )); } void _onCategoryClick2() { Scaffold.of(context).showSnackBar(SnackBar( content: Text("还未实现该功能"), )); } void _onClickTag(Tag tag) {} void _collect() async { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); String cookie=sharedPreferences.getString("cookie"); if(cookie==null){ Navigator.of(context).push(MaterialPageRoute(builder: (c) { return LoginAndRegisterPage(LoginAndRegister.LOGIN); })); }else { if(widget.artical.collect){ http.Response response = await http.post(Api.getUncollectUrl(widget.artical.id),headers:await CookieUtil.getCookie()); handleCollectResult(response); }else{ http.Response response = await http.post(Api.getCollectUrl(widget.artical.id),headers:await CookieUtil.getCookie()); handleCollectResult(response); } } } void handleCollectResult(http.Response response) { Map<String,dynamic> result=json.decode(response.body); if(result['errorCode']>=0){ setState(() { widget.artical.collect=!widget.artical.collect; }); }else{ Scaffold.of(context).showSnackBar(SnackBar( content: Text(result['errorMsg']), )); } } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Api/Api.dart
class Api{ static String getHomePageUrl(int page){ return "http://www.wanandroid.com/article/list/$page/json"; } static const String BANNER="http://www.wanandroid.com/banner/json"; static const String NAVIGATION="http://www.wanandroid.com/navi/json"; static const String TREE="http://www.wanandroid.com/tree/json"; static String getTreeArtical(int page,int cid){ return "http://www.wanandroid.com/article/list/$page/json?cid=$cid"; } static const String LOGIN="http://www.wanandroid.com/user/login"; static const String REGIDTER="http://www.wanandroid.com/user/register"; static String getUncollectUrl(int id){ return "http://www.wanandroid.com/lg/uncollect_originId/$id/json"; } /** * 我的收藏页 */ static String getCollectList(int page){ return "http://www.wanandroid.com/lg/collect/list/$page/json"; } static String getCollectUrl(int id){ return "http://www.wanandroid.com/lg/collect/$id/json"; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Api/Constant.dart
class Constanct{ static int SELECT_PAGER=0; } enum Page{ HOME_PAGE,CATEGORY_PAGE,GUIDE_PAGE,MINE_PAGE }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/generated/i18n.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; // ignore_for_file: non_constant_identifier_names // ignore_for_file: camel_case_types // ignore_for_file: prefer_single_quotes //This file is automatically generated. DO NOT EDIT, all your changes would be lost. class S implements WidgetsLocalizations { const S(); static const GeneratedLocalizationsDelegate delegate = const GeneratedLocalizationsDelegate(); static S of(BuildContext context) => Localizations.of<S>(context, WidgetsLocalizations); @override TextDirection get textDirection => TextDirection.ltr; } class en extends S { const en(); } class GeneratedLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> { const GeneratedLocalizationsDelegate(); List<Locale> get supportedLocales { return const <Locale>[ const Locale("en", ""), ]; } LocaleResolutionCallback resolution({Locale fallback}) { return (Locale locale, Iterable<Locale> supported) { final Locale languageLocale = new Locale(locale.languageCode, ""); if (supported.contains(locale)) return locale; else if (supported.contains(languageLocale)) return languageLocale; else { final Locale fallbackLocale = fallback ?? supported.first; return fallbackLocale; } }; } @override Future<WidgetsLocalizations> load(Locale locale) { final String lang = getLang(locale); switch (lang) { case "en": return new SynchronousFuture<WidgetsLocalizations>(const en()); default: return new SynchronousFuture<WidgetsLocalizations>(const S()); } } @override bool isSupported(Locale locale) => supportedLocales.contains(locale); @override bool shouldReload(GeneratedLocalizationsDelegate old) => false; } String getLang(Locale l) => l.countryCode != null && l.countryCode.isEmpty ? l.languageCode : l.toString();
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Model/Artical.dart
class Artical { final String apkLink; final String author; final int chapterId; final String chapterName; bool collect; final int courseId; final String desc; final bool fresh; final int id; final int type; final int userId; final int visible; final int zan; final String link; final String niceDate; final String origin; final String projectLink; final int publishTime; final int superChapterId; final String superChapterName; final String title; final String envelopePic; final List<Tag> tags; Artical({this.apkLink, this.author, this.chapterId, this.chapterName, this.collect, this.courseId, this.desc, this.fresh, this.id, this.type, this.userId, this.visible, this.zan, this.link, this.niceDate, this.origin, this.projectLink, this.publishTime, this.superChapterId , this.superChapterName, this.title,this.envelopePic, this.tags}); Artical.fromJson(Map<String, dynamic> json) : apkLink=json['apkLink'], author=json['author'], chapterId=json['chapterId'], chapterName=json['chapterName'], collect=json['collect']==null?true:json['collect'], courseId=json['courseId'], desc=json['desc'], fresh=json['fresh']==null?false:json['fresh'], envelopePic=json['envelopePic'], id=json['id'], type=json['type'], userId=json['userId'], visible=json['visible'], zan=json['zan'], link=json['link'], niceDate=json['niceDate'], origin=json['origin'], projectLink=json['projectLink'], publishTime=json['publishTime'], superChapterId=json['superChapterId'], superChapterName=json['superChapterName'], title=json['title'], tags=getTag(json['tags']); static List<Tag> getTag(List<dynamic> tags) { if(tags==null) return []; return tags.map((tag) => Tag((tag as Map<String, dynamic>)['name'], (tag as Map<String, dynamic>)['url'])).toList(); } } class Tag { final String name; final String url; Tag(this.name, this.url); Tag.fromJson(Map<String, dynamic> json) : name = json['name'], url = json['url']; }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Model/TreeModel.dart
import 'dart:convert' show json; class TreeBean { int errorCode; String errorMsg; List<Tree> data; TreeBean.fromParams({this.errorCode, this.errorMsg, this.data}); factory TreeBean(jsonStr) => jsonStr is String ? TreeBean.fromJson(json.decode(jsonStr)) : TreeBean.fromJson(jsonStr); TreeBean.fromJson(jsonRes) { errorCode = jsonRes['errorCode']; errorMsg = jsonRes['errorMsg']; data = []; for (var dataItem in jsonRes['data']){ data.add(new Tree.fromJson(dataItem)); } } @override String toString() { return '{"errorCode": $errorCode,"errorMsg": ${errorMsg != null?'${json.encode(errorMsg)}':'null'},"data": $data}'; } } class Tree { int courseId; int id; int order; int parentChapterId; int visible; String name; List<ChildTree> children; Tree.fromParams({this.courseId, this.id, this.order, this.parentChapterId, this.visible, this.name, this.children}); Tree.fromJson(jsonRes) { courseId = jsonRes['courseId']; id = jsonRes['id']; order = jsonRes['order']; parentChapterId = jsonRes['parentChapterId']; visible = jsonRes['visible']; name = jsonRes['name']; children = []; for (var childrenItem in jsonRes['children']){ children.add(new ChildTree.fromJson(childrenItem)); } } @override String toString() { return '{"courseId": $courseId,"id": $id,"order": $order,"parentChapterId": $parentChapterId,"visible": $visible,"name": ${name != null?'${json.encode(name)}':'null'},"children": $children}'; } } class ChildTree { int courseId; int id; int order; int parentChapterId; int visible; String name; List<dynamic> children; ChildTree.fromParams({this.courseId, this.id, this.order, this.parentChapterId, this.visible, this.name, this.children}); ChildTree.fromJson(jsonRes) { courseId = jsonRes['courseId']; id = jsonRes['id']; order = jsonRes['order']; parentChapterId = jsonRes['parentChapterId']; visible = jsonRes['visible']; name = jsonRes['name']; children = jsonRes['children']; } @override String toString() { return '{"courseId": $courseId,"id": $id,"order": $order,"parentChapterId": $parentChapterId,"visible": $visible,"name": ${name != null?'${json.encode(name)}':'null'},"children": $children}'; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Model/GuideModel.dart
import 'package:flyandroid/Model/Artical.dart'; class GuideData { final int errorCode; final String errorMsg; final List<Guide> data; GuideData(this.errorMsg, this.errorCode, this.data); GuideData.fromJson(Map<String, dynamic> json) : errorCode = json['errorCode'], errorMsg = json['errorMsg'], data = getGuides(json['data'] as List<dynamic>); static List<Guide> getGuides(List<dynamic> guides) { return guides .map((guide) => Guide.fromJson(guide as Map<String, dynamic>)) .toList(); } } class Guide { final List<Artical> articles; final String name; final int cid; Guide(this.name, this.cid, this.articles); Guide.fromJson(Map<String, dynamic> json) : articles = getArticals(json['articles'] as List<dynamic>), name = json['name'], cid = json['cid']; static List<Artical> getArticals(List<dynamic> articals) { return articals .map((artical) => Artical.fromJson(artical as Map<String, dynamic>)) .toList(); } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Model/UserModel.dart
import 'dart:convert' show json; class UserModel { int errorCode; String errorMsg; User data; UserModel.fromParams({this.errorCode, this.errorMsg, this.data}); factory UserModel(jsonStr) => jsonStr is String ? UserModel.fromJson(json.decode(jsonStr)) : UserModel.fromJson(jsonStr); UserModel.fromJson(jsonRes) { errorCode = jsonRes['errorCode']; errorMsg = jsonRes['errorMsg']; if (errorCode >= 0) data = new User.fromJson(jsonRes['data']); } @override String toString() { return '{"errorCode": $errorCode,"errorMsg": ${errorMsg != null ? '${json .encode(errorMsg)}' : 'null'},"data": $data}'; } } class User { int id; int type; String email; String icon; String password; String username; List<int> collectIds; User.fromParams( {this.id, this.type, this.email, this.icon, this.password, this.username, this.collectIds}); User.fromJson(jsonRes) { id = jsonRes['id']; type = jsonRes['type']; email = jsonRes['email']; icon = jsonRes['icon']; password = jsonRes['password']; username = jsonRes['username']; collectIds = (jsonRes['collectIds'] as List<dynamic>).map((d) => d as int).toList(); } @override String toString() { return '{"id": $id,"type": $type,"email": ${email != null ? '${json.encode( email)}' : 'null'},"icon": ${icon != null ? '${json.encode(icon)}' : 'null'},"password": ${password != null ? '${json.encode(password)}' : 'null'},"username": ${username != null ? '${json.encode(username)}' : 'null'},"collectIds": $collectIds}'; } }
0
mirrored_repositories/wanandroid/lib
mirrored_repositories/wanandroid/lib/Model/HomeModel.dart
import 'package:flyandroid/Model/Artical.dart'; class HomeData { final int errorCode; final String errorMsg; final _HomeData data; HomeData(this.errorMsg, this.errorCode, this.data); HomeData.fromJson(Map<String, dynamic>json) : errorCode=json['errorCode'], errorMsg=json['errorMsg'], data=_HomeData.fromJson(json['data'] as Map<String, dynamic>); } class _HomeData { final int curPage; final int size; final int total; final int pageCount; final List<Artical>datas; _HomeData(this.curPage, this.size, this.total, this.pageCount, this.datas); _HomeData.fromJson(Map<String, dynamic> json) : curPage=json['curpage'], size=json['size'], total=json['total'], pageCount=json['pageCount'], datas=getArticals(json['datas']); static List<Artical> getArticals(List<dynamic> articals) { return articals.map((artical) => Artical.fromJson(artical as Map<String, dynamic>)).toList(); } } class BannerData { final int errorCode; final String errorMsg; final List<_BannerData> data; BannerData(this.errorMsg, this.errorCode, this.data); BannerData.fromJson(Map<String, dynamic>json) : errorCode=json['errorCode'], errorMsg=json['errorMsg'], data=_getBannerDatas(json['data']); static List<_BannerData> _getBannerDatas(List<dynamic> jsons) { return jsons.map((banner) => _BannerData.fromJson(banner as Map<String, dynamic>)).toList(); } } class _BannerData { final String desc; final String imagePath; final String title; final String url; final int isVisible; final int order; final int type; final int id; _BannerData.fromJson(Map<String, dynamic> json) : desc=json['desc'], imagePath=json['imagePath'], title=json['title'], url=json['url'], isVisible=json['isVisible'], order=json['order'], id=json['id'], type=json['type']; }
0
mirrored_repositories/wanandroid
mirrored_repositories/wanandroid/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:flyandroid/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/particle_clock_fx.dart
import 'dart:math'; import 'dart:ui'; import 'package:flutter/widgets.dart'; import 'clock_fx.dart'; import 'particle.dart'; import 'utils/rnd.dart'; final easingDelayDuration = Duration(seconds: 10); /// Probabilities of Hour, Minute, Noise. final particleDistributions = [2, 4, 100]; /// Number of "arms" to emit noise particles from center. final int noiseAngles = 2000; /// Threshold for particles to go rouge. Lower = more particles. final rougeDistributionLmt = 85; /// Threshold for particles to go jelly. Lower = more particles. final jellyDistributionLmt = 97; class ParticleClockFx extends ClockFx { ParticleClockFx({required Size size, required DateTime? time}) : super( size: size, time: time, ); @override void tick(Duration duration) { var secFrac = DateTime.now().millisecond / 1000; var vecSpeed = duration.compareTo(easingDelayDuration) > 0 ? max(.2, Curves.easeInOutSine.transform(1 - secFrac)) : 1; var vecSpeedInv = Curves.easeInSine.transform(secFrac); // Used to avoid emitting all particles at once. var maxSpawnPerTick = 10; particles.asMap().forEach((i, p) { // Movement p!.x -= p.vx * vecSpeed; p.y -= p.vy * vecSpeed; p.dist = _getDistanceFromCenter(p); p.distFrac = p.dist / (sizeMin / 2); p.lifeLeft = p.life - p.distFrac; // Gradually reduce the speed of Noise particles. if (p.type == ParticleType.noise) { p.vx -= p.lifeLeft * p.vx * .001; p.vy -= p.lifeLeft * p.vy * .001; } // Gradually reduce the size of all particles. if (p.lifeLeft < .3) { p.size -= p.size * .0015; } // Make some of the particles go rouge. if (p.distribution > rougeDistributionLmt && p.distribution < jellyDistributionLmt) { var r = Rnd.getDouble(.2, 2.5) * vecSpeedInv * p.distFrac; p.x -= p.vx * r + (p.distFrac * Rnd.getDouble(-.4, .4)); p.y -= p.vy * r + (p.distFrac * Rnd.getDouble(-.4, .4)); } // Make some of the particles ease back, for a jelly effect. if (p.distribution >= jellyDistributionLmt) { var r = Rnd.getDouble(.1, .9) * vecSpeedInv * (1 - p.lifeLeft); p.x += p.vx * r; p.y += p.vy * r; } // Reset particles once they are invisible or at the edge. if (p.lifeLeft <= 0 || p.size <= .5) { resetParticle(i); if (maxSpawnPerTick > 0) { _activateParticle(p); maxSpawnPerTick--; } } }); super.tick(duration); } void _activateParticle(Particle p) { p.x = Rnd.getDouble(spawnArea.left, spawnArea.right); p.y = Rnd.getDouble(spawnArea.top, spawnArea.bottom); p.isFilled = Rnd.getBool(); p.size = Rnd.getDouble(3, 8); p.isFlowing = false; p.distFrac = 0; p.distribution = Rnd.getInt(1, particleDistributions[2]); if (p.distribution < particleDistributions[0]) { p.type = ParticleType.hour; } else if (p.distribution < particleDistributions[1]) { p.type = ParticleType.minute; } else { p.type = ParticleType.noise; } double? angle; switch (p.type) { case ParticleType.hour: angle = _getHourRadians(); p.life = Rnd.getDouble(.5, .55); p.size = sizeMin * .010; p.isFlowing = Rnd.ratio > .85; p.color = palette!.components![palette!.components!.length - 1]; break; case ParticleType.minute: angle = _getMinuteRadians(); p.life = Rnd.getDouble(.68, .73); p.size = sizeMin * .008; p.isFlowing = Rnd.ratio > .6; p.color = palette!.components![palette!.components!.length - 1]; break; case ParticleType.noise: // Find a random angle while avoiding clutter at the hour & minute hands. var am = _getMinuteRadians(); var ah = _getHourRadians() % (pi * 2); var d = pi / 18; // Probably not the most efficient solution right here. do { angle = Rnd.ratio * pi * 2; } while (_isBetween(angle!, am - d, am + d) || _isBetween(angle, ah - d, ah + d)); p.life = Rnd.getDouble(0.75, .8); p.size = sizeMin * (Rnd.ratio > .8 ? Rnd.getDouble(.0015, .003) : Rnd.getDouble(.002, .006)); break; } // Particle movement vector. p.vx = sin(-angle); p.vy = cos(-angle); // Particle movement angle. p.a = atan2(p.vy, p.vx) + pi; // Add some speed randomeness. double v = p.type == ParticleType.noise ? Rnd.getDouble(.5, 1) : Rnd.getDouble(.3, .4); p.vx *= v; p.vy *= v; } /// Gets the radians of the hour hand. double _getHourRadians() => (time!.hour * pi / 6) + (time!.minute * pi / (6 * 60)) + (time!.second * pi / (360 * 60)); /// Gets the radians of the minute hand. double _getMinuteRadians() => (time!.minute * (2 * pi) / 60) + (time!.second * pi / (30 * 60)); /// Checks if a value is between two other values. bool _isBetween(double value, double min, double max) { return value >= min && value <= max; } /// Calculates the distance from center using pythagoras rate. double _getDistanceFromCenter(Particle p) { var a = pow(center.dx - p.x, 2); var b = pow(center.dy - p.y, 2); return sqrt(a + b); } }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/clock_seconds_painter.dart
import 'dart:math'; import 'package:flutter/material.dart'; class ClockSecondsPainter extends CustomPainter { final Color? accentColor; ClockSecondsPainter({required this.accentColor}); @override void paint(Canvas canvas, Size size) { var center = Offset(size.width / 2, size.height / 2); var now = DateTime.now(); var secSize = pi / 50; // Animate smoothly with easing. var msecs = Curves.easeOutCirc.transform(now.millisecond / 1000); msecs = msecs * 2 * pi / 60; var timeAngle = (now.second - 1) * (2 * pi / 60) + msecs - secSize / 2; timeAngle = timeAngle - pi / 2; var radiusInner = size.height * .13; var radiusOuter = size.height * .9; var paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = center.dy * .003 ..strokeCap = StrokeCap.round ..color = accentColor!.withAlpha(40); var outerRect = Rect.fromCenter( center: center, width: radiusOuter, height: radiusOuter, ); var innerRect = Rect.fromCenter( center: center, width: radiusInner, height: radiusInner, ); // Outer track. canvas.drawArc(outerRect, 0, pi * 2, false, paint); // Inner track. canvas.drawArc(innerRect, 0, pi * 2, false, paint); paint ..strokeWidth = center.dy * .015 ..color = accentColor!; // Outer indicator. canvas.drawArc(outerRect, timeAngle, secSize, false, paint); // Inner indicator. canvas.drawArc( innerRect, timeAngle - (secSize * 6), secSize * 12, false, paint); } @override bool shouldRepaint(_) => false; }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/scene.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'bg_fx.dart'; import 'clock_bg_particle_painter.dart'; import 'clock_face_painter.dart'; import 'clock_fx.dart'; import 'clock_fx_painter.dart'; import 'clock_seconds_painter.dart'; import 'palette.dart'; import 'particle_clock_fx.dart'; import 'utils/rnd.dart'; class Scene extends StatefulWidget { final Size? size; final List<Palette>? palettes; final DateTime? time; final Brightness? brightness; const Scene({ Key? key, this.size, this.palettes, this.time, this.brightness, }) : super(key: key); @override SceneState createState() => SceneState(); } class SceneState extends State<Scene> with SingleTickerProviderStateMixin { late Ticker _ticker; ClockFx? _fx; BgFx? _bgFx; late Palette _palette; Color? _bgColor; Color? _accentColor; @override void initState() { _ticker = createTicker(_tick)..start(); _fx = ParticleClockFx( size: widget.size!, time: widget.time, ); _bgFx = BgFx( size: widget.size!, time: widget.time, ); _updatePalette(); super.initState(); } @override void dispose() { _ticker.dispose(); super.dispose(); } @override void didUpdateWidget(Scene oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.time != widget.time || oldWidget.brightness != widget.brightness) { _fx!.setTime(widget.time); _bgFx!.setTime(widget.time); // Change palette every 15th second to keep things interesting. if (widget.time!.second % 15 == 0 || oldWidget.brightness != widget.brightness) { _updatePalette(); } } if (oldWidget.size != widget.size) { _fx!.setSize(widget.size!); _bgFx!.setSize(widget.size!); _bgFx!.tick(Duration(days: 0)); // Trigger repaint. } } /// Randomly selects a new palette that conforms to the clock's brightness setting. /// The background color is set to the first component of the palette, and the accent /// color is set to the color of the palette that is furthest from the background color /// in terms of luminosity. void _updatePalette() { var isDarkMode = widget.brightness == Brightness.dark; _palette = Rnd.getPalette(widget.palettes, isDarkMode); _bgColor = _palette.components![0]; _accentColor = _palette.components![_palette.components!.length - 1]; _fx!.setPalette(_palette); _bgFx!.setPalette(_palette); } void _tick(Duration duration) { _fx!.tick(duration); if (widget.time!.second % 5 == 0) _bgFx!.tick(duration); } @override Widget build(BuildContext context) { return AnimatedContainer( duration: Duration(milliseconds: 1500), curve: Curves.easeOut, color: _bgColor, child: ClipRect( child: Stack( children: <Widget>[ _buildBgBlurFx(), _buildClockFace(), CustomPaint( painter: ClockFxPainter(fx: _fx), child: Container(), ), ], ), ), ); } Widget _buildBgBlurFx() { return RepaintBoundary( child: Stack( children: <Widget>[ CustomPaint( painter: ClockBgParticlePainter( fx: _bgFx, ), child: Container(), ), BackdropFilter( filter: ImageFilter.blur( sigmaX: widget.size!.width * .05, sigmaY: 0, ), // filter: ImageFilter.blur(sigmaX: 0, sigmaY: 0), child: Container(child: Text(" ")), ), ], ), ); } Widget _buildClockFace() { var faceSize = widget.size!.height * .85; return Center( child: Container( width: faceSize, height: faceSize, child: Stack( children: <Widget>[ // Paint the second hand. CustomPaint( size: Size(faceSize, faceSize), painter: ClockSecondsPainter( accentColor: _accentColor, ), ), // Paint the clock face. RepaintBoundary( key: Key(_accentColor.toString()), child: CustomPaint( size: widget.size!, painter: ClockFacePainter( accentColor: _accentColor, ), ), ), ], ), ), ); } }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/bg_fx.dart
import 'dart:math'; import 'dart:ui'; import 'package:flutter/widgets.dart'; import 'clock_fx.dart'; import 'particle.dart'; import 'utils/rnd.dart'; final easingDelayDuration = Duration(seconds: 15); class BgFx extends ClockFx { BgFx({required Size size, required DateTime? time}) : super( size: size, time: time, numParticles: 120, ); @override void tick(Duration duration) { var secFrac = 1 - (DateTime.now().millisecond / 1000); var vecSpeed = duration.compareTo(easingDelayDuration) > 0 ? max(.2, Curves.easeInOutSine.transform(secFrac)) : 1; particles.forEach((p) { p!.y -= p.vy * vecSpeed; if (p.y > height || p.y < 0 || p.life == 0) { _activateParticle(p); } }); super.tick(duration); } void _activateParticle(Particle p) { var xRnd = Rnd.getDouble(0, width / 5); p.x = Rnd.getBool() ? width - xRnd : 0 + xRnd; p.y = Rnd.getDouble(0, height); p.a = Rnd.ratio > .95 ? Rnd.getDouble(.6, .8) : Rnd.getDouble(.08, .4); p.isFilled = Rnd.getBool(); p.size = Rnd.getDouble(height / 20, height / 5); p.life = 1; p.vx = 0; p.vy = Rnd.getDouble(-3, 3); double v = Rnd.getDouble(.1, .5); p.vx = 0; p.vy *= v; } }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/clock_face_painter.dart
import 'dart:math'; import 'package:flutter/material.dart'; /// The number of sections to divide the clock face. final int arms = 60; /// Which parts of the sections to indicate quarters. final int quarters = (arms / 12).floor(); class ClockFacePainter extends CustomPainter { final Color? accentColor; ClockFacePainter({required this.accentColor}); @override void paint(Canvas canvas, Size size) { var cx = size.width / 2; var cy = size.height / 2; var radius = min(size.width / 2, size.height / 2); var circleRaidus = radius * .012; var paint = Paint() ..style = PaintingStyle.fill ..strokeWidth = circleRaidus * .5 ..color = accentColor!; for (var i = 1; i <= arms; i++) { var angle = i * 360 / arms; var a = -angle * pi / 180; var point = Offset(cx + radius * cos(a), cy + radius * sin(a)); if (i % quarters == 0) { canvas.drawCircle( point, circleRaidus * 2, paint ..color = accentColor! ..style = PaintingStyle.fill, ); } else { canvas.drawCircle( point, circleRaidus, paint ..color = accentColor!.withAlpha(100) ..style = PaintingStyle.stroke, ); } } } @override bool shouldRepaint(_) => false; }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/clock_bg_particle_painter.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'clock_fx.dart'; class ClockBgParticlePainter extends CustomPainter { ClockFx? fx; // ChangeNotifier used as repaint notifier. ClockBgParticlePainter({required this.fx}) : super(repaint: fx); @override void paint(Canvas canvas, Size size) { fx!.particles.forEach((p) { var pos = Offset(p!.x, p.y); var paint = Paint() ..color = p.color.withAlpha((255 * p.a).floor()) ..strokeWidth = p.size * .2 ..style = p.isFilled ? PaintingStyle.fill : PaintingStyle.stroke; if (p.isFilled) { var rect = Rect.fromCenter( center: pos, width: p.size, height: p.size, ); canvas.drawRect(rect, paint); } else { canvas.drawCircle(pos, p.size / 1.2, paint); } }); } @override bool shouldRepaint(_) => false; }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/clock_fx.dart
import 'dart:math'; import 'package:flutter/widgets.dart'; import 'palette.dart'; import 'particle.dart'; import 'utils/rnd.dart'; final Color transparent = Color.fromARGB(0, 0, 0, 0); abstract class ClockFx with ChangeNotifier { /// The available canvas width for the FX. late double width; /// The available canvas height for the FX. late double height; /// The minimum value of [width] and [height]. late double sizeMin; /// The center of the canvas. late Offset center; /// The area from wich to spawn new particles. late Rect spawnArea; /// The colors used for painting. Palette? palette; /// All the FX's particles. late List<Particle?> particles; /// The maximum number of particles. int numParticles; /// Date and time used for rendering time-specific effects. DateTime? time; ClockFx({ required Size size, required DateTime? time, this.numParticles = 5000, }) { this.time = time; particles = List<Particle?>.filled(numParticles, null); palette = Palette(components: [transparent, transparent]); setSize(size); } /// Initializes the particle effect by resetting all the particles and assigning a random color from the palette. void init() { if (palette == null) return; for (int i = 0; i < numParticles; i++) { var color = Rnd.getItem(palette!.components!); particles[i] = Particle(color: color); resetParticle(i); } } /// Sets the palette used for coloring. void setPalette(Palette palette) { this.palette = palette; var colors = palette.components!.sublist(1); var accentColor = colors[colors.length - 1]; particles.where((p) => p != null).forEach((p) => p!.color = p.type == ParticleType.noise ? Rnd.getItem(colors) : accentColor); } /// Sets the time used for time-specific effects. void setTime(DateTime? time) { this.time = time; } /// Sets the canvas size and updates dependent values. void setSize(Size size) { width = size.width; height = size.height; sizeMin = min(width, height); center = Offset(width / 2, height / 2); spawnArea = Rect.fromLTRB( center.dx - sizeMin / 100, center.dy - sizeMin / 100, center.dx + sizeMin / 100, center.dy + sizeMin / 100, ); init(); } /// Resets a particle's values. Particle resetParticle(int i) { Particle p = particles[i]!; p.size = p.a = p.vx = p.vy = p.life = p.lifeLeft = 0; p.x = center.dx; p.y = center.dy; return p; } void tick(Duration duration) { notifyListeners(); } }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/particle_clock.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter_clock_helper/model.dart'; import 'package:flutter/material.dart'; import 'palette.dart'; import 'scene.dart'; class ParticleClock extends StatefulWidget { const ParticleClock(this.model); final ClockModel model; @override _ParticleClockState createState() => _ParticleClockState(); } class _ParticleClockState extends State<ParticleClock> with SingleTickerProviderStateMixin { DateTime _dateTime = DateTime.now(); Timer? _timer; double seek = 0.0; double seekIncrement = 1 / 3600; @override void initState() { super.initState(); widget.model.addListener(_updateModel); _updateTime(); _updateModel(); } @override void didUpdateWidget(ParticleClock oldWidget) { super.didUpdateWidget(oldWidget); if (widget.model != oldWidget.model) { oldWidget.model.removeListener(_updateModel); widget.model.addListener(_updateModel); } } @override void dispose() { _timer?.cancel(); widget.model.removeListener(_updateModel); widget.model.dispose(); super.dispose(); } Future<List<Palette>> _loadPalettes() async { String data = await DefaultAssetBundle.of(context).loadString("assets/palettes.json"); var palettes = json.decode(data) as List; return palettes.map((p) => Palette.fromJson(p)).toList(); } void _updateModel() { // Cause the clock to rebuild when the model changes. setState(() {}); } void _updateTime() { setState(() { _dateTime = DateTime.now(); _timer = Timer( Duration(seconds: 1) - Duration(milliseconds: _dateTime.millisecond), _updateTime, ); }); } @override Widget build(BuildContext context) { return FutureBuilder( future: _loadPalettes(), builder: (context, snapshot) { if (!snapshot.hasData) { return Container( child: Center( child: Text("Could not load palettes."), ), ); } List<Palette>? palettes = snapshot.data as List<Palette>?; return LayoutBuilder( builder: (context, constraints) { return Scene( size: constraints.biggest, palettes: palettes, time: _dateTime, brightness: Theme.of(context).brightness, ); }, ); }, ); } }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/palette.dart
import 'dart:ui'; /// Holds a list of colors. class Palette { /// The palette's color members. All unique. List<Color>? components; Palette({this.components}); /// Creates a new palette from JSON. factory Palette.fromJson(List<dynamic> json) { var components = json.map((c) => Color(int.tryParse(c)!)).toList(); return Palette(components: components); } }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/main.dart
import 'dart:io'; import 'package:flutter_clock_helper/customizer.dart'; import 'package:flutter_clock_helper/model.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'particle_clock.dart'; void main() { // A temporary measure until Platform supports web and TargetPlatform supports // macOS. if (!kIsWeb && Platform.isMacOS) { // TODO(gspencergoog): Update this when TargetPlatform includes macOS. // https://github.com/flutter/flutter/issues/31366 // See https://github.com/flutter/flutter/wiki/Desktop-shells#target-platform-override. debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; } runApp(ClockCustomizer((ClockModel model) => ParticleClock(model))); }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/clock_fx_painter.dart
import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'clock_fx.dart'; import 'particle.dart'; /// Where handles should start, denoted in percentage of full radius. const double handlesStart = .1; /// Where noise should start, denoted in percentage of full radius. const double noiseStart = .15; /// Alpha value for noise particles. const double noiseAlpha = 160; class ClockFxPainter extends CustomPainter { ClockFx? fx; // ChangeNotifier used as repaint notifier. ClockFxPainter({required this.fx}) : super(repaint: fx); @override void paint(Canvas canvas, Size size) { fx!.particles.forEach((p) { double a; // Fade in particles by calculating alpha based on distance. if (p!.type == ParticleType.noise) { a = max(0.0, (p.distFrac - .13) / p.distFrac) * 255; a = min(a, min(noiseAlpha, p.lifeLeft * 3 * 255)); } else { a = p.distFrac <= handlesStart ? 255 * Curves.easeIn.transform(p.distFrac / handlesStart) : min(255, p.lifeLeft * 10 * 255); } var alpha = a.floor(); var circlePaint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = p.size / 4 ..color = p.color.withAlpha(alpha); var particlePosition = Offset(p.x, p.y); // Fill some particles. if (p.isFilled) { circlePaint.style = PaintingStyle.fill; // Draw gradient arc stroke on some filled particles. if (p.isFlowing!) { var threshold = p.distribution < 2 ? .2 : .4; var flowAlpha = max(0, (p.distFrac - threshold) / p.distFrac) * alpha; var shader = SweepGradient( colors: [ p.color.withAlpha(0), p.color.withAlpha(flowAlpha.floor()), ], startAngle: pi, endAngle: 2 * pi, transform: GradientRotation(p.a), stops: [.6, 1], ).createShader(Rect.fromCircle( center: fx!.center, radius: p.dist, )); var gradientPaint = Paint() ..strokeWidth = p.size / 2 ..shader = shader ..style = PaintingStyle.stroke; canvas.drawCircle(fx!.center, p.dist, gradientPaint); } } canvas.drawCircle(particlePosition, p.size, circlePaint); }); } @override bool shouldRepaint(_) => true; }
0
mirrored_repositories/flutter_particle_clock
mirrored_repositories/flutter_particle_clock/lib/particle.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class Particle { /// The particle's X-position. double x; /// The particle's Y-position. double y; /// The particle's emit angle in radians. double a; /// Speed vector (horizontally). double vx; /// Speed vector (vertically). double vy; /// The distance from canvas center. double dist; /// The distance from canvas center in percentage (0-1). double distFrac; /// The particle's size. double size; /// The life length of the particle (0-1). double life; /// The life remaining of the particle (0-1). double lifeLeft; /// If the particle is filled or only stroked. bool isFilled; /// If the particle should have "speed marks". bool? isFlowing; /// The color of the particle. Color color; /// The particle's distribution value. int distribution; /// The particle's type. ParticleType type; Particle({ this.x = 0, this.y = 0, this.a = 0, this.vx = 0, this.vy = 0, this.dist = 0, this.distFrac = 0, this.size = 0, this.life = 0, this.lifeLeft = 0, this.isFilled = false, this.isFlowing = false, this.color = Colors.black, this.distribution = 0, this.type = ParticleType.noise, }); } enum ParticleType { hour, minute, noise, }
0
mirrored_repositories/flutter_particle_clock/lib
mirrored_repositories/flutter_particle_clock/lib/utils/rnd.dart
import 'dart:math'; import 'package:flutter/painting.dart'; import '../palette.dart'; class Rnd { static int _seed = DateTime.now().millisecondsSinceEpoch; static Random random = Random(_seed); static set seed(int val) => random = Random(_seed = val); static int get seed => _seed; /// Gets the next double. static get ratio => random.nextDouble(); /// Gets a random int between [min] and [max]. static int getInt(int min, int max) { return min + random.nextInt(max - min); } /// Gets a random double between [min] and [max]. static double getDouble(double min, double max) { return min + random.nextDouble() * (max - min); } /// Gets a random boolean with chance [chance]. static bool getBool([double chance = 0.5]) { return random.nextDouble() < chance; } /// Randomize the positions of items in a list. static List shuffle(List list) { for (int i = 0, l = list.length; i < l; i++) { int j = random.nextInt(l); if (j == i) { continue; } dynamic item = list[j]; list[j] = list[i]; list[i] = item; } return list; } /// Randomly selects an item from a list. static dynamic getItem(List list) { return list[random.nextInt(list.length)]; } /// Gets a random palette from a list of palettes and sorts its' colors by luminance. /// /// Given if [dark] or not, this method makes sure the luminance of the background color is valid. static Palette getPalette(List<Palette>? palettes, bool dark) { Palette? result; while (result == null) { Palette palette = Rnd.getItem(palettes!); List<Color> colors = Rnd.shuffle(palette.components!) as List<Color>; var luminance = colors[0].computeLuminance(); if (dark ? luminance <= .1 : luminance >= .1) { var lumDiff = colors .sublist(1) .asMap() .map( (i, color) => MapEntry( i, [i, (luminance - color.computeLuminance()).abs()], ), ) .values .toList(); lumDiff.sort((List<num> a, List<num> b) { return a[1].compareTo(b[1]); }); List<Color> sortedColors = lumDiff.map((d) => colors[d[0] + 1 as int]).toList(); result = Palette( components: [colors[0]] + sortedColors, ); } } return result; } }
0
mirrored_repositories/youtube
mirrored_repositories/youtube/lib/firebase_options.dart
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for macos - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.windows: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for windows - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); case TargetPlatform.linux: throw UnsupportedError( 'DefaultFirebaseOptions have not been configured for linux - ' 'you can reconfigure this by running the FlutterFire CLI again.', ); default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.', ); } } static const FirebaseOptions web = FirebaseOptions( apiKey: 'AIzaSyA6ZvBSqQ9U3g83ZIvjUZTTBOd1IELRWh0', appId: '1:895734210430:web:2e15237d20283487899d2f', messagingSenderId: '895734210430', projectId: 'yt-recreation', authDomain: 'yt-recreation.firebaseapp.com', storageBucket: 'yt-recreation.appspot.com', measurementId: 'G-R14RMXMQFD', ); static const FirebaseOptions android = FirebaseOptions( apiKey: 'AIzaSyCr54LDn0CH3FU79WcST1ueQLorQu57lW0', appId: '1:895734210430:android:4645e0a9cad39f60899d2f', messagingSenderId: '895734210430', projectId: 'yt-recreation', storageBucket: 'yt-recreation.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'AIzaSyDuidplbQLoKWenzNkC1LBGBRF3o05PqW8', appId: '1:895734210430:ios:f0798dcb7e7398c4899d2f', messagingSenderId: '895734210430', projectId: 'yt-recreation', storageBucket: 'yt-recreation.appspot.com', iosClientId: '895734210430-1t1fpc5n5vrmc1e35c39bnk43kfg9e1h.apps.googleusercontent.com', iosBundleId: 'site.ritom.youtube', ); }
0
mirrored_repositories/youtube
mirrored_repositories/youtube/lib/main.dart
import 'dart:ui'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:youtube/pages/youtube_page.dart'; import 'firebase_options.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError; PlatformDispatcher.instance.onError = (error, stack) { FirebaseCrashlytics.instance.recordError(error, stack, fatal: true); return true; }; runApp( const YoutubeApp() ); } class YoutubeApp extends StatelessWidget { const YoutubeApp({super.key}); final bottomNavTheme = const BottomNavigationBarThemeData( showUnselectedLabels: false, selectedLabelStyle: TextStyle(fontSize: 14), type: BottomNavigationBarType.fixed, ); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: "YoutubeApp", theme: ThemeData.light(useMaterial3: true).copyWith( bottomNavigationBarTheme: bottomNavTheme ), darkTheme: ThemeData.dark(useMaterial3: true).copyWith( bottomNavigationBarTheme: bottomNavTheme ), home: const YoutubePage(), ); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/pages/upload_video.dart
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/foundation.dart' show Uint8List, kIsWeb; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'package:video_player/video_player.dart'; import 'package:video_thumbnail/video_thumbnail.dart'; import 'package:youtube/components/detailed_button.dart'; import 'package:firebase_auth/firebase_auth.dart'; import '../models/video.dart'; class UploadPage extends StatefulWidget { const UploadPage({super.key}); @override State<StatefulWidget> createState() { return _UploadPageState(); } } class _UploadPageState extends State<UploadPage> { File? videoFile; late VideoPlayerController _controller; Future<void>? _initializeVideoPlayerFuture; var _startedUploading = false; String title = "",description = "",downloadLink = ""; User getCurrentUser() { return FirebaseAuth.instance.currentUser!; //Null is not possible } Future getFile() async { try { final picker = ImagePicker(); final file = await picker.pickVideo(source: ImageSource.gallery); if(file!=null) { videoFile = File(file.path); if (videoFile!=null) { _controller = VideoPlayerController.file(videoFile!); // Initialize the controller and store the Future for later use. setState(() { _initializeVideoPlayerFuture = _controller.initialize(); }); // Use the controller to loop the video. _controller.play(); _controller.setLooping(true); } else { throw Exception("File is non null but Video file from path is null"); } } else { throw Exception("Video file can not be null"); } } catch(e,stack) { FirebaseCrashlytics.instance.recordError(e, stack); Navigator.pop(context); } } @override void initState() { if (videoFile==null) { getFile(); } super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } Future<String> uploadThumbnail(String videoId)async { if(_thumbnail!=null) { final DateTime now = DateTime.now(); final int millSeconds = now.millisecondsSinceEpoch; final userId = getCurrentUser().uid; final storageRef = FirebaseStorage.instance.ref("thumbnails/$userId/$videoId/$millSeconds"); try { await storageRef.putData(_thumbnail!); return await storageRef.getDownloadURL(); } catch(e,stack) { storageRef.delete(); FirebaseCrashlytics.instance.recordError(e, stack); Navigator.pop(context); } } return ""; } void uploadVideoFireStore() async { try { final userId = getCurrentUser().uid; final DateTime now = DateTime.now(); final int millSeconds = now.millisecondsSinceEpoch; final thumbnailLink = await uploadThumbnail(millSeconds.toString()); final video = Video(ownerId: userId, id: millSeconds.toString(),title: title,description: description, thumbnail: thumbnailLink, privacy: VideoPrivacy.public,uploadTime: millSeconds); CollectionReference videosCollection = FirebaseFirestore.instance .collection('user_videos') .doc(userId) .collection("videos"); videosCollection.doc(millSeconds.toString()).set(video.toJson()).then((value) => Navigator.pop(context) ); } catch (e,stack) { FirebaseCrashlytics.instance.recordError(e, stack); } } void uploadVideoStorage() async { if(videoFile!=null) { setState(() { _startedUploading = true; }); _controller.dispose(); final DateTime now = DateTime.now(); final int millSeconds = now.millisecondsSinceEpoch; final userId = getCurrentUser().uid; final storageRef = FirebaseStorage.instance.ref("videos/$userId/$millSeconds"); try { await storageRef.putFile(videoFile!); downloadLink = await storageRef.getDownloadURL(); } catch(e,stack) { storageRef.delete(); FirebaseCrashlytics.instance.recordError(e, stack); Navigator.pop(context); } } } void _onTitleChange(String newTitle) { title = newTitle; } var _descriptionVisible = false; void _addDescription() { setState(() { _descriptionVisible = true; }); } void changeDescription(String desc) { setState(() { description = desc; }); } void _changeVisibility() { } Uint8List? _thumbnail; void pickThumb() async { final picker = ImagePicker(); final file = await picker.pickImage(source: ImageSource.gallery); if (file!=null) { final bytes = await file.readAsBytes(); setState(() { _thumbnail = bytes; }); } } void _getThumbnailImage() async { if (kIsWeb) { pickThumb(); } else { if (videoFile!=null&&_thumbnail==null) { final newThumbnail = await VideoThumbnail.thumbnailData( video: videoFile!.path, imageFormat: ImageFormat.JPEG, maxWidth: 128, quality: 75, ); setState(() { _thumbnail = newThumbnail; }); } else { pickThumb(); } } } Widget getThumbnail() { if (kIsWeb&&_thumbnail==null) { return ElevatedButton(onPressed: _getThumbnailImage, child: const Text("Upload thumbnail")); } else { if (_thumbnail==null) { _getThumbnailImage(); } return IconButton(onPressed: _getThumbnailImage, icon: _thumbnail == null ? const Icon(Icons.add) : Image.memory(_thumbnail!),); } } Widget geTitleAndThumb() { return SizedBox( height: 156, child: Row( children: [ SizedBox( width: 108, height: 108, child:getThumbnail(), ), SizedBox( width: 230, height: 150, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Title",style: Theme.of(context).textTheme.headlineSmall,), TextField( onChanged: _onTitleChange, decoration: const InputDecoration( labelText: "Caption", hintText: "Caption your video" ), ) ], ), ) ], ), ); } Widget buildPlayer() { return Column( children: [ FutureBuilder( future: _initializeVideoPlayerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { // If the VideoPlayerController has finished initialization, use // the data it provides to limit the aspect ratio of the video. return AspectRatio( aspectRatio: _controller.value.aspectRatio, // Use the VideoPlayer widget to display the video. child: VideoPlayer(_controller), ); } else { // If the VideoPlayerController is still initializing, show a // loading spinner. return const Center( child: CircularProgressIndicator(), ); } }, ), Padding( padding: const EdgeInsets.all(8.0), child: Align( alignment: Alignment.centerRight, child: ElevatedButton(onPressed: uploadVideoStorage, child: const Text("Upload")), ), ) ], ); } Widget getBody() { if (_descriptionVisible) { return Padding( padding: const EdgeInsets.only(left: 16,right: 16), child: TextField(minLines: 12,maxLines: 20, onChanged: changeDescription, ) ); } if (_startedUploading) { return Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ geTitleAndThumb(), SizedBox( width: 250, child: ElevatedButton(onPressed: _addDescription, child: const Text("Add description")), ), CustomButton(startIcon: Icons.lock, label: "Visibility", value: "Public", onPressed: _changeVisibility), Align( alignment: Alignment.centerRight, child: ElevatedButton(onPressed: uploadVideoFireStore,child: const Text("Upload video"),), ) ], ); } else { if (_initializeVideoPlayerFuture!=null) { return buildPlayer(); } else { return const Text("Getting video"); } } } void onSubmit () { if (_descriptionVisible) { setState(() { _descriptionVisible = false; }); } else { uploadVideoFireStore(); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading:false, title: const Text("Upload a new video"), actions: [ IconButton(onPressed: onSubmit, icon: const Icon(Icons.done)) ], ), body: getBody() ); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/pages/channel_page.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:flutter/material.dart'; import 'package:youtube/models/user.dart'; import '../components/youtube_video.dart'; import '../models/channel.dart'; import '../models/video.dart'; class ChannelPage extends StatefulWidget { final UserModel user; const ChannelPage({super.key, required this.user}); @override State<ChannelPage> createState() => _ChannelPageState(); } class _ChannelPageState extends State<ChannelPage> { Future<Channel?> createChannelModel() async { try { final channelsCollection = FirebaseFirestore.instance.collection('channels'); final channelDoc = await channelsCollection.doc(widget.user.id).get(); if (channelDoc.exists) { final data = channelDoc.data(); if (data!=null) { return Channel.fromJson(data); } else { throw Exception("Somehow channel data is null"); } } else { final channel = Channel(id: widget.user.id, username: widget.user.username, displayName: widget.user.name, description: ''); await channelsCollection.doc(widget.user.id).set(channel.toJson()); return channel; } } catch (e,stack) { FirebaseCrashlytics.instance.recordError(e, stack); Navigator.pop(context); } return null; } @override void initState() { super.initState(); } void onSearch() { } void onMenu() { } void subscribeChannel() { } Widget buildInformation(Channel channel) { const informationTextStyle = TextStyle( fontSize: 12, color: Colors.grey, ); return SizedBox( width: MediaQuery.of(context).size.width, height: 70, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( channel.username, maxLines: 1, overflow: TextOverflow.ellipsis, style: informationTextStyle, ), const SizedBox(width: 8,), const Text("1M subscribers",style: informationTextStyle,), const SizedBox(width: 8,), Text("${channel.videoCount} videos",style: informationTextStyle,) ], ), Padding( padding: const EdgeInsets.only(left: 16,right: 16), child: Text( channel.description, maxLines: 3, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.labelSmall, ) ), ], ), ); } Widget buildSubscribe() { return Padding( padding: const EdgeInsets.all(12.0), child: SizedBox( width: MediaQuery.of(context).size.width-96, height: 42, child: ElevatedButton( onPressed: subscribeChannel, child: const Text("Subscribe") ), ), ); } Future<List<Video>> buildVideos()async { final collection = await FirebaseFirestore.instance. collection("user_videos").doc(widget.user.id) .collection("videos") .orderBy("uploadTime",descending: true) .get(); final videos = collection.docs.map((e) => Video.fromJson(e.data())).toList(); return videos; } Widget buildHomeTab() { return buildVideosTab(); // TODO create a separate tab } Widget buildVideosTab() { return FutureBuilder( future: buildVideos(), builder: (futureContext,snapshot) { if (snapshot.hasError){ return Center(child: Column( children: [ const Text("Something went wrong"), Text("Error ${snapshot.error}"), ], ),); } if (snapshot.hasData) { if (snapshot.data!=null) { final videos = snapshot.data!; return ListView.builder( itemCount: videos.length, itemBuilder: (listContext,index) { return YoutubeVideo(video: videos[index], context: listContext,); //Maybe create another widget } ); } else { return const Center(child: Text("Something went wrong.This should not happen"),); } } return const Center(child: CircularProgressIndicator(),); }); } Widget buildToCome() { return const Center(child: Text("Coming soon"),); } @override Widget build(BuildContext context) { return FutureBuilder( future: createChannelModel(), builder: (futureContext,snapshot) { if (snapshot.hasError) { return const Center(child: Text("Something went wrong"),); } if (!snapshot.hasData) { return const Center(child: CircularProgressIndicator(),); } if (snapshot.data==null) { return const Center(child: Text("Something went wrong"),); } final channel = snapshot.data!; return Scaffold( appBar: AppBar( title: Text(channel.username), actions: [ IconButton(onPressed: onSearch, icon: const Icon(Icons.search)), IconButton(onPressed: onMenu, icon: const Icon(Icons.more_vert)), ], ), body: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox( height: 200, width: MediaQuery.of(context).size.width, child: Image( fit: BoxFit.fill, image: NetworkImage(channel.banner), errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { // If loading from the network fails, return the fallback asset return const Image(image: AssetImage("assets/GradientImage.jpg"),fit: BoxFit.fill,); }, ), ), Text(channel.displayName, style: Theme.of(futureContext).textTheme.headlineMedium,), buildInformation(channel), buildSubscribe(), SizedBox( height: 300, child: DefaultTabController( length: 4, child: Scaffold( appBar: AppBar( toolbarHeight: 0, automaticallyImplyLeading:false, bottom: const TabBar( tabs: [ Tab(text:"Home"), Tab(text:"Videos"), Tab(text:"Playlists"), Tab(text:"About"), ], ), ), body: TabBarView( children: [ buildHomeTab(), buildVideosTab(), buildToCome(), buildToCome(), ], ), ), ), ), ], ), ); }); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/pages/youtube_page.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:firebase_ui_auth/firebase_ui_auth.dart' as auth_ui; import 'package:firebase_ui_auth/firebase_ui_auth.dart'; import 'package:firebase_ui_oauth_google/firebase_ui_oauth_google.dart' as auth_google; import 'package:flutter/material.dart'; import 'package:youtube/nav_pages/home.dart'; import 'package:youtube/nav_pages/library.dart'; import 'package:youtube/nav_pages/notifications.dart'; import 'package:youtube/nav_pages/subscriptions.dart'; import 'package:youtube/pages/upload_video.dart'; import 'package:youtube/pages/channel_page.dart'; import '../models/user.dart'; class YoutubePage extends StatefulWidget { const YoutubePage({super.key}); @override State<YoutubePage> createState() => _YoutubePageState(); } class _YoutubePageState extends State<YoutubePage> { var _index = 0; StatefulWidget _currentBody = const HomePage(); late UserModel newUser; Future<void> checkAndCreateUser(User user) async { final usersCollection = FirebaseFirestore.instance.collection('users'); // Check if the user document already exists final userDoc = await usersCollection.doc(user.uid).get(); if (!userDoc.exists) { String newName = user.displayName?? user.email!.split("@")[0]; newUser = UserModel(id: user.uid, name: newName, username: user.uid, email: user.email!, profileImage: user.photoURL); await usersCollection.doc(user.uid).set(newUser.toJson()); } else { final data = userDoc.data(); if (data!=null) { newUser = UserModel.fromJson(data); } else { throw Exception("User Doc exists but data is null"); } } } Future<String> onState() async { try { User? firebaseUser = FirebaseAuth.instance.currentUser; if (firebaseUser!=null) { await checkAndCreateUser(firebaseUser); } } catch(e,stacktrace) { FirebaseCrashlytics.instance.recordError(e,stacktrace); } return "Done"; } void _changeIndex(int newIndex) { setState(() { _index = newIndex; if (newIndex == 2) { _index = 0; showModalBottomSheet(context: context, builder: buildUploadButton); } else if (newIndex == 4) { _currentBody = pages[3]; } else { _currentBody = pages[newIndex]; } }); } Widget buildUploadItem(BuildContext context,IconData icon, String text, void Function() onPress) { return InkWell( onTap: ()=> { Navigator.pop(context), onPress() }, child: Padding( padding: const EdgeInsets.all(12.0), child: Row( children: [ Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: Theme.of(context).colorScheme.outline) ), child: Icon(icon,size: 32,), ), const SizedBox(width: 16,), Text(text,style: const TextStyle(fontSize: 24),), ], ), ), ); } void onUpload() { Navigator.push( context, MaterialPageRoute(builder: (context) => const UploadPage()), ); } void onCreatePost() { } Widget buildUploadButton(BuildContext context) { return SizedBox( height: 420, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text("Create"), IconButton(onPressed: () => { Navigator.pop(context)}, icon: const Icon(Icons.close)) ], ), buildUploadItem(context,Icons.arrow_upward_outlined, "Upload a video", onUpload), buildUploadItem(context,Icons.edit_square, "Create a post", onCreatePost), ], ), ); } final pages = [ const HomePage(), const NotificationPage(), const SubscriptionPage(), const LibraryPage(), ]; final nav = [ const BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"), const BottomNavigationBarItem( icon: Icon(Icons.notifications), label: "Notifications"), const BottomNavigationBarItem(icon: Icon(Icons.add), label: "Add post"), const BottomNavigationBarItem( icon: Icon(Icons.subscriptions), label: "Subscriptions"), const BottomNavigationBarItem( icon: Icon(Icons.video_library), label: "Library") ]; void gotoCurrentUser() { Navigator.push( context, MaterialPageRoute(builder: (context) => ChannelPage(user: newUser)) ); } @override Widget build(BuildContext context) { return StreamBuilder<User?>( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (!snapshot.hasData) { return auth_ui.SignInScreen( providers: [ auth_ui.EmailAuthProvider(), auth_google.GoogleProvider( clientId: "895734210430-uc47lqjp40uo1ip4dudnim2skn1uhnop.apps.googleusercontent.com"), ], headerBuilder: (context, constraints, shrinkOffset) { return Padding( padding: const EdgeInsets.all(20), child: AspectRatio( aspectRatio: 1, child: Image.asset('assets/Youtube.png'), ), ); }, subtitleBuilder: (context, action) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: action == AuthAction.signIn ? const Text('Welcome back, Just sign in please') : const Text('Still not a user, sign up now.'), ); }, footerBuilder: (context, action) { return const Padding( padding: EdgeInsets.only(top: 16), child: Text( 'By signing in, you agree to our terms and conditions.', style: TextStyle(color: Colors.grey), ), ); }, sideBuilder: (context, shrinkOffset) { return Padding( padding: const EdgeInsets.all(20), child: AspectRatio( aspectRatio: 1, child: Image.asset('assets/Youtube.png'), ), ); }, ); } else { return FutureBuilder( future: onState(), builder: (futureContext,snapshot){ if (!snapshot.hasData) { return SafeArea( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("Creating user data",style: Theme.of(context).textTheme.bodyLarge,), const CircularProgressIndicator(), ], ), ), ); } return Scaffold( appBar: AppBar( title: const Text("Youtube", textAlign: TextAlign.center,), leading: const Center( child: Image(image: AssetImage('assets/Youtube.png'), ), ), actions: [ Padding( padding: const EdgeInsets.only(right: 16), child: InkWell( onTap: gotoCurrentUser, child: const UserAvatar(size: 48,), ), ) ], ), bottomNavigationBar: BottomNavigationBar( items: nav, currentIndex: _index, onTap: _changeIndex, iconSize: 20, ), body: _currentBody ); }); } }, ); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/nav_pages/notifications.dart
import 'package:flutter/cupertino.dart'; class NotificationPage extends StatefulWidget { const NotificationPage({super.key}); @override State<StatefulWidget> createState() { return NotificationPageState(); } } class NotificationPageState extends State<NotificationPage> { @override Widget build(BuildContext context) { return const Column( children: [ Text("Dummy text in notifs") ], ); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/nav_pages/library.dart
import 'package:flutter/cupertino.dart'; class LibraryPage extends StatefulWidget { const LibraryPage({super.key}); @override State<StatefulWidget> createState() { return LibraryPageState(); } } class LibraryPageState extends State<LibraryPage> { @override Widget build(BuildContext context) { return const Column( children: [ Text("Dummy text") ], ); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/nav_pages/subscriptions.dart
import 'package:flutter/cupertino.dart'; class SubscriptionPage extends StatefulWidget { const SubscriptionPage({super.key}); @override State<StatefulWidget> createState() { return SubscriptionPageState(); } } class SubscriptionPageState extends State<SubscriptionPage> { @override Widget build(BuildContext context) { return const Column( children: [ Text("Dummy text") ], ); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/nav_pages/home.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import '../components/youtube_video.dart'; import '../models/video.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<StatefulWidget> createState() { return HomePageState(); } } class HomePageState extends State<HomePage> { Future<List<Video>> buildVideos()async { List<Video> videos = []; final currentUser = FirebaseAuth.instance.currentUser!; final subscribers = await FirebaseFirestore.instance. collection("user_videos").doc(currentUser.uid).get(); for (String subscriberId in subscribers.data()?["user_ids"]) { final collection = await FirebaseFirestore.instance. collection("user_videos").doc(subscriberId) .collection("videos") .orderBy("uploadTime",descending: true) .get(); final data = collection.docs.map((e) => Video.fromJson(e.data())).toList(); videos.addAll(data); } videos.shuffle(); return videos; } @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return FutureBuilder( future: buildVideos(), builder: (futureContext,snapshot) { if (snapshot.hasError){ return Center(child: Column( children: [ const Text("Something went wrong"), Text("Error ${snapshot.error}"), ], ),); } if (snapshot.hasData) { if (snapshot.data!=null) { final videos = snapshot.data!; return ListView.builder( itemCount: videos.length, itemBuilder: (listContext,index) { return YoutubeVideo(video: videos[index], context: listContext,); } ); } else { return const Center(child: Text("Something went wrong.This should not happen"),); } } return const Center(child: CircularProgressIndicator(),); }); } }
0
mirrored_repositories/youtube/lib
mirrored_repositories/youtube/lib/components/user_avatar.dart
import 'package:flutter/material.dart'; class UserAvatar extends StatefulWidget { final String? profileImage; final void Function() onPress; const UserAvatar({super.key, required this.profileImage,required this.onPress}); @override State<UserAvatar> createState() => _UserAvatarState(); } class _UserAvatarState extends State<UserAvatar> { @override Widget build(BuildContext context) { if (widget.profileImage==null) { return const Center( child: SizedBox( width: 24, height: 24, child: CircularProgressIndicator(), ), ); } else { return CircleAvatar( foregroundImage: NetworkImage(widget.profileImage!), backgroundColor: Theme.of(context).colorScheme.inverseSurface.withAlpha(30), radius: 20, ); } } }
0