repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/shared/error.dart
import 'package:flutter/material.dart'; class ErrorMessage extends StatelessWidget { final String message; const ErrorMessage({Key? key, this.message = 'lmao rip'}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: Text(message), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/shared/bottom_nav.dart
import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; class IconBottomButton extends StatelessWidget { final IconData icon; final bool selected; final Function() onPressed; const IconBottomButton( {required this.icon, required this.selected, required this.onPressed, Key? key}) : super(key: key); @override Widget build(BuildContext context) { return IconButton( iconSize: 27.0, icon: Icon(icon, color: selected ? const Color(0xFF84C879) : const Color(0xFFC5D0DB)), onPressed: onPressed, ); } } // onPressed: () { // Navigator.pushNamed(context, '/'); // },
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/sideFunctions/depot_map.dart
import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'dart:async'; class MapScreen extends StatefulWidget { const MapScreen({Key? key}) : super(key: key); @override _MapScreenState createState() => _MapScreenState(); } class _MapScreenState extends State<MapScreen> { // ignore: prefer_final_fields Completer<GoogleMapController> _controller = Completer(); Iterable markers = []; // ignore: prefer_final_fields Iterable _markers = Iterable.generate(AppConstant.list.length, (index) { return Marker( markerId: MarkerId(AppConstant.list[index]['id']), position: LatLng( AppConstant.list[index]['lat'], AppConstant.list[index]['lon'], ), infoWindow: InfoWindow( title: AppConstant.list[index]["title"], snippet: AppConstant.list[index]["snippet"])); }); @override void initState() { setState(() { markers = _markers; }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Local Waste Depots"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: GoogleMap( onMapCreated: (GoogleMapController controller) { _controller.complete(controller); }, markers: Set.from(markers), initialCameraPosition: const CameraPosition( target: LatLng(43.592337920450426, -79.61564521970341), zoom: 10, ), )); } } class AppConstant { static List<Map<String, dynamic>> list = [ { "title": "WM Mississauga Transfer Station", "snippet": "6465 Danville Rd, Mississauga, ON L5T 2H7", "id": "1", "lat": 43.6553242463149, "lon": -79.68118478254947, }, { "title": "Disposal Bins Mississauga", "snippet": "1270 Central Pkwy W #404, Mississauga, ON L5C 4P4", "id": "2", "lat": 43.581256635270016, "lon": -79.66813851813716, }, { "title": "Call Disposal Services Ltd", "snippet": "190 Bovaird Dr W, Brampton, ON L7A 1A2", "id": "3", "lat": 43.70498288451847, "lon": -79.79173470730636 }, { "title": "Walker Waste & Recycling Drop-off", "snippet": "5030 Mainway, Burlington, ON L7L 5Z1", "id": "4", "lat": 43.38895249350822, "lon": -79.7793750883646 }, { "title": "AG Disposal Services Inc", "snippet": "740 Weller Ct, Oakville, ON L6K 3S9", "id": "5", "lat": 43.441822373575995, "lon": -79.69972421090003 }, { "title": "Halton Waste Management Site", "snippet": "5400 Regional Rd 25, Milton, ON L9E 0L2", "id": "6", "lat": 43.47693679264958, "lon": -79.82373223320872 }, { "title": "Tech Reset Electronic Recycling", "snippet": "2301 Royal Windsor Dr Unit # 2, Mississauga, ON L5J 1K5", "id": "7", "lat": 43.5059772432798, "lon": -79.63681031810616 }, { "title": "Roadrunner Bins Inc.", "snippet": "100 Emby Dr, Mississauga, ON L5M 1H6", "id": "8", "lat": 43.578893919269774, "lon": -79.71491624285193 }, { "title": "WM Wentworth Transfer Station", "snippet": "117 Wentworth Ct, Brampton, ON L6T 5L4", "id": "9", "lat": 43.744308163762604, "lon": -79.66397572841385 }, { "title": "SHORNCLIFFE DISPOSAL SERVICES", "snippet": "51 Shorncliffe Rd, Etobicoke, ON M8Z 5K2", "id": "10", "lat": 43.628988504649456, "lon": -79.54213906683528 }, { "title": "Toronto Household Hazardous Waste Drop-off Depot", "snippet": "50 Ingram Dr, North York, ON M6M 2L6", "id": "11", "lat": 43.70129481679347, "lon": -79.47144140281334 }, { "title": "GIC Medical Disposal", "snippet": "250 University Avenue, 2nd Floor, Toronto, ON M5H 3E5", "id": "12", "lat": 43.650181453627965, "lon": -79.38857187345802 }, { "title": "WM Wentworth Transfer Station", "snippet": "20 Esandar Dr, Toronto, ON M4G 1Y2", "id": "13", "lat": 43.70641384044831, "lon": -79.3582307264573 }, { "title": "Commissioners Street Transfer Station", "snippet": "400 Commissioners St, Toronto, ON M4M 3K2", "id": "14", "lat": 43.651734040547794, "lon": -79.33925141578226 }, { "title": "Bin There Dump That Toronto", "snippet": "56 The Esplanade, Toronto, ON M5E 1A6", "id": "15", "lat": 43.64726248044176, "lon": -79.37422742209225 }, { "title": "Bermondsey Transfer Station", "snippet": "188 Bermondsey Rd, North York, ON M4A 1Y1", "id": "16", "lat": 43.72078355240848, "lon": -79.32011117245861 }, { "title": "Scarborough Disposal", "snippet": "63 Raleigh Ave, Scarborough, ON M1K 1A1", "id": "17", "lat": 43.703582856330044, "lon": -79.26467514742986 }, { "title": "Waste Connections of Canada - Toronto", "snippet": "650 Creditstone Rd, Concord, ON L4K 5C8", "id": "18", "lat": 43.80439746693767, "lon": -79.52025747838844 }, { "title": "Thornhill Recycling Depot", "snippet": "5 Green Ln, Thornhill, ON L3T 7P7", "id": "19", "lat": 43.82127499043211, "lon": -79.40069533121884 }, { "title": "Victoria Park Transfer Station", "snippet": "3350 Victoria Park Ave, North York, ON M2H 2E1", "id": "20", "lat": 43.80353023638217, "lon": -79.33752394528311 }, { "title": "Earl Turcott Waste Management Facility", "snippet": "300 Rodick Rd, Markham, ON L6G 1E2", "id": "21", "lat": 43.83461879171274, "lon": -79.34833861183542 }, { "title": "Markham Household Hazardous Waste Depot", "snippet": "403 Rodick Rd #383, Markham, ON L6G 1B2", "id": "22", "lat": 43.83725004768767, "lon": -79.34518433409096 }, ]; }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/sideFunctions/calendar.dart
import 'package:flutter/material.dart'; import 'package:syncfusion_flutter_calendar/calendar.dart'; class Calendar extends StatefulWidget { const Calendar({Key? key}) : super(key: key); @override _CalendarState createState() => _CalendarState(); } class _CalendarState extends State<Calendar> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Peel Waste Pickup Calendar"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: Padding( padding: const EdgeInsets.only(top: 10), child: SfCalendar( headerStyle: const CalendarHeaderStyle( textAlign: TextAlign.center, textStyle: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, )), view: CalendarView.month, firstDayOfWeek: 7, monthViewSettings: const MonthViewSettings( showAgenda: true, agendaItemHeight: 50, ), dataSource: MeetingDataSource(getAppointments()), ), )); } } List<Appointment> getAppointments() { List<Appointment> meetings = <Appointment>[]; meetings.add(Appointment( startTime: DateTime(2022, 1, 4), endTime: DateTime(2022, 1, 4), subject: 'Recycling Collection', color: Colors.blue, recurrenceRule: 'FREQ=DAILY;INTERVAL=14;COUNT=30', recurrenceExceptionDates: <DateTime>[ DateTime(2022, 2, 22), DateTime(2022, 5, 24), DateTime(2022, 8, 2), DateTime(2022, 10, 11), ], isAllDay: true)); meetings.add(Appointment( startTime: DateTime(2022, 1, 4), endTime: DateTime(2022, 1, 4), subject: 'Organics Collection', color: Colors.green, recurrenceRule: 'FREQ=DAILY;INTERVAL=7;COUNT=54', recurrenceExceptionDates: <DateTime>[ DateTime(2022, 2, 22), DateTime(2022, 5, 24), DateTime(2022, 8, 2), DateTime(2022, 9, 6), DateTime(2022, 10, 11), DateTime(2022, 12, 27), ], isAllDay: true)); meetings.add(Appointment( startTime: DateTime(2022, 1, 11), endTime: DateTime(2022, 1, 11), subject: 'Garbage Collection', color: Colors.black, recurrenceRule: 'FREQ=DAILY;INTERVAL=14;COUNT=30', recurrenceExceptionDates: <DateTime>[ DateTime(2022, 2, 22), DateTime(2022, 9, 6), DateTime(2022, 12, 27), ], isAllDay: true)); //Yard Waste 1 meetings.add(Appointment( startTime: DateTime(2022, 3, 8), endTime: DateTime(2022, 3, 8), subject: 'Yard Waste Collection', color: Colors.brown, recurrenceRule: 'FREQ=DAILY;INTERVAL=7;COUNT=20', recurrenceExceptionDates: <DateTime>[ DateTime(2022, 5, 24), DateTime(2022, 6, 28), DateTime(2022, 12, 27), ], isAllDay: true)); //Yard Waste 2 meetings.add(Appointment( startTime: DateTime(2022, 8, 16), endTime: DateTime(2022, 8, 16), subject: 'Yard Waste Collection', color: Colors.brown, recurrenceRule: 'FREQ=DAILY;INTERVAL=14;COUNT=4', isAllDay: true)); //Yard Waste 3 meetings.add(Appointment( startTime: DateTime(2022, 10, 4), endTime: DateTime(2022, 10, 4), subject: 'Yard Waste Collection', color: Colors.brown, recurrenceRule: 'FREQ=DAILY;INTERVAL=7;COUNT=10', recurrenceExceptionDates: <DateTime>[ DateTime(2022, 10, 11), ], isAllDay: true)); return meetings; } class MeetingDataSource extends CalendarDataSource { MeetingDataSource(List<Appointment> source) { appointments = source; } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/sideFunctions/carbon.dart
// ignore_for_file: avoid_unnecessary_containers, prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:myapp/services/firestore.dart'; import 'package:myapp/shared/error.dart'; import 'package:myapp/shared/loading.dart'; import 'package:syncfusion_flutter_gauges/gauges.dart'; class CarbonScreen extends StatefulWidget { const CarbonScreen({Key? key}) : super(key: key); @override _CarbonScreenState createState() => _CarbonScreenState(); } class _CarbonScreenState extends State<CarbonScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("My Carbon Savings"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: fetchCarbon()); } FutureBuilder<double> fetchCarbon() { return FutureBuilder<double>( future: FirestoreService().getCarbon(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var carbon = snapshot.data!; var carbonString = carbon.toString(); return Center( child: Column( children: [ Container( padding: const EdgeInsets.all(25), child: SfRadialGauge(axes: <RadialAxis>[ RadialAxis(minimum: 0, maximum: 150, ranges: <GaugeRange>[ GaugeRange( startValue: 0, endValue: 50, color: Colors.green), GaugeRange( startValue: 50, endValue: 100, color: Colors.orange), GaugeRange( startValue: 100, endValue: 150, color: Colors.red) ], pointers: <GaugePointer>[ NeedlePointer( value: carbon, enableAnimation: true, ) ], annotations: <GaugeAnnotation>[ GaugeAnnotation( widget: Container( child: Text('$carbonString LBs CO2', style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold))), angle: 90, positionFactor: 0.5) ]) ])), Container( margin: const EdgeInsets.symmetric(horizontal: 30.0), child: Image.asset('assets/encouragewizard.png'), ) ], )); } else { return const Text('No topics in Firestore. Check Database'); } }); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/quiz/quiz.dart
import 'package:flutter/material.dart'; class QuizScreen extends StatelessWidget { const QuizScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container(); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/login/login.dart
// ignore_for_file: unnecessary_const import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:myapp/services/auth.dart'; import 'package:myapp/services/firestore.dart'; import 'package:sign_in_with_apple/sign_in_with_apple.dart'; import 'package:carousel_slider/carousel_slider.dart'; final List<String> imgList = [ "assets/onboarding1.png", "assets/onboarding2.png", "assets/onboarding3.png", ]; final List<Widget> imageSliders = imgList .map((item) => Container( margin: const EdgeInsets.only(bottom: 30), child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: Stack( children: <Widget>[ Image.asset( item, fit: BoxFit.cover, width: 1000.0, height: 1200, ), ], )), )) .toList(); class LoginScreen extends StatelessWidget { const LoginScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: const Color(0xFFF9FCFF), body: Container( padding: const EdgeInsets.all(30), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ ///Carousel CarouselSlider( options: CarouselOptions( height: 350, autoPlay: true, viewportFraction: 0.9, aspectRatio: 2.0, enlargeCenterPage: true, ), items: imageSliders, ), ///Guest Flexible( child: LoginButton( icon: FontAwesomeIcons.userNinja, text: 'Continue as guest', loginMethod: AuthService().anonLogin, color: const Color(0xFF84C879)), ), ///Google LoginButton( icon: FontAwesomeIcons.google, text: 'Sign in with Google', loginMethod: AuthService().googleLogin, color: Colors.blue), ///Apple FutureBuilder<Object>( future: SignInWithApple.isAvailable(), builder: (context, snapshot) { if (snapshot.data == true) { return SignInWithAppleButton( borderRadius: const BorderRadius.all(Radius.circular(12)), onPressed: () { AuthService().signInWithApple(); }, ); } else { return Container(); } }, ), ], ), ), ); } } class LoginButton extends StatelessWidget { final firestoreInstance = FirebaseFirestore.instance; final Color color; final IconData icon; final String text; final Function loginMethod; LoginButton( {Key? key, required this.text, required this.icon, required this.color, required this.loginMethod}) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.only(bottom: 10), child: ElevatedButton.icon( icon: Icon( icon, color: Colors.white, size: 20, ), style: TextButton.styleFrom( padding: const EdgeInsets.all(20), backgroundColor: color, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), // <-- Radius ), ), onPressed: () { loginMethod(); }, label: Text(text, textAlign: TextAlign.center), )); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/drawerScreens/statistics.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:avatar_view/avatar_view.dart'; import 'package:myapp/services/firestore.dart'; import 'package:myapp/shared/error.dart'; import 'package:myapp/shared/loading.dart'; class StatScreen extends StatefulWidget { const StatScreen({Key? key}) : super(key: key); @override _StatScreenState createState() => _StatScreenState(); } class _StatScreenState extends State<StatScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("User Statistics"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: Center( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.only(top: 30), child: AvatarView( radius: 60, borderWidth: 5, borderColor: const Color(0xFF84C879), avatarType: AvatarType.CIRCLE, imagePath: "assets/wizard.png", placeHolder: Icon( Icons.person, size: 50, ), errorWidget: Icon( Icons.error, size: 50, ), ), ), Expanded( child: Padding( padding: const EdgeInsets.only(top: 30), child: nameFetch(), ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only(right: 10), child: Icon( Icons.calendar_today, size: 40, ), ), Text( "Join Date:", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ], ), ), Expanded( flex: 1, child: Padding( padding: const EdgeInsets.only(top: 5), child: dateFetch(), ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.bar_chart, size: 45, ), Text( "Total Scans:", style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ], ), ), Expanded( flex: 2, child: Padding( padding: const EdgeInsets.only(top: 5), child: scanFetch(), ), ), ], ), ), ); } FutureBuilder<String> nameFetch() { return FutureBuilder<String>( future: FirestoreService().getName(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var name = snapshot.data!; return Text( name, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ); } else { return const Text('Check Database'); } }); } FutureBuilder<String> scanFetch() { return FutureBuilder<String>( future: FirestoreService().scanCount(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var name = snapshot.data!; return Text( name, style: TextStyle( fontSize: 36, color: const Color(0xFF84C879), ), ); } else { return const Text('Check Database'); } }); } FutureBuilder<String> dateFetch() { return FutureBuilder<String>( future: FirestoreService().joinDate(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var name = snapshot.data!; return Text( name, style: TextStyle( fontSize: 30, color: const Color(0xFF84C879), ), ); } else { return const Text('Check Database'); } }); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/drawerScreens/privacy.dart
import 'dart:ui'; import 'package:flutter/material.dart'; class PrivacyScreen extends StatelessWidget { const PrivacyScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Privacy Policy"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: const SingleChildScrollView( scrollDirection: Axis.vertical, child: Padding( padding: EdgeInsets.only(top: 20), child: Text( ''' Privacy Policy ============== Last updated: January 11, 2022 This Privacy Policy describes Our policies and procedures on the collection, use and disclosure of Your information when You use the Service and tells You about Your privacy rights and how the law protects You. We use Your Personal data to provide and improve the Service. By using the Service, You agree to the collection and use of information in accordance with this Privacy Policy. This Privacy Policy has been created with the help of the [Privacy Policy Template](https://www.termsfeed.com/blog/sample-privacy- policy-template/). Interpretation and Definitions ============================== Interpretation -------------- The words of which the initial letter is capitalized have meanings defined under the following conditions. The following definitions shall have the same meaning regardless of whether they appear in singular or in plural. Definitions ----------- For the purposes of this Privacy Policy: * Account means a unique account created for You to access our Service or parts of our Service. * Affiliate means an entity that controls, is controlled by or is under common control with a party, where "control" means ownership of 50% or more of the shares, equity interest or other securities entitled to vote for election of directors or other managing authority. * Application means the software program provided by the Company downloaded by You on any electronic device, named WasteWizard * Company (referred to as either "the Company", "We", "Us" or "Our" in this Agreement) refers to WasteWizard. * Country refers to: Ontario, Canada * Device means any device that can access the Service such as a computer, a cellphone or a digital tablet. * Personal Data is any information that relates to an identified or identifiable individual. * Service refers to the Application. * Service Provider means any natural or legal person who processes the data on behalf of the Company. It refers to third-party companies or individuals employed by the Company to facilitate the Service, to provide the Service on behalf of the Company, to perform services related to the Service or to assist the Company in analyzing how the Service is used. * Usage Data refers to data collected automatically, either generated by the use of the Service or from the Service infrastructure itself (for example, the duration of a page visit). * You means the individual accessing or using the Service, or the company, or other legal entity on behalf of which such individual is accessing or using the Service, as applicable. Collecting and Using Your Personal Data ======================================= Types of Data Collected ----------------------- Personal Data ~~~~~~~~~~~~~ While using Our Service, We may ask You to provide Us with certain personally identifiable information that can be used to contact or identify You. Personally identifiable information may include, but is not limited to: * First name and last name * Address, State, Province, ZIP/Postal code, City * Usage Data Usage Data ~~~~~~~~~~ Usage Data is collected automatically when using the Service. Usage Data may include information such as Your Device's Internet Protocol address (e.g. IP address), browser type, browser version, the pages of our Service that You visit, the time and date of Your visit, the time spent on those pages, unique device identifiers and other diagnostic data. When You access the Service by or through a mobile device, We may collect certain information automatically, including, but not limited to, the type of mobile device You use, Your mobile device unique ID, the IP address of Your mobile device, Your mobile operating system, the type of mobile Internet browser You use, unique device identifiers and other diagnostic data. We may also collect information that Your browser sends whenever You visit our Service or when You access the Service by or through a mobile device. Information Collected while Using the Application ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While using Our Application, in order to provide features of Our Application, We may collect, with Your prior permission: * Information regarding your location * Information from your Device's phone book (contacts list) * Pictures and other information from your Device's camera and photo library We use this information to provide features of Our Service, to improve and customize Our Service. The information may be uploaded to the Company's servers and/or a Service Provider's server or it may be simply stored on Your device. You can enable or disable access to this information at any time, through Your Device settings. Use of Your Personal Data ------------------------- The Company may use Personal Data for the following purposes: * To provide and maintain our Service , including to monitor the usage of our Service. * To manage Your Account: to manage Your registration as a user of the Service. The Personal Data You provide can give You access to different functionalities of the Service that are available to You as a registered user. * For the performance of a contract: the development, compliance and undertaking of the purchase contract for the products, items or services You have purchased or of any other contract with Us through the Service. * To contact You: To contact You by email, telephone calls, SMS, or other equivalent forms of electronic communication, such as a mobile application's push notifications regarding updates or informative communications related to the functionalities, products or contracted services, including the security updates, when necessary or reasonable for their implementation. * To provide You with news, special offers and general information about other goods, services and events which we offer that are similar to those that you have already purchased or enquired about unless You have opted not to receive such information. * To manage Your requests: To attend and manage Your requests to Us. * For business transfers: We may use Your information to evaluate or conduct a merger, divestiture, restructuring, reorganization, dissolution, or other sale or transfer of some or all of Our assets, whether as a going concern or as part of bankruptcy, liquidation, or similar proceeding, in which Personal Data held by Us about our Service users is among the assets transferred. * For other purposes : We may use Your information for other purposes, such as data analysis, identifying usage trends, determining the effectiveness of our promotional campaigns and to evaluate and improve our Service, products, services, marketing and your experience. We may share Your personal information in the following situations: * With Service Providers: We may share Your personal information with Service Providers to monitor and analyze the use of our Service, to contact You. * For business transfers: We may share or transfer Your personal information in connection with, or during negotiations of, any merger, sale of Company assets, financing, or acquisition of all or a portion of Our business to another company. * With Affiliates: We may share Your information with Our affiliates, in which case we will require those affiliates to honor this Privacy Policy. Affiliates include Our parent company and any other subsidiaries, joint venture partners or other companies that We control or that are under common control with Us. * With business partners: We may share Your information with Our business partners to offer You certain products, services or promotions. * With other users: when You share personal information or otherwise interact in the public areas with other users, such information may be viewed by all users and may be publicly distributed outside. * With Your consent : We may disclose Your personal information for any other purpose with Your consent. Retention of Your Personal Data ------------------------------- The Company will retain Your Personal Data only for as long as is necessary for the purposes set out in this Privacy Policy. We will retain and use Your Personal Data to the extent necessary to comply with our legal obligations (for example, if we are required to retain your data to comply with applicable laws), resolve disputes, and enforce our legal agreements and policies. The Company will also retain Usage Data for internal analysis purposes. Usage Data is generally retained for a shorter period of time, except when this data is used to strengthen the security or to improve the functionality of Our Service, or We are legally obligated to retain this data for longer time periods. Transfer of Your Personal Data ------------------------------ Your information, including Personal Data, is processed at the Company's operating offices and in any other places where the parties involved in the processing are located. It means that this information may be transferred to — and maintained on — computers located outside of Your state, province, country or other governmental jurisdiction where the data protection laws may differ than those from Your jurisdiction. Your consent to this Privacy Policy followed by Your submission of such information represents Your agreement to that transfer. The Company will take all steps reasonably necessary to ensure that Your data is treated securely and in accordance with this Privacy Policy and no transfer of Your Personal Data will take place to an organization or a country unless there are adequate controls in place including the security of Your data and other personal information. Disclosure of Your Personal Data -------------------------------- Business Transactions ~~~~~~~~~~~~~~~~~~~~~ If the Company is involved in a merger, acquisition or asset sale, Your Personal Data may be transferred. We will provide notice before Your Personal Data is transferred and becomes subject to a different Privacy Policy. Law enforcement ~~~~~~~~~~~~~~~ Under certain circumstances, the Company may be required to disclose Your Personal Data if required to do so by law or in response to valid requests by public authorities (e.g. a court or a government agency). Other legal requirements ~~~~~~~~~~~~~~~~~~~~~~~~ The Company may disclose Your Personal Data in the good faith belief that such action is necessary to: * Comply with a legal obligation * Protect and defend the rights or property of the Company * Prevent or investigate possible wrongdoing in connection with the Service * Protect the personal safety of Users of the Service or the public * Protect against legal liability Security of Your Personal Data ------------------------------ The security of Your Personal Data is important to Us, but remember that no method of transmission over the Internet, or method of electronic storage is 100% secure. While We strive to use commercially acceptable means to protect Your Personal Data, We cannot guarantee its absolute security. Children's Privacy ================== Our Service does not address anyone under the age of 13. We do not knowingly collect personally identifiable information from anyone under the age of 13. If You are a parent or guardian and You are aware that Your child has provided Us with Personal Data, please contact Us. If We become aware that We have collected Personal Data from anyone under the age of 13 without verification of parental consent, We take steps to remove that information from Our servers. If We need to rely on consent as a legal basis for processing Your information and Your country requires consent from a parent, We may require Your parent's consent before We collect and use that information. Links to Other Websites ======================= Our Service may contain links to other websites that are not operated by Us. If You click on a third party link, You will be directed to that third party's site. We strongly advise You to review the Privacy Policy of every site You visit. We have no control over and assume no responsibility for the content, privacy policies or practices of any third party sites or services. Changes to this Privacy Policy ============================== We may update Our Privacy Policy from time to time. We will notify You of any changes by posting the new Privacy Policy on this page. We will let You know via email and/or a prominent notice on Our Service, prior to the change becoming effective and update the "Last updated" date at the top of this Privacy Policy. You are advised to review this Privacy Policy periodically for any changes. Changes to this Privacy Policy are effective when they are posted on this page. Contact Us ========== If you have any questions about this Privacy Policy, You can contact us: * By email: [email protected] ''', style: TextStyle( fontSize: 10, fontWeight: FontWeight.w300, ), ), ))); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/drawerScreens/notifications.dart
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; class NotificationScreen extends StatelessWidget { const NotificationScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Notifications"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(right: 10), child: Icon( Icons.notifications_active, color: Colors.blueGrey[300], ), ), Text( "No New Notifications", style: TextStyle( color: Colors.blueGrey[300], ), ), ], ), )); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/drawerScreens/help.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'dart:io'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; class HelpScreen extends StatelessWidget { const HelpScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Help Centre"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Image.asset( 'assets/helpwizard.png', width: 250, ), ), Padding( padding: const EdgeInsets.only(top: 20), child: Qa( question: '''Q: Where can I find more info about recycling? ''', answer: '''A: There are articles about recycling in our app. '''), ), Qa( question: '''Q: How come I can't find a waste depot in my area? ''', answer: '''A: Currently WasteWizard++ only supports depot locations located in the Great Toronto Area. The core issue is that all data must be manually gathered for this specific data, and so we have not been able to implement it. Dynamic locations/maps will be implemented in the future through a crowdsourcing data model. '''), Qa( question: '''Q: How do I contact WasteWizard++?''', answer: '''A: If you have any questions you can contact us by sending an email to [email protected]. '''), Qa( question: '''Q: Where can I find more information about WasteWizard++? ''', answer: '''A: Our application is 90% open source. Additional information regarding the application, in addition to our source code can be found on our Github repository. '''), Qa( question: '''Q: Why is recycling important? ''', answer: '''A: You can help our world by simply starting recycling, so why not? The complicated process of sorting your recycling is handled by the city, and now, the process of determining recyclable items is also handled by this application! Recycling will not only help reduce your carbon footprint, but it also helps reduce the need for harvesting raw materials, saves energy, reduces greenhouse gases, prevents pollution, and more. '''), Qa( question: '''Q: How do I use the app? ''', answer: '''A: All you need to do is click the center camera button on the bottom bar! The rest of the application is handled by our in-house Machine Learning engine. All image processing is done on the local machine. '''), Qa( question: '''Q: Will the app steal my personal information? ''', answer: '''A: No, we will not share any of your information to a third party. All user information is encrypted. '''), Qa( question: '''Q: How do I know what garbage they are taking and when garbage trucks are coming? ''', answer: '''A: There is a calendar in our app that displays the disposal schedule for the Peel region. The core issue is that all data must be manually gathered for this specific data, and so we have not been able to implement it. Dynamic calendars will be implemented in the future through a crowdsourcing data model. '''), Center( child: ElevatedButton( child: Text("Source Code + Full Documentation"), onPressed: () async { const url = 'https://github.com/pane2004/myapp'; if (await canLaunch(url)) { await launch( url, forceSafariVC: true, forceWebView: true, enableJavaScript: true, ); } }, ), ), ], ), ), )); } } class Qa extends StatelessWidget { final String question; final String answer; const Qa({ Key? key, required this.question, required this.answer, }) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( question, style: const TextStyle(fontWeight: FontWeight.bold), ), Text(answer), ], ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/drawerScreens/settings.dart
// ignore_for_file: prefer_const_literals_to_create_immutables, prefer_const_constructors import 'package:flutter/material.dart'; import 'package:myapp/services/firestore.dart'; class SettingsScreen extends StatefulWidget { const SettingsScreen({Key? key}) : super(key: key); @override _SettingsScreenState createState() => _SettingsScreenState(); } class _SettingsScreenState extends State<SettingsScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("WasteWizard++ Settings"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Padding( padding: const EdgeInsets.only(top: 30), child: Text("ALERT: All Setting Buttons are irreversible!"), ), ), Padding( padding: const EdgeInsets.all(30), child: ElevatedButton( onPressed: () { FirestoreService().clearScans(); }, style: ButtonStyle( minimumSize: MaterialStateProperty.all(Size(250, 80)), backgroundColor: MaterialStateProperty.all<Color>(Color(0xFF84C879)), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), side: BorderSide(color: const Color(0xFF84C879)))), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.delete_forever, size: 35, ), Text( "Delete Scan History", style: TextStyle(fontSize: 16), ), ], ), )), Padding( padding: const EdgeInsets.all(30), child: ElevatedButton( onPressed: () { FirestoreService().resetCarbon(); }, style: ButtonStyle( minimumSize: MaterialStateProperty.all(Size(250, 80)), backgroundColor: MaterialStateProperty.all<Color>(Color(0xFF84C879)), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), side: BorderSide(color: const Color(0xFF84C879)))), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.restart_alt, size: 35, ), Text( "Reset Carbon Savings", style: TextStyle(fontSize: 16), ), ], ), )), Center( child: Padding( padding: const EdgeInsets.all(30), child: Image.asset( 'assets/logolong.png', width: 400, ), ), ) ], ), ), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/profile/profile.dart
import 'package:flutter/material.dart'; import 'package:myapp/services/auth.dart'; class ProfileScreen extends StatelessWidget { const ProfileScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Profile'), ), body: ElevatedButton( child: const Text('signout'), onPressed: () async { await AuthService().signOut(); Navigator.of(context) .pushNamedAndRemoveUntil('/', (route) => false); }), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/topics.dart
// ignore_for_file: unnecessary_const, prefer_const_constructors import 'dart:io'; import 'dart:typed_data'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/services.dart'; import 'package:image/image.dart' as img; import 'package:path/path.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:myapp/services/firestore.dart'; import 'package:myapp/services/models.dart'; import 'package:myapp/shared/bottom_nav.dart'; import 'package:myapp/shared/loading.dart'; import 'package:myapp/shared/error.dart'; import 'package:myapp/topics/scanHistoryFull.dart'; import 'package:myapp/topics/topic_item.dart'; import 'package:myapp/topics/tool_item.dart'; import 'package:myapp/topics/drawer.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:image_picker/image_picker.dart'; import 'package:tflite_flutter_helper/tflite_flutter_helper.dart'; import 'package:myapp/topics/classifier.dart'; import 'package:myapp/topics/classifier_quant.dart'; final List<String> imgList = [ "assets/cover1.jpg", "assets/cover2.jpg", "assets/cover3.jpg", ]; final List<String> toolList = [ "My Carbon Savings", "Local Waste Depots", "Pickup Schedule", ]; final List<Widget> imageSliders = imgList .map((item) => Builder(builder: (context) { return Container( margin: const EdgeInsets.only(right: 30), child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: InkWell( onTap: () { Navigator.pushNamed(context, '/$item'); }, child: Stack( children: <Widget>[ Image.asset( item, fit: BoxFit.cover, width: 1000.0, height: 800, ), ], ), )), ); })) .toList(); class TopicsScreen extends StatefulWidget { const TopicsScreen({Key? key}) : super(key: key); @override State<TopicsScreen> createState() => _TopicsScreenState(); } class _TopicsScreenState extends State<TopicsScreen> { int _selectedIndex = 0; late Classifier _classifier; File? _image; final picker = ImagePicker(); Image? _imageWidget; img.Image? fox; Category? category; bool isLoading = true; UploadTask? task; late String urlDownload; @override void initState() { super.initState(); _classifier = ClassifierQuant(); } Future getImage() async { final pickedFile = await picker.pickImage( source: ImageSource.camera, imageQuality: 30, ); setState(() { _image = File(pickedFile!.path); _imageWidget = Image.file(_image!); _predict(); }); } void _predict() async { img.Image imageInput = img.decodeImage(_image!.readAsBytesSync())!; var pred = _classifier.predict(imageInput); setState(() { category = pred; }); } Future uploadFile() async { if (_image == null) return; final fileName = basename(_image!.path); final destination = 'files/$fileName'; task = FirestoreService.uploadFile(destination, _image!); if (task == null) return; final snapshot = await task!.whenComplete(() {}); var link = await snapshot.ref.getDownloadURL(); setState(() { urlDownload = link; }); } @override Widget build(BuildContext context) { return FutureBuilder<List<Scan>>( future: FirestoreService().getScans(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var scans = snapshot.data!; final screen = [ MainHome(scans: scans), const ScanHistoryFull(), ]; return Scaffold( backgroundColor: const Color(0xFFF9FCFF), drawer: nameFetch(), body: screen[_selectedIndex], ///Floating Navbar floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: isLoading ? FloatingActionButton( child: const Icon(Icons.camera_alt_rounded), onPressed: () async { setState(() { isLoading = false; }); await getImage(); await uploadFile(); FirestoreService().updateTotal(); await FirestoreService().updateScans( urlDownload.toString(), category!.label.toString()); setState(() { isLoading = true; }); category == null ? Text("Oof") : Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) => TopicScreen( image: _image, output: category!.label, ), ), ); }, backgroundColor: const Color(0xFF84C879), ) : Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, decoration: BoxDecoration( color: Colors.white, ), child: Center(child: CircularProgressIndicator()), ), bottomNavigationBar: BottomAppBar( shape: const AutomaticNotchedShape( RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(25), topRight: Radius.circular(25), ), ), StadiumBorder()), notchMargin: 5, color: Colors.white, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const SizedBox( width: 70.0, ), IconBottomButton( icon: Icons.home, selected: _selectedIndex == 0, onPressed: () { setState(() { _selectedIndex = 0; }); }), const SizedBox( width: 150.0, ), IconBottomButton( icon: Icons.document_scanner, selected: _selectedIndex == 1, onPressed: () { setState(() { _selectedIndex = 1; }); }), const SizedBox( width: 70.0, ), ], ), )); } else { return const Text('No topics in Firestore. Check Database'); } }, ); } FutureBuilder<String> nameFetch() { return FutureBuilder<String>( future: FirestoreService().getName(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var name = snapshot.data!; return TopicDrawer(name: name); } else { return const Text('No topics in Firestore. Check Database'); } }); } } class TopicScreen extends StatelessWidget { final File? image; final String output; const TopicScreen({ Key? key, required this.image, required this.output, }) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: const Color(0xFF84C879), title: Text(output), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: ListView(children: [ Hero( tag: 1, child: AspectRatio( aspectRatio: 1.5, child: Image.file( image!, fit: BoxFit.cover, width: MediaQuery.of(context).size.width, ), ), ), Padding( padding: const EdgeInsets.only(top: 20), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only(right: 10), child: generateIcon(output), ), Text( output, style: const TextStyle( fontSize: 36, fontWeight: FontWeight.bold, ), ), ], ), ), ), Divider( height: 50, ), Padding( padding: const EdgeInsets.only(bottom: 50), child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Padding( padding: EdgeInsets.only(bottom: 15), child: Text( "Before Disposing, Please Consider:", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18, ), ), ), Text("1. Reusing the item"), Text("2. Donating the item."), Text("3. Selling the item."), Text("4. Reflecting on the waste source."), ], ), ), ), ]), ); } generateIcon(String classification) { var icon = classification; switch (icon) { case 'Recycling': return Icon( FontAwesomeIcons.recycle, color: Color(0xFF4188D6), ); case 'Garbage': return Icon( FontAwesomeIcons.trash, color: Color(0xFFFFC92B), ); case 'Compost': return Icon( FontAwesomeIcons.leaf, color: Color(0xFF9ED593), ); case 'Hazardous Waste': return Icon( FontAwesomeIcons.exclamation, color: Colors.red, ); default: return Icon( FontAwesomeIcons.leaf, color: Color(0xFF9ED593), ); } } } class MainHome extends StatelessWidget { const MainHome({ Key? key, required this.scans, }) : super(key: key); final List<Scan> scans; @override Widget build(BuildContext context) { return CustomScrollView( slivers: <Widget>[ const TopBar(), const Tools(), ScanHistory(scans: scans), ], ); } } class ScanHistory extends StatelessWidget { const ScanHistory({ Key? key, required this.scans, }) : super(key: key); final List<Scan> scans; @override Widget build(BuildContext context) { return SliverToBoxAdapter(child: buildHistory()); } FutureBuilder<List<Scan>> buildHistory() { return FutureBuilder<List<Scan>>( future: FirestoreService().getScans(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var name = snapshot.data!; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 25, top: 10), child: Text( "Scan History", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24, ), ), ), GridView.count( mainAxisSpacing: 10, childAspectRatio: 4, shrinkWrap: true, primary: false, padding: const EdgeInsets.all(20), crossAxisCount: 1, children: name .map((scan) => TopicItem( scan: scan, )) .toList(), ), ]); } else { return const Text('No topics in Firestore. Check Database'); } }); } } class TopBar extends StatelessWidget { const TopBar({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return SliverAppBar( centerTitle: true, backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: const BorderRadius.only( bottomLeft: const Radius.circular(50), bottomRight: Radius.circular(50))), snap: false, pinned: true, floating: false, expandedHeight: 240.0, flexibleSpace: FlexibleSpaceBar( centerTitle: true, title: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { var top = constraints.biggest.height; return AnimatedOpacity( duration: const Duration(milliseconds: 300), opacity: 1.0, child: Text(top > 64 && top < 249 ? "" : "WasteWizard++"), ); }, ), background: Container( padding: const EdgeInsets.only(top: 50), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( padding: const EdgeInsets.only(left: 20, bottom: 10), child: const Text( "Recommended Reads", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 24, ), ), ), CarouselSlider( options: CarouselOptions( height: 125, autoPlay: true, viewportFraction: 0.9, enlargeCenterPage: true, ), items: imageSliders, ) ], ), )), ); } } class Tools extends StatelessWidget { const Tools({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return SliverToBoxAdapter( child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 25, top: 10), child: Text( "Tools", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24, ), ), ), GridView.count( shrinkWrap: true, primary: false, padding: const EdgeInsets.only(left: 25, right: 25, top: 15), crossAxisSpacing: 10, crossAxisCount: 3, children: toolList .map((tool) => ToolItem( tool: tool, title: tool, )) .toList(), ) ]), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/scanHistoryFull.dart
import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:myapp/services/firestore.dart'; import 'package:myapp/services/models.dart'; import 'package:myapp/shared/bottom_nav.dart'; import 'package:myapp/shared/error.dart'; import 'package:myapp/shared/loading.dart'; import 'package:myapp/topics/topic_item.dart'; import 'drawer.dart'; class ScanHistoryFull extends StatelessWidget { const ScanHistoryFull({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return FutureBuilder<List<Scan>>( future: FirestoreService().getScans(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const LoadingScreen(); } else if (snapshot.hasError) { return Center( child: ErrorMessage(message: snapshot.error.toString()), ); } else if (snapshot.hasData) { var scans = snapshot.data!; return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: const Color(0xFF84C879), title: const Text('WasteWizard++'), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: SingleChildScrollView(child: ScanHistory(scans: scans)), ); } else { return const Text('No topics in Firestore. Check Database'); } }); } } class ScanHistory extends StatelessWidget { const ScanHistory({ Key? key, required this.scans, }) : super(key: key); final List<Scan> scans; @override Widget build(BuildContext context) { return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 25, top: 10), child: Text( "Scan History", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24, ), ), ), GridView.count( mainAxisSpacing: 10, childAspectRatio: 4, shrinkWrap: true, primary: false, padding: const EdgeInsets.all(20), crossAxisCount: 1, children: scans .map((scan) => TopicItem( scan: scan, )) .toList(), ), ]); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/classifier.dart
import 'dart:math'; import 'package:image/image.dart'; import 'package:collection/collection.dart'; import 'package:tflite_flutter/tflite_flutter.dart'; import 'package:tflite_flutter_helper/tflite_flutter_helper.dart'; abstract class Classifier { late Interpreter interpreter; late InterpreterOptions _interpreterOptions; late List<int> _inputShape; late List<int> _outputShape; late TensorImage _inputImage; late TensorBuffer _outputBuffer; late TfLiteType _inputType; late TfLiteType _outputType; final String _labelsFileName = 'assets/labels.txt'; final int _labelsLength = 4; late var _probabilityProcessor; late List<String> labels; String get modelName; NormalizeOp get preProcessNormalizeOp; NormalizeOp get postProcessNormalizeOp; Classifier({int? numThreads}) { _interpreterOptions = InterpreterOptions(); if (numThreads != null) { _interpreterOptions.threads = numThreads; } loadModel(); loadLabels(); } Future<void> loadModel() async { try { interpreter = await Interpreter.fromAsset(modelName, options: _interpreterOptions); print('Interpreter Created Successfully'); _inputShape = interpreter.getInputTensor(0).shape; _outputShape = interpreter.getOutputTensor(0).shape; _inputType = interpreter.getInputTensor(0).type; _outputType = interpreter.getOutputTensor(0).type; _outputBuffer = TensorBuffer.createFixedSize(_outputShape, _outputType); _probabilityProcessor = TensorProcessorBuilder().add(postProcessNormalizeOp).build(); } catch (e) { print('Unable to create interpreter, Caught Exception: ${e.toString()}'); } } Future<void> loadLabels() async { labels = await FileUtil.loadLabels(_labelsFileName); if (labels.length == _labelsLength) { print('Labels loaded successfully'); } else { print('Unable to load labels'); } } TensorImage _preProcess() { int cropSize = min(_inputImage.height, _inputImage.width); return ImageProcessorBuilder() .add(ResizeWithCropOrPadOp(cropSize, cropSize)) .add(ResizeOp( _inputShape[1], _inputShape[2], ResizeMethod.NEAREST_NEIGHBOUR)) .add(preProcessNormalizeOp) .build() .process(_inputImage); } Category predict(Image image) { final pres = DateTime.now().millisecondsSinceEpoch; _inputImage = TensorImage(_inputType); _inputImage.loadImage(image); _inputImage = _preProcess(); final pre = DateTime.now().millisecondsSinceEpoch - pres; print('Time to load image: $pre ms'); final runs = DateTime.now().millisecondsSinceEpoch; interpreter.run(_inputImage.buffer, _outputBuffer.getBuffer()); final run = DateTime.now().millisecondsSinceEpoch - runs; print('Time to run inference: $run ms'); Map<String, double> labeledProb = TensorLabel.fromList( labels, _probabilityProcessor.process(_outputBuffer)) .getMapWithFloatValue(); final pred = getTopProbability(labeledProb); return Category(pred.key, pred.value); } void close() { interpreter.close(); } } MapEntry<String, double> getTopProbability(Map<String, double> labeledProb) { var pq = PriorityQueue<MapEntry<String, double>>(compare); pq.addAll(labeledProb.entries); return pq.first; } int compare(MapEntry<String, double> e1, MapEntry<String, double> e2) { if (e1.value > e2.value) { return -1; } else if (e1.value == e2.value) { return 0; } else { return 1; } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/classifier_quant.dart
import 'package:myapp/topics/classifier.dart'; import 'package:tflite_flutter_helper/tflite_flutter_helper.dart'; class ClassifierQuant extends Classifier { ClassifierQuant({int numThreads = 1}) : super(numThreads: numThreads); @override String get modelName => 'model.tflite'; @override NormalizeOp get preProcessNormalizeOp => NormalizeOp(0, 1); @override NormalizeOp get postProcessNormalizeOp => NormalizeOp(0, 255); }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/tool_item.dart
import 'package:flutter/material.dart'; class ToolItem extends StatelessWidget { final String tool; final String title; const ToolItem({Key? key, required this.tool, required this.title}) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () { Navigator.pushNamed(context, '/$tool'); }, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( flex: 3, child: SizedBox( child: Image.asset( 'assets/topics/$tool.png', fit: BoxFit.contain, ), ), ), Text(title, style: const TextStyle(fontSize: 16), textAlign: TextAlign.center), ], ), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/drawer.dart
// ignore_for_file: prefer_const_constructors import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:myapp/services/auth.dart'; import 'package:myapp/services/firestore.dart'; import 'package:provider/provider.dart'; import 'package:myapp/quiz/quiz.dart'; import 'package:myapp/services/models.dart'; class TopicDrawer extends StatefulWidget { final String name; const TopicDrawer({Key? key, required this.name}) : super(key: key); @override State<TopicDrawer> createState() => _TopicDrawerState(); } class _TopicDrawerState extends State<TopicDrawer> { late TextEditingController controller; String newName = ''; @override void initState() { super.initState(); controller = TextEditingController(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Drawer( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(top: 30, left: 20), child: Image.asset( 'assets/logolong.png', width: 250, )), Padding( padding: EdgeInsets.only(top: 15, left: 20), child: Row( children: [ Text( widget.name, style: TextStyle( fontWeight: FontWeight.bold, color: Color(0xFF84C879), fontSize: 24, ), ), IconButton( color: Color(0xFF84C879), icon: const Icon(Icons.edit), onPressed: () async { final newName = await openPopup(); if (newName == null || newName.isEmpty) return; setState(() => this.newName = newName); FirestoreService().changeName(newName); }, ) ], ), ), Divider( indent: 20, endIndent: 20, thickness: 1.5, height: 60, ), SideBar( title: "Statistics", icon: Icons.query_stats, page: '/statistics', ), SideBar( title: "Notifications", icon: Icons.notifications_active, page: '/noti', ), SideBar( title: "History", icon: Icons.history, page: '/scanHistory', ), Divider( indent: 20, endIndent: 20, thickness: 1.5, height: 60, ), SideBar( title: "Settings", icon: Icons.settings, page: '/settings', ), SideBar( title: "Privacy Policy", icon: Icons.privacy_tip, page: '/privacy', ), SideBar( title: "Help Centre", icon: Icons.help, page: '/help', ), InkWell( onTap: () async { await AuthService().signOut(); Navigator.of(context) .pushNamedAndRemoveUntil('/', (route) => false); }, child: Padding( padding: const EdgeInsets.only(left: 20), child: ListTile( title: Text("Sign Out"), leading: Icon(Icons.logout), iconColor: const Color(0xFF84C879), ), ), ) ], ), ); Future<String?> openPopup() => showDialog<String>( context: context, builder: (context) => AlertDialog( title: Text( "Change Display Name", style: TextStyle( fontWeight: FontWeight.w800, fontSize: 18, ), ), content: TextField( cursorColor: const Color(0xFF84C879), autofocus: true, controller: controller, decoration: InputDecoration( hintText: "Enter your name", enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: const Color(0xFF84C879)), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: const Color(0xFF84C879)), ), border: UnderlineInputBorder( borderSide: BorderSide(color: const Color(0xFF84C879)), ), ), ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(controller.text); Navigator.pushNamed(context, '/'); }, child: Text( "Confirm", style: TextStyle( color: const Color(0xFF84C879), fontWeight: FontWeight.bold, fontSize: 18, ), ), style: TextButton.styleFrom(splashFactory: NoSplash.splashFactory), ) ], shape: RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(15), ), ), )); } class SideBar extends StatelessWidget { final String title; final IconData icon; final String page; const SideBar({ Key? key, required this.title, required this.icon, required this.page, }) : super(key: key); @override Widget build(BuildContext context) { return InkWell( onTap: () { Navigator.pushNamed(context, page); }, child: Padding( padding: const EdgeInsets.only(left: 20), child: ListTile( title: Text(title), leading: Icon(icon), iconColor: const Color(0xFF84C879), ), ), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/topics/topic_item.dart
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:myapp/services/models.dart'; class TopicItem extends StatelessWidget { final Scan scan; const TopicItem({Key? key, required this.scan}) : super(key: key); @override Widget build(BuildContext context) { return Hero( tag: scan.img, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), ), child: InkWell( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) => TopicScreen(scan: scan), ), ); }, child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(5.0), child: SizedBox( height: 75, width: 75, child: AspectRatio( aspectRatio: 1, child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.network( scan.img, fit: BoxFit.cover, ), ), ), ), ), Padding( padding: const EdgeInsets.only(left: 15), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( scan.classification, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), overflow: TextOverflow.fade, softWrap: false, ), Text( scan.time, style: const TextStyle(color: Color(0xFFC5D0DB)), overflow: TextOverflow.fade, softWrap: false, ), ], ), ), const Spacer(), Padding( padding: const EdgeInsets.only(right: 20), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipOval( child: Material( color: generateColour(scan.classification), child: SizedBox( width: 60, height: 60, child: generateIcon(scan.classification)), ), ), ], ), ) ], ), ), ), ); } generateIcon(String classification) { var icon = classification; switch (icon) { case 'Recycling': return Icon( FontAwesomeIcons.recycle, color: Color(0xFF4188D6), ); case 'Garbage': return Icon( FontAwesomeIcons.trash, color: Color(0xFFFFC92B), ); case 'Compost': return Icon( FontAwesomeIcons.leaf, color: Color(0xFF9ED593), ); case 'Hazardous Waste': return Icon( FontAwesomeIcons.exclamation, color: Colors.red, ); default: return Icon( FontAwesomeIcons.leaf, color: Color(0xFF9ED593), ); } } generateColour(String classification) { var icon = classification; switch (icon) { case 'Recycling': return Color(0xFFEFF7FF); case 'Garbage': return Color(0xFFFFF8E3); case 'Compost': return Color(0xFFECFBDF); case 'Hazardous Waste': return Colors.red[100]; default: return Color(0xFFECFBDF); } } } class TopicScreen extends StatelessWidget { final Scan scan; const TopicScreen({Key? key, required this.scan}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: const Color(0xFF84C879), title: Text(scan.classification), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: ListView(children: [ Hero( tag: scan.img, child: Image.network(scan.img, width: MediaQuery.of(context).size.width), ), Padding( padding: const EdgeInsets.only(top: 20), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only(right: 10), child: generateIcon(scan.classification), ), Text( scan.classification, style: const TextStyle( fontSize: 36, fontWeight: FontWeight.bold, ), ), ], ), ), ), Divider( height: 50, ), Padding( padding: const EdgeInsets.only(bottom: 50), child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Padding( padding: EdgeInsets.only(bottom: 15), child: Text( "Before Disposing, Please Consider:", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18, ), ), ), Text("1. Reusing the item"), Text("2. Donating the item."), Text("3. Selling the item."), Text("4. Reflecting on the waste source."), ], ), ), ), ]), ); } generateIcon(String classification) { var icon = classification; switch (icon) { case 'Recycling': return Icon( FontAwesomeIcons.recycle, color: Color(0xFF4188D6), ); case 'Garbage': return Icon( FontAwesomeIcons.trash, color: Color(0xFFFFC92B), ); case 'Compost': return Icon( FontAwesomeIcons.leaf, color: Color(0xFF9ED593), ); case 'Hazardous Waste': return Icon( FontAwesomeIcons.exclamation, color: Colors.red, ); default: return Icon( FontAwesomeIcons.leaf, color: Color(0xFF9ED593), ); } } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/about/about.dart
import 'package:flutter/material.dart'; class AboutScreen extends StatelessWidget { const AboutScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/home/home.dart
import 'package:flutter/material.dart'; import 'package:myapp/shared/bottom_nav.dart'; import 'package:myapp/login/login.dart'; import 'package:myapp/topics/topics.dart'; import 'package:myapp/services/auth.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return StreamBuilder( stream: AuthService().userStream, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Text('loading'); } else if (snapshot.hasError) { return const Center( child: Text('error'), ); } else if (snapshot.hasData) { return const TopicsScreen(); } else { return const LoginScreen(); } }, ); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/articles/article1.dart
import 'package:flutter/material.dart'; class Article1 extends StatelessWidget { const Article1({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Articles"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(top: 25), child: Center( child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: Image.asset( 'assets/cover1.jpg', width: 400, ), ), ), ), const Padding( padding: EdgeInsets.only(top: 25), child: Text( '''As the strike continues, it delays in the collection of garbage and organics, while recycling and yard waste will not be picked up during the labour disruption. The Region of Peel says residents affected by the strike should continue to put out their garbage on their scheduled day, but it may not be collected. This strike involved workers at Emterra Environmental, one of the region's waste collection contractors. Author: Andy Chen''', style: TextStyle(fontSize: 20), ), ) ])))); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/articles/article3.dart
import 'package:flutter/material.dart'; class Article3 extends StatelessWidget { const Article3({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Articles"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(top: 25), child: Center( child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: Image.asset( 'assets/cover3.jpg', width: 400, ), ), ), ), const Padding( padding: EdgeInsets.only(top: 25), child: Text( '''The benefit of compost, it can save resources, there are valuable resources out of the landfill that it could save and reduce landfill wastes. It also could reduce GreenHouse gases. It can help to save the environment. The benefit of garbage, is that it could save time to deal with garbage, and it has less cost than other methods. It has less trash than others. Author: Andy Chen''', style: TextStyle(fontSize: 20), ), ) ])))); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/articles/article2.dart
import 'package:flutter/material.dart'; class Article2 extends StatelessWidget { const Article2({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Articles"), backgroundColor: const Color(0xFF84C879), shape: const ContinuousRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(50), bottomRight: Radius.circular(50))), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Padding( padding: const EdgeInsets.all(15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(top: 25), child: Center( child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: Image.asset( 'assets/cover2.jpg', width: 400, ), ), ), ), const Padding( padding: EdgeInsets.only(top: 25), child: Text( '''Benefit of recycling; Recycling diverts waste from landfill: It stop material from being sent to landfill each year, that reduces our conserves land space, Recycling conserves resource:by recycling products made using natural resources, we reduce the load on our environment, Recycling waves energy: To use recycled printed paper and packaging as raw materials, it conserves both transportation and processing energy. Author: Andy Chen''', style: TextStyle(fontSize: 20), ), ) ])))); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/services/auth.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'dart:convert'; import 'dart:math'; import 'package:crypto/crypto.dart'; import 'package:sign_in_with_apple/sign_in_with_apple.dart'; import 'package:myapp/services/firestore.dart'; class AuthService { final userStream = FirebaseAuth.instance.authStateChanges(); final user = FirebaseAuth.instance.currentUser; final firestoreInstance = FirebaseFirestore.instance; ///Anonymous Firebase Login Future<void> anonLogin() async { DateTime today = DateTime.now(); String date = today.toString().substring(0, 10); try { await FirebaseAuth.instance.signInAnonymously(); } on FirebaseAuthException catch (e) { //Handle Error } finally { var newFirebaseUser = FirebaseAuth.instance.currentUser; FirebaseFirestore.instance .collection('users') .doc(newFirebaseUser?.uid) .get() .then((DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists) { } else { firestoreInstance.collection("users").doc(newFirebaseUser?.uid).set({ "displayName": "Guest User", "carbon": 0, "scanCount": 0, "joinDate": date, }).then((_) { firestoreInstance .collection('users') .doc(newFirebaseUser?.uid) .collection('scans') .doc('999999999999999999999999') .set({ "img": "https://firebasestorage.googleapis.com/v0/b/projecttest-f77b1.appspot.com/o/icon%20(1).png?alt=media&token=4c6feb3d-a2d2-4b05-8326-cc013a6544f7", "classification": "My First Scan", "time": date, }); }); } }); } } ///Firebase Logout Future<void> signOut() async { await FirebaseAuth.instance.signOut(); } ///Google Firebase Login Future<void> googleLogin() async { try { final googleUser = await GoogleSignIn().signIn(); if (googleUser == null) return; final googleAuth = await googleUser.authentication; final authCredential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); await FirebaseAuth.instance.signInWithCredential(authCredential); } on FirebaseAuthException catch (e) { //Handle Error } finally { var newFirebaseUser = FirebaseAuth.instance.currentUser; FirebaseFirestore.instance .collection('users') .doc(newFirebaseUser?.uid) .get() .then((DocumentSnapshot documentSnapshot) { if (documentSnapshot.exists) { } else { firestoreInstance.collection("users").doc(newFirebaseUser?.uid).set({ "displayName": "Guest User", "carbon": 0, "scanCount": 0, "Location": "Greater Toronto Area" }); } }); } } ///Apple Firebase Login String generateNonce([int length = 32]) { const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._'; final random = Random.secure(); return List.generate(length, (_) => charset[random.nextInt(charset.length)]) .join(); } /// Returns the sha256 hash of [input] in hex notation. String sha256ofString(String input) { final bytes = utf8.encode(input); final digest = sha256.convert(bytes); return digest.toString(); } Future<UserCredential> signInWithApple() async { // To prevent replay attacks with the credential returned from Apple, we // include a nonce in the credential request. When signing in with // Firebase, the nonce in the id token returned by Apple, is expected to // match the sha256 hash of `rawNonce`. final rawNonce = generateNonce(); final nonce = sha256ofString(rawNonce); // Request credential for the currently signed in Apple account. final appleCredential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], nonce: nonce, ); // Create an `OAuthCredential` from the credential returned by Apple. final oauthCredential = OAuthProvider("apple.com").credential( idToken: appleCredential.identityToken, rawNonce: rawNonce, ); // Sign in the user with Firebase. If the nonce we generated earlier does // not match the nonce in `appleCredential.identityToken`, sign in will fail. return await FirebaseAuth.instance.signInWithCredential(oauthCredential); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/services/firestore.dart
import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:rxdart/rxdart.dart'; import 'package:myapp/services/auth.dart'; import 'package:myapp/services/models.dart'; import 'package:firebase_storage/firebase_storage.dart'; class FirestoreService { final FirebaseFirestore _db = FirebaseFirestore.instance; final firebaseUser = FirebaseAuth.instance.currentUser; ///Reads name from user document Future<String> getName() async { var ref = _db.collection('users').doc(firebaseUser!.uid); var snapshot = await ref.get(); return snapshot.data()!["displayName"]; } ///Reads name from user document Future<double> getCarbon() async { var ref = _db.collection('users').doc(firebaseUser!.uid); var snapshot = await ref.get(); return snapshot.data()!["carbon"]; } ///Reads scans from user document Future<String> scanCount() async { var ref = _db.collection('users').doc(firebaseUser!.uid); var snapshot = await ref.get(); return snapshot.data()!["scanCount"].toString(); } ///Reads joinDate from user document Future<String> joinDate() async { var ref = _db.collection('users').doc(firebaseUser!.uid); var snapshot = await ref.get(); return snapshot.data()!["joinDate"]; } ///Deletes all scan documents from user subcollection Future<void> clearScans() async { var snapshots = await _db .collection('users') .doc(firebaseUser!.uid) .collection('scans') .get(); for (var doc in snapshots.docs) { await doc.reference.delete(); } } ///Updates Users Display Name changeName(String name) { _db .collection('users') .doc(firebaseUser!.uid) .update({"displayName": name}); } ///Updates Users Carbon Amount resetCarbon() { _db.collection('users').doc(firebaseUser!.uid).update({"carbon": 0}); } ///Adds user totals for scans updateTotal() { _db.collection('users').doc(firebaseUser!.uid).update({ "carbon": FieldValue.increment(0.35), "scanCount": FieldValue.increment(1), }); } ///Updates Users Scans Name updateScans(String img, String classification) async { DateTime today = DateTime.now(); String date = today.toString().substring(0, 10); var countSnapshot = await _db.collection('users').doc(firebaseUser!.uid).get(); _db .collection('users') .doc(firebaseUser!.uid) .collection('scans') .doc(countSnapshot.data()!["scanCount"].toString()) .set({ "img": img, "classification": classification, "time": date, }); } static UploadTask? uploadFile(String destination, File file) { try { final ref = FirebaseStorage.instance.ref(destination); return ref.putFile(file); } on FirebaseException catch (e) { return null; } } /// Reads all documments from the topics collection Future<List<Topic>> getTopics() async { var ref = _db.collection('topics'); var snapshot = await ref.get(); var data = snapshot.docs.map((s) => s.data()); var topics = data.map((d) => Topic.fromJson(d)); return topics.toList(); } /// Reads all documments from the topics collection Future<List<Scan>> getScans() async { var ref = _db.collection('users').doc(firebaseUser!.uid).collection('scans'); var snapshot = await ref.get(); var data = snapshot.docs.map((s) => s.data()); var scans = data.map((d) => Scan.fromJson(d)); return scans.toList(); } /// Retrieves a single quiz document Future<Quiz> getQuiz(String quizId) async { var ref = _db.collection('quizzes').doc(quizId); var snapshot = await ref.get(); return Quiz.fromJson(snapshot.data() ?? {}); } /// Listens to current user's report document in Firestore Stream<Report> streamReport() { return AuthService().userStream.switchMap((user) { if (user != null) { var ref = _db.collection('reports').doc(user.uid); return ref.snapshots().map((doc) => Report.fromJson(doc.data()!)); } else { return Stream.fromIterable([Report()]); } }); } /// Updates the current user's report document after completing quiz Future<void> updateUserReport(Quiz quiz) { var user = AuthService().user!; var ref = _db.collection('reports').doc(user.uid); var data = { 'total': FieldValue.increment(1), 'topics': { quiz.topic: FieldValue.arrayUnion([quiz.id]) } }; return ref.set(data, SetOptions(merge: true)); } }
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/services/models.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'models.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Option _$OptionFromJson(Map<String, dynamic> json) => Option( value: json['value'] as String? ?? '', detail: json['detail'] as String? ?? '', correct: json['correct'] as bool? ?? false, ); Map<String, dynamic> _$OptionToJson(Option instance) => <String, dynamic>{ 'value': instance.value, 'detail': instance.detail, 'correct': instance.correct, }; Question _$QuestionFromJson(Map<String, dynamic> json) => Question( options: (json['options'] as List<dynamic>?) ?.map((e) => Option.fromJson(e as Map<String, dynamic>)) .toList() ?? const [], text: json['text'] as String? ?? '', ); Map<String, dynamic> _$QuestionToJson(Question instance) => <String, dynamic>{ 'text': instance.text, 'options': instance.options, }; Quiz _$QuizFromJson(Map<String, dynamic> json) => Quiz( title: json['title'] as String? ?? '', video: json['video'] as String? ?? '', description: json['description'] as String? ?? '', id: json['id'] as String? ?? '', topic: json['topic'] as String? ?? '', questions: (json['questions'] as List<dynamic>?) ?.map((e) => Question.fromJson(e as Map<String, dynamic>)) .toList() ?? const [], ); Map<String, dynamic> _$QuizToJson(Quiz instance) => <String, dynamic>{ 'id': instance.id, 'title': instance.title, 'description': instance.description, 'video': instance.video, 'topic': instance.topic, 'questions': instance.questions, }; Topic _$TopicFromJson(Map<String, dynamic> json) => Topic( id: json['id'] as String? ?? '', title: json['title'] as String? ?? '', description: json['description'] as String? ?? '', img: json['img'] as String? ?? 'default.png', quizzes: (json['quizzes'] as List<dynamic>?) ?.map((e) => Quiz.fromJson(e as Map<String, dynamic>)) .toList() ?? const [], ); Map<String, dynamic> _$TopicToJson(Topic instance) => <String, dynamic>{ 'id': instance.id, 'title': instance.title, 'description': instance.description, 'img': instance.img, 'quizzes': instance.quizzes, }; Scan _$ScanFromJson(Map<String, dynamic> json) => Scan( classification: json['classification'] as String? ?? '', time: json['time'] as String? ?? '', img: json['img'] as String? ?? 'https://stickerly.pstatic.net/sticker_pack/13279e882d3a25af/KXTZ1R/2/39a69c85-b054-4d3c-9cdb-cf450cea8597-023.png', ); Map<String, dynamic> _$ScanToJson(Scan instance) => <String, dynamic>{ 'classification': instance.classification, 'time': instance.time, 'img': instance.img, }; Report _$ReportFromJson(Map<String, dynamic> json) => Report( uid: json['uid'] as String? ?? '', topics: json['topics'] as Map<String, dynamic>? ?? const {}, total: json['total'] as int? ?? 0, ); Map<String, dynamic> _$ReportToJson(Report instance) => <String, dynamic>{ 'uid': instance.uid, 'total': instance.total, 'topics': instance.topics, };
0
mirrored_repositories/wastewizardpp/lib
mirrored_repositories/wastewizardpp/lib/services/models.dart
import 'package:json_annotation/json_annotation.dart'; part 'models.g.dart'; @JsonSerializable() class Option { String value; String detail; bool correct; Option({this.value = '', this.detail = '', this.correct = false}); factory Option.fromJson(Map<String, dynamic> json) => _$OptionFromJson(json); Map<String, dynamic> toJson() => _$OptionToJson(this); } @JsonSerializable() class Question { String text; List<Option> options; Question({this.options = const [], this.text = ''}); factory Question.fromJson(Map<String, dynamic> json) => _$QuestionFromJson(json); Map<String, dynamic> toJson() => _$QuestionToJson(this); } @JsonSerializable() class Quiz { String id; String title; String description; String video; String topic; List<Question> questions; Quiz( {this.title = '', this.video = '', this.description = '', this.id = '', this.topic = '', this.questions = const []}); factory Quiz.fromJson(Map<String, dynamic> json) => _$QuizFromJson(json); Map<String, dynamic> toJson() => _$QuizToJson(this); } @JsonSerializable() class Topic { late final String id; final String title; final String description; final String img; final List<Quiz> quizzes; Topic( {this.id = '', this.title = '', this.description = '', this.img = 'default.png', this.quizzes = const []}); factory Topic.fromJson(Map<String, dynamic> json) => _$TopicFromJson(json); Map<String, dynamic> toJson() => _$TopicToJson(this); } @JsonSerializable() class Scan { final String classification; final String time; final String img; Scan({ this.classification = '', this.time = '', this.img = 'https://stickerly.pstatic.net/sticker_pack/13279e882d3a25af/KXTZ1R/2/39a69c85-b054-4d3c-9cdb-cf450cea8597-023.png', }); factory Scan.fromJson(Map<String, dynamic> json) => _$ScanFromJson(json); Map<String, dynamic> toJson() => _$ScanToJson(this); } @JsonSerializable() class Report { String uid; int total; Map topics; Report({this.uid = '', this.topics = const {}, this.total = 0}); factory Report.fromJson(Map<String, dynamic> json) => _$ReportFromJson(json); Map<String, dynamic> toJson() => _$ReportToJson(this); }
0
mirrored_repositories/wastewizardpp
mirrored_repositories/wastewizardpp/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:myapp/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(App()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/crypto-mobile-app-UI-
mirrored_repositories/crypto-mobile-app-UI-/lib/main.dart
import 'package:crypto_wallet/view/home_screen_view.dart'; import 'package:crypto_wallet/view_model/account_screen_view_model.dart'; import 'package:crypto_wallet/view_model/login_screen__view_model.dart'; import 'package:crypto_wallet/view_model/registration_screen_view_model.dart'; import 'package:crypto_wallet/utils/util_logic.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider( create: (context) => RegistrationScreenViewModel(), ), ChangeNotifierProvider( create: (context) => LoginScreenViewModel(), ), ChangeNotifierProvider( create: (context) => AccountScreenViewModel(), ), ChangeNotifierProvider( create: (context) => UtilLogic(), ), ], child: MaterialApp( debugShowCheckedModeBanner: false, // title: 'Flutter Demo', theme: ThemeData.light(), home: const HomeScreenview(), ), ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view/registration_screen_view.dart
import 'package:crypto_wallet/widgets/custom_button.dart'; import 'package:crypto_wallet/widgets/custom_textform_field.dart'; import 'package:flutter/material.dart'; class RegisrationScreenView extends StatefulWidget { const RegisrationScreenView({ Key? key, }) : super(key: key); @override State<RegisrationScreenView> createState() => _RegisrationScreenViewState(); } class _RegisrationScreenViewState extends State<RegisrationScreenView> { final TextEditingController _userName = TextEditingController(); final TextEditingController _password = TextEditingController(); final TextEditingController _bio = TextEditingController(); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Text( "Let us Dive Together..", style: TextStyle(color: Color(0xffAFB4C0)), ), const Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text( "Weclome to Crypto Graphic World...", style: TextStyle(color: Color(0xffAFB4C0)), ), ), CustomTextFormField( controller: _userName, title: "User name", titleStyle: const TextStyle(color: Color(0xffFFFFFF), fontSize: 12), ), Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: CustomTextFormField( controller: _bio, title: "Bio", titleStyle: const TextStyle(color: Color(0xffFFFFFF), fontSize: 12), ), ), const Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text( "Create Password", style: TextStyle(color: Color(0xffFFFFFF)), ), ), const Text( "This password will unlock your private wallet only on this service", style: TextStyle(color: Color(0xffAFB4C0)), ), Padding( padding: const EdgeInsets.only(top: 8.0, bottom: 4.0), child: CustomTextFormField( controller: _password, title: "Password", isPassword: true, titleStyle: const TextStyle(color: Color(0xffFFFFFF), fontSize: 12), ), ), const Text( "Must be at least 8 characters", style: TextStyle(color: Color(0xffAFB4C0), fontSize: 12), ), const Spacer(), CustomButton( buttonName: "Sign-Up", onPressed: () { // wait for the view model }, ) ], ), ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view/login_screen_view.dart
import 'package:crypto_wallet/view/account_screen_view.dart'; import 'package:crypto_wallet/widgets/custom_button.dart'; import 'package:crypto_wallet/widgets/custom_textform_field.dart'; import 'package:flutter/material.dart'; class LoginScreenView extends StatefulWidget { const LoginScreenView({ Key? key, }) : super(key: key); @override State<LoginScreenView> createState() => _LoginScreenViewState(); } class _LoginScreenViewState extends State<LoginScreenView> { final TextEditingController _userName = TextEditingController(); final TextEditingController _password = TextEditingController(); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Padding( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset( "assets/imgs/coins.png", height: size.height * 0.25, width: size.width * 1, ), const Text( "Let us Dive Together..", style: TextStyle(color: Color(0xffAFB4C0)), ), const Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text( "Weclome to Crypto Graphic World...", style: TextStyle(color: Color(0xffAFB4C0)), ), ), CustomTextFormField( controller: _userName, title: "User name", titleStyle: const TextStyle(color: Color(0xffFFFFFF), fontSize: 12), ), Padding( padding: const EdgeInsets.only(top: 8.0, bottom: 4.0), child: CustomTextFormField( controller: _password, title: "Password", isPassword: true, titleStyle: const TextStyle(color: Color(0xffFFFFFF), fontSize: 12), ), ), const Text( "Must be at least 8 characters", style: TextStyle(color: Color(0xffAFB4C0), fontSize: 12), ), // ], // ) const Spacer(), CustomButton( buttonName: "Login", onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const AccountScreenView(), )); }, ) ], ), ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view/account_screen_view.dart
import 'package:crypto_wallet/model/currency_model.dart'; import 'package:crypto_wallet/model/transactions_model.dart'; import 'package:crypto_wallet/view_model/account_screen_view_model.dart'; import 'package:crypto_wallet/widgets/custom_button.dart'; import 'package:crypto_wallet/widgets/custom_textform_field.dart'; import 'package:crypto_wallet/widgets/gradient_container.dart'; import 'package:crypto_wallet/widgets/indicator.dart'; import 'package:crypto_wallet/widgets/loading_indicator.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:provider/provider.dart'; class AccountScreenView extends StatefulWidget { const AccountScreenView({Key? key}) : super(key: key); @override State<AccountScreenView> createState() => _AccountScreenViewState(); } List<String> options = ["option 1", "option 2"]; class _AccountScreenViewState extends State<AccountScreenView> { String currentOption = options[0]; @override Widget build(BuildContext context) { final List<Curreny> _currencies = [ Curreny( coinColor: const Color(0xff4B70FF).withOpacity(0.6), lineSource: "eth_line", title: "Ethereum", shortCut: "ETH", logo: "eth_logo", value: "6780", increment: "10.56"), Curreny( coinColor: const Color(0xffBE1AF7).withOpacity(0.4), lineSource: "btc_line", title: "Bitcoin", logo: "btc_logo", shortCut: "BTC", value: "6780", increment: "10.56"), Curreny( coinColor: const Color(0xff00F4C8).withOpacity(0.4), lineSource: "eth_line", title: "Ethereum", shortCut: "ETH", logo: "eth_logo", value: "6780", increment: "10.56"), ]; final List<TransactinosModel> _transactionsList = [ TransactinosModel( destionationAddress: "7x8348urijkj3878392", name: "Ahmed", value: "0.05", type: "eth"), TransactinosModel( destionationAddress: "8x094059ijkj3878392", name: "Khalid", value: "0.045", type: "btc"), TransactinosModel( destionationAddress: "92wjodkrijkj3878392", name: "Taha", value: "4.0345", type: "eth"), TransactinosModel( destionationAddress: "83jedkjmijkj3878392", name: "Yonius", value: "0.745", type: "btc"), TransactinosModel( destionationAddress: "1x8348urijkj3878392", name: "Samar", value: "0.1345", type: "eth"), TransactinosModel( destionationAddress: "2x8348urijkj3878392", name: "Mona", value: "1.0345", type: "btc"), ]; return SafeArea( child: Scaffold( backgroundColor: const Color(0xff081534), body: Padding( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Image.asset("assets/imgs/profile.png"), IconButton( onPressed: () {}, icon: const Icon( Icons.notification_important_outlined, color: Colors.white38, )) ], ), const Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text( "Profile Balance", style: TextStyle(color: Color(0xffAFB4C0)), ), ), Padding( padding: const EdgeInsets.only(bottom: 8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: const [ Text( "0.0456788 ETH", style: TextStyle(color: Color(0xffFFFFFF), fontSize: 18), ), Indicator(), ], ), ), const Padding( padding: EdgeInsets.only(bottom: 8.0), child: Text( "My Portfolio", style: TextStyle(color: Color(0xffAFB4C0)), ), ), Expanded( flex: 1, child: ListView.separated( itemCount: _currencies.length, itemBuilder: (context, index) => GradientContainer(model: _currencies[index]), separatorBuilder: (context, index) => const SizedBox( width: 10, ), scrollDirection: Axis.horizontal, padding: const EdgeInsets.symmetric(horizontal: 4.0), ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text( "Last Transactions", style: TextStyle(color: Color(0xffFFFFFF)), ), IconButton( onPressed: () { showDialog( context: context, builder: (context) => _buildTransferDialog()); }, icon: const Icon( Icons.add, color: Color(0xffFFFFFF), )) ], ), ), Expanded( flex: 2, child: ListView.separated( itemCount: _transactionsList.length, itemBuilder: (context, index) => _buildTransactionsList(_transactionsList[index]), separatorBuilder: (context, index) => const Divider(), )), ], ), ), )); } Widget _buildTransferDialog() { final size = MediaQuery.of(context).size; final _destuinationAddress = TextEditingController(); final _value = TextEditingController(); return StatefulBuilder(builder: (context, setState) { // return Dialog( backgroundColor: Colors.transparent, child: Container( width: size.width * 0.5, height: size.height * 0.6, padding: const EdgeInsets.all(12), decoration: BoxDecoration( gradient: LinearGradient( colors: [ const Color(0xffBE1AF7), const Color(0xff4B70FF).withOpacity(0.9), ], begin: Alignment.topRight, end: Alignment.bottomLeft, ), borderRadius: BorderRadius.circular(12), color: const Color(0xffFFFFFF)), child: Consumer<AccountScreenViewModel>( builder: (context, accountViewModel, child) => accountViewModel.isLoading ? const LoadingWidget() : Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text( "Making Transaction", style: TextStyle(color: Color(0xffFFFFFF)), ), IconButton( onPressed: () => Navigator.pop(context), icon: const Icon( Icons.close, color: Color(0xffFFFFFF), )) ], ), const Divider( color: Color(0xffFFFFFF), ), CustomTextFormField( controller: _destuinationAddress, title: "Destionation", titleStyle: const TextStyle( color: Color(0xffAFB4C0), ), ), CustomTextFormField( controller: _value, title: "Value", titleStyle: const TextStyle( color: Color(0xffAFB4C0), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Radio( value: options[0], activeColor: const Color(0xff4B70FF), groupValue: currentOption, onChanged: (_val) { setState(() { currentOption = _val.toString(); }); }), const Text( "ETH", style: TextStyle(color: Color(0xffFFFFFF)), ), const Spacer(), Radio( value: options[1], activeColor: const Color(0xffBE1AF7), groupValue: currentOption, onChanged: (_val) { setState(() { currentOption = _val.toString(); }); }), const Text("BTC", style: TextStyle(color: Color(0xffFFFFFF))) ], ), CustomButton( buttonName: "Transfer", onPressed: () { accountViewModel.changeLoading(); print(accountViewModel.isLoading); }, ) ], ), ), ), ); }); } Widget _buildTransactionsList(TransactinosModel model) => Padding( padding: const EdgeInsets.all(8.0), child: Material( elevation: 3, color: const Color(0xff081534), child: Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Text( "Currency Type :", style: TextStyle(color: Color(0xffAFB4C0)), ), Text("User ", style: TextStyle(color: Color(0xffAFB4C0))), Text("Value ", style: TextStyle(color: Color(0xffAFB4C0))), ], ), Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text(model.type, style: const TextStyle(color: Color(0xffFFFFFF))), Text(model.name, style: const TextStyle(color: Color(0xffFFFFFF))), Text(model.value, style: const TextStyle(color: Color(0xffFFFFFF))), ], ), const Spacer(), SvgPicture.asset("assets/icons/${model.type}_logo.svg") ], ), ), ); }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view/main_screen_view.dart
import 'package:crypto_wallet/view/login_screen_view.dart'; import 'package:crypto_wallet/view/registration_screen_view.dart'; import 'package:flutter/material.dart'; class MainScreenView extends StatefulWidget { const MainScreenView({Key? key}) : super(key: key); @override State<MainScreenView> createState() => _MainScreenViewState(); } class _MainScreenViewState extends State<MainScreenView> { @override Widget build(BuildContext context) { return SafeArea( child: DefaultTabController( length: 2, child: Scaffold( backgroundColor: const Color(0xff081534).withOpacity(0.87), body: Column( children: const [ TabBar(tabs: [ Tab( child: Text("Sign-Up"), ), Tab( child: Text("Login"), ) ]), Expanded( child: TabBarView(children: [ RegisrationScreenView(), LoginScreenView(), ]), ) ], ), ))); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view/home_screen_view.dart
import 'package:crypto_wallet/view/main_screen_view.dart'; import 'package:crypto_wallet/widgets/custom_button.dart'; import 'package:flutter/material.dart'; class HomeScreenview extends StatefulWidget { const HomeScreenview({ Key? key, }) : super(key: key); @override State<HomeScreenview> createState() => _HomeScreenviewState(); } class _HomeScreenviewState extends State<HomeScreenview> { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return SafeArea( child: Scaffold( backgroundColor: const Color(0xff081534).withOpacity(0.87), body: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Image.asset( "assets/imgs/splash.png", height: size.height * 0.5, width: size.width * 1, ), const Padding( padding: EdgeInsets.all(12.0), child: Text( "Your Personal Crypto Wallet", style: TextStyle(color: Color(0xffFFFFFF), fontSize: 32), ), ), const Padding( padding: EdgeInsets.all(12.0), child: Text( "Its Secured By Crypto Graphic Technics and Hash Alogarithm", style: TextStyle( color: Color.fromARGB(255, 233, 225, 225), fontSize: 16), ), ), const SizedBox( height: 40, ), CustomButton( buttonName: "Get Started", onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const MainScreenView(), )); }, icon: const Icon( Icons.keyboard_arrow_right_outlined, color: Colors.black, ), ) ], ), )); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/widgets/custom_button.dart
import 'package:flutter/material.dart'; class CustomButton extends StatefulWidget { const CustomButton( {Key? key, required this.buttonName, this.icon, this.onPressed}) : super(key: key); final Widget? icon; final String buttonName; final Function()? onPressed; @override State<CustomButton> createState() => _CustomButtonState(); } class _CustomButtonState extends State<CustomButton> { @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(12.0), child: Container( padding: const EdgeInsets.all(4.0), decoration: BoxDecoration( color: const Color(0xff00F4C8), borderRadius: BorderRadius.circular(12)), child: TextButton( onPressed: widget.onPressed, child: widget.icon == null ? Center( child: Text( widget.buttonName, style: const TextStyle(color: Color(0xff000000)), ), ) : Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( widget.buttonName, style: const TextStyle(color: Color(0xff000000)), ), widget.icon! ], ), ), ), ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/widgets/gradient_container.dart
import 'package:crypto_wallet/model/currency_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class GradientContainer extends StatefulWidget { const GradientContainer({ Key? key, required this.model, }) : super(key: key); final Curreny model; @override State<GradientContainer> createState() => _GradientContainerState(); } class _GradientContainerState extends State<GradientContainer> { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Container( height: size.height * 0.2, width: size.width * 0.42, padding: const EdgeInsets.all(8.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(18), gradient: LinearGradient( colors: [ // const Color(0xffFFFFFF).withOpacity(0.4), widget.model.coinColor, const Color(0xffFFFFFF).withOpacity(0.5) ], begin: Alignment.topLeft, end: Alignment.bottomRight, tileMode: TileMode.decal)), child: Column( children: [ Expanded( child: Row( children: [ SvgPicture.asset( "assets/icons/${widget.model.logo}.svg", height: 30, width: 30, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.model.title, style: const TextStyle(color: Color(0xffFFFFFF)), ), Text( widget.model.shortCut, style: const TextStyle(color: Colors.white24), ) ], ), ) ], ), ), Expanded( child: SvgPicture.asset( "assets/icons/${widget.model.lineSource}.svg", ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( widget.model.value, style: const TextStyle(color: Color(0xffFFFFFF)), ), const Spacer(), const Icon( Icons.arrow_drop_up, color: Color(0Xff04DC00), ), Text( widget.model.increment, style: const TextStyle(color: Color(0Xff04DC00)), ), ], ), ) ], ), ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/widgets/indicator.dart
import 'package:flutter/material.dart'; class Indicator extends StatelessWidget { const Indicator({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( width: 80, decoration: BoxDecoration( color: const Color(0xff012500), borderRadius: BorderRadius.circular(30), ), child: Row( children: const [ Icon( Icons.arrow_drop_up_outlined, color: Color(0xff04DC00), ), Text( "10.45 %", style: TextStyle(color: Color(0xffFFFFFF)), ) ], ), ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/widgets/custom_textform_field.dart
import 'package:crypto_wallet/utils/util_logic.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class CustomTextFormField extends StatelessWidget { const CustomTextFormField( {Key? key, required this.controller, required this.title, required this.titleStyle, this.isPassword}) : super(key: key); final TextEditingController controller; final TextStyle titleStyle; final String title; final bool? isPassword; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 4.0), child: Text( title, style: titleStyle, ), ), Container( decoration: BoxDecoration( color: const Color(0xffFFFFFF), borderRadius: BorderRadius.circular(5)), child: Consumer<UtilLogic>( builder: (context, utilLogicProvider, child) => TextFormField( controller: controller, obscureText: isPassword == true ? utilLogicProvider.isPasswordObsecure : false, decoration: InputDecoration( suffixIcon: isPassword != null && isPassword == true ? IconButton( onPressed: () { utilLogicProvider.changePasswordVisibilty(); }, icon: utilLogicProvider.isPasswordObsecure ? const Icon(Icons.visibility_off) : const Icon(Icons.visibility)) : null, border: InputBorder.none, contentPadding: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 12.0)), )), ), ], ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/widgets/loading_indicator.dart
import 'package:flutter/material.dart'; import 'package:loading_indicator/loading_indicator.dart'; class LoadingWidget extends StatefulWidget { const LoadingWidget({Key? key}) : super(key: key); @override State<LoadingWidget> createState() => _LoadingWidgetState(); } class _LoadingWidgetState extends State<LoadingWidget> { @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ SizedBox( height: 80, width: 60, child: LoadingIndicator( indicatorType: Indicator.ballGridBeat, /// Required, The loading type of the widget colors: [Colors.white, Color(0xff4B70FF)], /// Optional, The color collections strokeWidth: 2, /// Optional, The stroke of the line, only applicable to widget which contains line backgroundColor: Colors.transparent, /// Optional, Background of the widget // pathBackgroundColor: Colors.black /// Optional, the stroke backgroundColor ), ), Text( "Transfering Funds...", style: TextStyle(color: Colors.white), ) ], ); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/model/transactions_model.dart
class TransactinosModel { final String destionationAddress; final String name; final String value; final String type; TransactinosModel( {required this.destionationAddress, required this.name, required this.value, required this.type}); }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/model/currency_model.dart
import 'package:flutter/material.dart'; class Curreny { final Color coinColor; final String lineSource; final String logo; final String title; final String shortCut; final String value; final String increment; Curreny({ required this.coinColor, required this.lineSource, required this.title, required this.logo, required this.shortCut, required this.value, required this.increment, }); }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view_model/login_screen__view_model.dart
import 'package:flutter/cupertino.dart'; class LoginScreenViewModel with ChangeNotifier {}
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view_model/registration_screen_view_model.dart
import 'package:flutter/cupertino.dart'; class RegistrationScreenViewModel with ChangeNotifier {}
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/view_model/account_screen_view_model.dart
import 'package:flutter/cupertino.dart'; class AccountScreenViewModel with ChangeNotifier { bool isLoading = false; void changeLoading() { isLoading = !isLoading; notifyListeners(); } }
0
mirrored_repositories/crypto-mobile-app-UI-/lib
mirrored_repositories/crypto-mobile-app-UI-/lib/utils/util_logic.dart
import 'package:flutter/cupertino.dart'; class UtilLogic with ChangeNotifier { var isPasswordObsecure = true; void changePasswordVisibilty() { isPasswordObsecure = !isPasswordObsecure; notifyListeners(); } }
0
mirrored_repositories/crypto-mobile-app-UI-
mirrored_repositories/crypto-mobile-app-UI-/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:crypto_wallet/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/Coursely
mirrored_repositories/Coursely/lib/intropage.dart
import 'package:coursely/intropage2.dart'; import 'package:flutter/material.dart'; class intropage extends StatelessWidget { const intropage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, backgroundColor: Colors.white, actions: <Widget>[ TextButton( onPressed: () { print('The skip button is pressed'); Navigator.push(context, MaterialPageRoute(builder: (context)=> intropage2()), ); }, child: Text( 'Skip', style: TextStyle(fontSize: 14, color: Colors.black54), )), ], ), body: Column( children: [ Padding(padding: EdgeInsets.only( top: 50, ),), Container(child: Center(child: Image.asset('assets/introimage.jpg'))), SizedBox(height: 110,), Container( child: Text( 'Hi There!', style: TextStyle( fontFamily: 'Poppins', fontSize: 40, fontWeight: FontWeight.bold, ), ), ), SizedBox( height: 5, ), Container( child: Text( 'Unlock your potential with every course\n one click at a time.', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Poppins', fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black, ), ), ), SizedBox( height: 25, ), Container( child: ElevatedButton(onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const intropage2()), ); print('The button is pressed'); },style: ButtonStyle( backgroundColor: MaterialStatePropertyAll<Color>(Colors.black), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), ), ), child: Icon(Icons.arrow_forward_outlined,color: Colors.white,)) ), ], ), ); } }
0
mirrored_repositories/Coursely
mirrored_repositories/Coursely/lib/homepage.dart
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class homepage extends StatelessWidget { const homepage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only( top: 80, left: 30, ), child: Container( child: RichText( text: TextSpan( children: [ TextSpan( text: 'Hi,', style: TextStyle( fontFamily: 'Cirka', fontSize: 22.0, color: Colors.black, fontWeight: FontWeight.normal), ), TextSpan( text: ' Priyansh', style: TextStyle( fontFamily: 'Cirka', fontSize: 22.0, color: Color(0xFFCC5A07), fontWeight: FontWeight.normal), ), TextSpan( text: '\nWelcome to Coursely', style: TextStyle( fontFamily: 'Cirka', fontSize: 22.0, color: Colors.black, fontWeight: FontWeight.normal), ), ], ), ), ), ), SizedBox(height: 30), Padding( padding: const EdgeInsets.only( left: 30, ), child: Container( child: Text( 'Your Courses', style: TextStyle( fontFamily: 'Poppins', fontSize: 20.0, fontWeight: FontWeight.bold, ), ), ), ), SizedBox(height: 20), Row( children: [ Padding( padding: const EdgeInsets.only( left: 30, ), child: Stack( children: [ Container( height: 150, width: 150, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(10.0), ), ), Padding( padding: EdgeInsets.only( left: 45, top: 45, ), child: Container( height: 60, width: 60, child: Image.asset('assets/figma logo.png'), ), ), ], ), ), SizedBox(width: 10), Stack( children: [ Container( height: 150, width: 150, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(10), ), ), Padding( padding: EdgeInsets.only( left: 45, top: 45, ), child: Container( height: 60, width: 60, child: Image.asset('assets/flutter-logo.png'), ), ), ], ), SizedBox(width: 10), Stack( children: [ Container( height: 150, width: 60, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.only( topLeft: Radius.circular(10), bottomLeft: Radius.circular(10), ), ), ), Padding( padding: EdgeInsets.only( top: 45, left: 20, ), child: Container( height: 60, width: 40, child: Image.asset('assets/Atlantis-logo.png'), ), ), ], ), ], ), SizedBox(height: 15), Row( children: [ Padding( padding: const EdgeInsets.only(left: 30), child: Container( child: Text( 'UI/UX on Figma', style: TextStyle( fontFamily: 'Poppins', fontSize: 16.0, fontWeight: FontWeight.bold, ), ), ), ), SizedBox(width: 45), Container( child: Text( 'Flutter Workshop', style: TextStyle( fontFamily: 'Poppins', fontSize: 16.0, fontWeight: FontWeight.bold, ), ), ), SizedBox(width: 40), Container( child: Text( 'Atlan', style: TextStyle( fontFamily: 'Poppins', fontSize: 16.0, fontWeight: FontWeight.bold, ), ), ), ], ), SizedBox(height: 2), Row( children: [ Padding( padding: EdgeInsets.only(left: 32), child: Container( child: Text( 'by Christopher D', style: TextStyle( fontFamily: 'Poppins', fontSize: 14.0, fontWeight: FontWeight.normal, ), ), ), ), SizedBox(width: 55), Container( child: Text( 'by Katalina C', style: TextStyle( fontFamily: 'Poppins', fontSize: 14.0, ), ), ), SizedBox(width: 80), Container( child: Text( 'by Flo', style: TextStyle( fontFamily: 'Poppins', fontSize: 14.0, ), ), ), ], ), SizedBox(height: 30), Padding( padding: const EdgeInsets.only(left: 30), child: Container( child: Text( 'Personal Statistics', style: TextStyle( fontFamily: 'Poppins', fontSize: 20.0, fontWeight: FontWeight.bold, ), ), ), ), SizedBox(height: 20), Row( children: [ Padding( padding: const EdgeInsets.only(left: 45), child: Stack( children: [ Container( height: 150, width: 150, decoration: BoxDecoration( color: Colors.black12, borderRadius: BorderRadius.circular(10), ), ), Column( children: [ Padding( padding: const EdgeInsets.only(left: 35, top: 30), child: Container( child: Text( '11', style: TextStyle( fontFamily: 'Poppins', fontSize: 30.0, fontWeight: FontWeight.w800, ), ), ), ), SizedBox( height: 3, ), Padding( padding: const EdgeInsets.only(left: 35), child: Container( child: Text( 'Course\nCompleted', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Poppins', fontSize: 15.0, fontWeight: FontWeight.bold), ), ), ), ], ), ], ), ), SizedBox( width: 40, ), Stack( children: [ Container( height: 150, width: 150, decoration: BoxDecoration( color: Colors.black12, borderRadius: BorderRadius.circular(10), ), ), Column( children: [ Padding( padding: const EdgeInsets.only(left: 40, top: 30), child: Container( child: Text( '3', style: TextStyle( fontFamily: 'Poppins', fontSize: 30.0, fontWeight: FontWeight.w800, ), ), ), ), SizedBox( height: 3, ), Padding( padding: const EdgeInsets.only(left: 40), child: Container( child: Text( 'Course\nprogress', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Poppins', fontSize: 15.0, fontWeight: FontWeight.bold), ), ), ), ], ) ], ) ], ), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 30), child: Container( child: Text( 'Learn more way faster', style: TextStyle( fontFamily: 'Poppins', fontSize: 20.0, fontWeight: FontWeight.bold, ), ), ), ), SizedBox( height: 20, ), Center( child: Container( height: 50, width: 350, child: ElevatedButton( style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), ), backgroundColor: Colors.black), onPressed: () {}, child: Text( 'Go pro now and save 80%', style: TextStyle( fontFamily: 'Poppins', fontSize: 14, color: Colors.white), ), ), ), ), ], ), bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.black, fixedColor: Colors.white, unselectedItemColor: Colors.white, items: [ BottomNavigationBarItem(icon: Icon(Icons.home,color: Colors.white,), label: 'Home',), BottomNavigationBarItem(icon: Icon(Icons.search,color: Colors.white,), label: 'Explore',), BottomNavigationBarItem(icon: Icon(Icons.account_circle_sharp,color: Colors.white,), label: 'Profile',), ]), ); } }
0
mirrored_repositories/Coursely
mirrored_repositories/Coursely/lib/main.dart
import 'package:coursely/intropage.dart'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Coursely', home: intropage(), ); } }
0
mirrored_repositories/Coursely
mirrored_repositories/Coursely/lib/intropage2.dart
import 'package:coursely/homepage.dart'; import 'package:flutter/material.dart'; class intropage2 extends StatelessWidget { const intropage2({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, backgroundColor: Colors.white, ), body: Column( children: [ Padding(padding: EdgeInsets.only( top: 50, ),), Container(child: Center(child: Image.asset('assets/intro2.png'))), SizedBox(height: 110,), Container( child: Text( 'We are all set!', style: TextStyle( fontFamily: 'Poppins', fontSize: 40, fontWeight: FontWeight.bold, ), ), ), SizedBox( height: 5, ), Container( child: Text( 'Embark on a journey of knowledge and growth \n one course at a time', textAlign: TextAlign.center, style: TextStyle( fontFamily: 'Poppins', fontSize: 15, fontWeight: FontWeight.bold, color: Colors.black, ), ), ), SizedBox( height: 25, ), Container( child: ElevatedButton(onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => homepage()), ); print('The button is pressed'); },style: ButtonStyle( backgroundColor: MaterialStatePropertyAll<Color>(Colors.black), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), ), ), child: Text('Lets Go',style: TextStyle( fontFamily: 'Poppins', fontSize: 14, color: Colors.white, ),)), ), ], ), ); } }
0
mirrored_repositories/Coursely
mirrored_repositories/Coursely/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:coursely/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/Beacon/App/Beacon_app
mirrored_repositories/Beacon/App/Beacon_app/lib/main.dart
import 'package:Beacon_app/UI/Intray/intray_page.dart'; import 'package:Beacon_app/UI/Login/loginscreen.dart'; import 'package:Beacon_app/bloc/resources/repository.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'models/global.dart'; import 'package:http/http.dart' as http; import 'package:Beacon_app/models/classes/user.dart'; import 'package:Beacon_app/bloc/blocs/user_bloc_provider.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Beacon', theme: ThemeData( primarySwatch: Colors.grey, dialogBackgroundColor: Colors.transparent), home: MyHomePage()); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { TaskBloc tasksBloc; String apiKey = ""; Repository _repository = Repository(); @override Widget build(BuildContext context) { return FutureBuilder( future: signinUser(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { apiKey = snapshot.data; tasksBloc = TaskBloc(apiKey); print(apiKey); } else { print("No data"); } // String apiKey = snapshot.data; //apiKey.length > 0 ? getHomePage() : return apiKey.length > 0 ? getHomePage() : LoginPage( login: login, newUser: false, ); }, ); } void login() { setState(() { build(context); }); } Future signinUser() async { String userName = ""; String apiKey = await getApiKey(); if (apiKey.length > 0) { userBloc.signinUser("", "", apiKey); } else { print("No Api key Found"); } return apiKey; } Future getApiKey() async { print("hello"); SharedPreferences prefs = await SharedPreferences.getInstance(); return await prefs.getString("API_Token"); } Widget getHomePage() { return MaterialApp( color: Colors.yellow, home: SafeArea( child: DefaultTabController( length: 3, child: new Scaffold( body: Stack(children: <Widget>[ TabBarView( children: [ new Container( color: blueColor, ), IntrayPage( apiKey: apiKey, ), new Container( child: Center( child: FlatButton( color: Colors.orangeAccent[700], child: Text("Log out"), onPressed: () { logout(); }, ), ), color: blueColor, ), ], ), Container( height: 170, decoration: BoxDecoration( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(80), bottomRight: Radius.circular(80), ), color: Colors.white, ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Text( "Intray", style: intrayTitleStyle, )), Container(), ], ), ), Container( height: 80, width: 80, margin: EdgeInsets.only( top: 120, left: MediaQuery.of(context).size.width * 0.75), child: Container( height: 80, width: 80, child: FloatingActionButton( child: Icon( Icons.add, size: 70, ), backgroundColor: Colors.orange[400], onPressed: _additionmenubox, ), ), ), ]), appBar: AppBar( elevation: 0, title: new TabBar( tabs: [ Tab( icon: new Icon(Icons.calendar_today, size: 55), ), Tab( icon: new Icon(Icons.add, size: 60), ), Tab( icon: new Icon(Icons.menu, size: 60), ), ], labelColor: blueColor, unselectedLabelColor: greylightColor, indicatorSize: TabBarIndicatorSize.label, indicatorPadding: EdgeInsets.all(5.0), indicatorColor: Colors.transparent, ), backgroundColor: Colors.white, ), backgroundColor: Colors.white, ), ), ), ); } void _additionmenubox() { TextEditingController taskName = new TextEditingController(); TextEditingController deadline = new TextEditingController(); // flutter defined function showDialog( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( content: Container( padding: EdgeInsets.all(20), constraints: BoxConstraints.expand(height: 900, width: 690), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(35)), color: Colors.white, gradient: LinearGradient( colors: [Colors.white, Colors.grey[200], Colors.grey[300]]), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text("Adder", style: intrayTitleStyle), Container( child: FlatButton( color: Colors.transparent, child: Text( " Tasks ", style: additionMenuStyle, ), onPressed: _showAddDialog, ), ), Container( child: FlatButton( color: Colors.transparent, child: Text( " Meets ", style: additionMenuStyle, ), onPressed: _showAddDialog, ), ), Container( child: FlatButton( color: Colors.transparent, child: Text( " Reminders ", style: additionMenuStyle, ), onPressed: _showAddDialog, ), ), Container( alignment: Alignment.topLeft, child: FloatingActionButton( child: Icon( Icons.cancel, size: 50, ), backgroundColor: Colors.grey[400], onPressed: () { Navigator.pop(context); }, ), ), ], ), ), ); }, ); } void _showAddDialog() { TextEditingController taskName = new TextEditingController(); TextEditingController deadline = new TextEditingController(); // flutter defined function showDialog( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( content: Container( padding: EdgeInsets.all(10), constraints: BoxConstraints.expand(height: 900, width: 690), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(35)), color: Colors.white, gradient: LinearGradient( colors: [Colors.white, Colors.grey[200], Colors.grey[300]]), ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text("Tasks", style: intrayTitleStyle,), Text(" Task Name ", style: additionMenuStyle), Container( child: TextField( autofocus: false, style: TextStyle( fontFamily: 'Roboto', fontSize: 22.0, color: blueColor, fontWeight: FontWeight.bold), decoration: InputDecoration( filled: true, fillColor: Colors.white, hintText: 'Task Name', contentPadding: const EdgeInsets.only( left: 14.0, bottom: 8.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), ), controller: taskName, ), ), Text(" Deadline ", style: additionMenuStyle), Container( child: TextField( autofocus: false, style: TextStyle( fontFamily: 'Roboto', fontSize: 22.0, color: blueColor, fontWeight: FontWeight.bold), decoration: InputDecoration( filled: true, fillColor: Colors.white, hintText: 'Task Name', contentPadding: const EdgeInsets.only( left: 14.0, bottom: 8.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), ), controller: deadline, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ RaisedButton( color: Colors.transparent, child: Text( " Cancel ", style: additionbuttonStyle, ), onPressed: () { Navigator.pop(context); }, ), RaisedButton( color: Colors.transparent, child: Text( " Add ", style: additionbuttonStyle, ), onPressed: () { if (taskName.text != null) { addTask(taskName.text, deadline.text); Navigator.pop(context);} }, ), ], ) ], ), ), ); }, ); } void addTask(String taskName, String deadline) async { await _repository.addUserTask(this.apiKey, taskName, deadline); } logout() async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString("API_Token", ""); setState(() { build(context); }); } @override void initState() { super.initState(); } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib
mirrored_repositories/Beacon/App/Beacon_app/lib/models/global.dart
import 'package:flutter/material.dart'; Color blueSignupColor = new Color(0x030D1C); Color blueColor = new Color(0xFF131A23); Color greyColor = new Color(0xFF131A23); Color greylightColor = new Color(0x707070); Color floatingOrangeColor = new Color(0xF57615); Color pluckcardcolor = new Color(0xF5F5F5); TextStyle intrayTitleStyle = new TextStyle( fontFamily: 'Roboto', fontWeight: FontWeight.bold, color: blueColor, fontSize: 65); TextStyle loginTitleStyle = new TextStyle( fontFamily: 'Roboto', fontWeight: FontWeight.bold, color: Colors.grey[400], fontSize: 50); TextStyle pluckLightTitleStyle = new TextStyle( fontFamily: 'Comic San MS', fontWeight: FontWeight.normal, color: blueColor, fontSize: 30, ); TextStyle pluckLightDateStyle = new TextStyle( fontFamily: 'LCDMono2', fontWeight: FontWeight.normal, color: blueColor, ); TextStyle pluckLightInsideStyle = new TextStyle( fontFamily: 'Roboto', fontWeight: FontWeight.bold, color: blueColor); TextStyle pluckDarkTitleStyle = new TextStyle( fontFamily: 'Roboto', fontWeight: FontWeight.bold, color: Colors.yellow); TextStyle yellowSigninStyleU = new TextStyle( fontFamily: 'Avenir', color: Colors.yellow, fontSize: 30, fontWeight: FontWeight.bold); TextStyle yellowSigninStyleUx = new TextStyle( fontFamily: 'Avenir', color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold); TextStyle yellowSigninStyle = new TextStyle( fontFamily: 'Avenir', color: Colors.yellow[800], fontSize: 15, ); TextStyle additionMenuStyle = new TextStyle( fontFamily: 'Avenir', color: blueColor, fontSize: 40, decoration: TextDecoration.underline, ); TextStyle additionbuttonStyle = new TextStyle( fontFamily: 'Avenir', color: blueColor, fontSize: 15, decoration: TextDecoration.underline, );
0
mirrored_repositories/Beacon/App/Beacon_app/lib/models
mirrored_repositories/Beacon/App/Beacon_app/lib/models/widgets/intray_todo_widget.dart
import 'package:Beacon_app/models/global.dart'; import 'package:flutter/material.dart'; import 'package:Beacon_app/UI/Intray/intray_page.dart'; class IntrayTodo extends StatelessWidget { final String title; final String deadline; final String keyValue; IntrayTodo({this.keyValue, this.title, this.deadline}); @override Widget build(BuildContext context) { return Container( key: Key(keyValue), decoration: BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(25), topRight: Radius.circular(25), bottomLeft: Radius.circular(25), bottomRight: Radius.circular(25), ), gradient: LinearGradient( colors: [Colors.white, Colors.grey[200], Colors.grey[300]]), boxShadow: [ new BoxShadow(color: Colors.yellow.withOpacity(0.5), blurRadius: 10) ]), child: Row( children: <Widget>[ Radio(), Column( children: [ Center( child: Text( deadline, style: pluckLightDateStyle, ), ), Center( child: Text( title, style: pluckLightTitleStyle, ), ), ], ) ], ), margin: EdgeInsets.only(bottom: 10), padding: EdgeInsets.all(30), height: 200, ); } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/models
mirrored_repositories/Beacon/App/Beacon_app/lib/models/classes/task.dart
import 'dart:convert'; class Task { List<Task> tasks; String note; DateTime timeToComplete; bool completed; String repeats; String deadline; List<DateTime> reminders; int taskId; String title; Task(this.title, this.completed, this.taskId, this.note, this.deadline); factory Task.fromJson(Map<String, dynamic> parsedJson) { return Task( parsedJson['title'], parsedJson['completed'], parsedJson['id'], parsedJson['note'], parsedJson['deadline'], ); } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/models
mirrored_repositories/Beacon/App/Beacon_app/lib/models/classes/user.dart
// ignore: unused_import import 'package:flutter/rendering.dart'; class User { String username; String lastname; String firstname; String email; String password; String api_key; int id; User(this.username, this.lastname, this.firstname, this.email, this.password, this.id, this.api_key); factory User.fromJson(Map<String, dynamic> parsedJson) { return User( parsedJson['username'], parsedJson['lastname'], parsedJson['emailadress'], parsedJson['firstname'], parsedJson['password'], parsedJson['id'], parsedJson['api_key']); } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/models
mirrored_repositories/Beacon/App/Beacon_app/lib/models/authentication/authorize.dart
import 'dart:async'; import 'package:flutter/material.dart'; class AuthService with ChangeNotifier { var currentUser; AuthService() { print("new AuthService"); } Future getUser() { return Future.value(currentUser); } // wrappinhg the firebase calls Future logout() { this.currentUser = null; notifyListeners(); return Future.value(currentUser); } // wrapping the firebase calls Future createUser( {String firstName, String lastName, String email, String password}) async {} // logs in the user if password matches Future loginUser({String email, String password}) { if (password == 'password123') { this.currentUser = {'email': email}; notifyListeners(); return Future.value(currentUser); } else { this.currentUser = null; return Future.value(null); } } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/bloc
mirrored_repositories/Beacon/App/Beacon_app/lib/bloc/blocs/user_bloc_provider.dart
import '../resources/repository.dart'; import 'package:rxdart/rxdart.dart'; import 'package:Beacon_app/models/classes/user.dart'; import 'package:Beacon_app/models/classes/task.dart'; class UserBloc { final _repository = Repository(); final _userGetter = PublishSubject<User>(); Observable<User> get getUser => _userGetter.stream; registerUser(String username, String firstname, String lastname, String password, String email) async { User user = await _repository.registerUser( username, firstname, lastname, password, email); _userGetter.sink.add(user); } signinUser(String username, String password, String apiKey) async { User user = await _repository.signinUser(username, password, apiKey); _userGetter.sink.add(user); } dispose() { _userGetter.close(); } } class TaskBloc { final _repository = Repository(); final _taskSubject = BehaviorSubject<List<Task>>(); String apiKey; var _tasks = <Task>[]; TaskBloc(String api_key) { this.apiKey = api_key; _updateTasks(api_key).then((_) { _taskSubject.add(_tasks); }); } Stream<List<Task>> get getTasks => _taskSubject.stream; Future<Null> _updateTasks(String apiKey) async { _tasks = await _repository.getUserTasks(apiKey); } } final userBloc = UserBloc();
0
mirrored_repositories/Beacon/App/Beacon_app/lib/bloc
mirrored_repositories/Beacon/App/Beacon_app/lib/bloc/resources/api.dart
import 'dart:async'; import 'package:http/http.dart' show Client; import 'dart:convert'; import 'package:Beacon_app/models/classes/user.dart'; import 'package:Beacon_app/models/classes/task.dart'; import 'package:shared_preferences/shared_preferences.dart'; class ApiProvider { Client client = Client(); final _apiKey = 'your_api_key'; Future signinUser(String username, String password, String apiKey) async { //We need to change the I.P ADDRESS OF Local Machine in the frontend to achive local port interaction of the AVD passing through local machine Ip Address final response = await client.post("http://10.0.2.2:5000/api/Signin", headers: {"Authorization": apiKey}, body: jsonEncode({ "username": username, "password": password, })); print(response.body.toString()); final Map result = json.decode(response.body); if (response.statusCode == 201) { // If the call to the server was successful, parse the JSON await saveApiKey(result["data"]["api_key"]); } else { // If that call was not successful, throw an error. throw Exception('Failed to load post'); } } Future<User> registerUser(String username, String firstname, String lastname, String password, String email) async { //We need to change the I.P ADDRESS OF Local Machine in the frontend to achive local port interaction of the AVD passing through local machine Ip Address final response = await client.post("http://10.0.2.2:5000/api/Register", // headers: "", body: jsonEncode({ "emailaddress": email, "username": username, "password": password, "firstname": firstname, "lastname": lastname })); print(response.body.toString()); final Map result = json.decode(response.body); if (response.statusCode == 201) { // If the call to the server was successful, parse the JSON await saveApiKey(result["data"]["api_key"]); return User.fromJson(result["data"]); } else { // If that call was not successful, throw an error. throw Exception('Failed to load post'); } } Future<List<Task>> getUserTasks(String apiKey) async { //We need to change the I.P ADDRESS OF Local Machine in the frontend to achive local port interaction of the AVD passing through local machine Ip Address final response = await client.get( "http://10.0.2.2:5000/api/tasks", headers: {"Authorization": apiKey}, ); final Map result = json.decode(response.body); if (response.statusCode == 201) { // If the call to the server was successful, parse the JSON List<Task> tasks = []; for (Map json_ in result["data"]) { try { tasks.add(Task.fromJson(json_)); } catch (Exception) { print(Exception); } } for (Task task in tasks) { print(task.taskId); } return tasks; } else { // If that call was not successful, throw an error. throw Exception('Failed to load tasks'); } } Future addUserTask(String apiKey, String taskName, String deadline) async { //We need to change the I.P ADDRESS OF Local Machine in the frontend to achive local port interaction of the AVD passing through local machine Ip Address final response = await client.post("http://10.0.2.2:5000/api/tasks", headers: {"Authorization": apiKey}, body: jsonEncode({ "note": "", "repeats": "", "completed": false, "deadline": deadline, "reminders": "", "title": taskName })); if (response.statusCode == 201) { print("Task added"); } else { // If that call was not successful, throw an error. print(json.decode(response.body)); throw Exception('Failed to load tasks'); } } saveApiKey(String api_Key) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString('API_Token', api_Key); } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/bloc
mirrored_repositories/Beacon/App/Beacon_app/lib/bloc/resources/repository.dart
import 'dart:async'; import 'api.dart'; import 'package:Beacon_app/models/classes/user.dart'; class Repository { final apiProvider = ApiProvider(); Future<User> registerUser(String username, String firstname, String lastname, String password, String email) => apiProvider.registerUser(username, firstname, lastname, password, email); Future signinUser(String username, String password, String apiKey) => apiProvider.signinUser(username, password, apiKey); Future getUserTasks(String apiKey) => apiProvider.getUserTasks(apiKey); Future<Null> addUserTask(String apiKey, String taskName, String deadline) async { apiProvider.addUserTask(apiKey, taskName, deadline); } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/UI
mirrored_repositories/Beacon/App/Beacon_app/lib/UI/Intray/intray_page.dart
import 'package:Beacon_app/models/classes/task.dart'; import 'package:Beacon_app/models/global.dart'; import 'package:Beacon_app/models/widgets/intray_todo_widget.dart'; import 'package:flutter/material.dart'; import 'package:Beacon_app/bloc/blocs/user_bloc_provider.dart'; import 'package:flutter/src/widgets/framework.dart'; class IntrayPage extends StatefulWidget { final String apiKey; IntrayPage({this.apiKey}); @override _IntrayPageState createState() => _IntrayPageState(); } class _IntrayPageState extends State<IntrayPage> { List<Task> taskList = []; TaskBloc tasksBloc; // // TaskBloc taskBloc; @override void initState() { tasksBloc = TaskBloc(widget.apiKey); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Container( height: 600, width: 100, color: blueColor, child: StreamBuilder( // Wrap our widget with a StreamBuilder stream: tasksBloc.getTasks, // pass our Stream getter here initialData: [], // provide an initial data builder: (context, snapshot) { if (snapshot.hasData && snapshot != null) { if (snapshot.data.length > 0) { taskList = snapshot.data; return _buildReorderableListSimple(context, snapshot.data); } else if (snapshot.data.length == 0) { return Center(child: Text('No Data')); } } else if (snapshot.hasError) { return Container(); } return CircularProgressIndicator(); }, // access the data in our Stream here )); } Widget _buildListTile(BuildContext context, Task item) { return ListTile( key: Key(item.taskId.toString()), title: IntrayTodo( title: item.title, deadline: item.deadline.toString(), ), ); } Widget _buildReorderableListSimple( BuildContext context, List<Task> tasklist) { return Theme( data: ThemeData(canvasColor: blueColor.withOpacity(0.1)), child: ReorderableListView( // handleSide: ReorderableListSimpleSide.Right, // handleIcon: Icon(Icons.access_alarm), padding: EdgeInsets.only(top: 200.0), children: taskList.map((Task item) => _buildListTile(context, item)).toList(), onReorder: (oldIndex, newIndex) { setState(() { Task item = taskList[oldIndex]; taskList.remove(item); taskList.insert(newIndex, item); }); }, ), ); } void _onReorder(int oldIndex, int newIndex) { setState(() { if (newIndex > oldIndex) { newIndex -= 1; } final Task item = taskList.removeAt(oldIndex); taskList.insert(newIndex, item); }); } // Future<List<Task>> getList() async { // List<Task> tasks = await tasksBloc.getUserTasks(widget.apiKey); // print(taskList[0].title); // return tasks; // } }
0
mirrored_repositories/Beacon/App/Beacon_app/lib/UI
mirrored_repositories/Beacon/App/Beacon_app/lib/UI/Login/loginscreen.dart
import 'package:flutter/material.dart'; import 'package:Beacon_app/bloc/blocs/user_bloc_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:Beacon_app/models/classes/user.dart'; import 'package:Beacon_app/models/global.dart'; class LoginPage extends StatefulWidget { final VoidCallback login; final bool newUser; const LoginPage({Key key, this.newUser, this.login}) : super(key: key); @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { TextEditingController emailController = new TextEditingController(); TextEditingController usernameController = new TextEditingController(); TextEditingController firstNameController = new TextEditingController(); TextEditingController passwordController = new TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: blueColor, body: Center(child: widget.newUser ? getSignupPage() : getSigninPage()), ); } Widget getSigninPage() { TextEditingController usernameText = new TextEditingController(); TextEditingController passwordText = new TextEditingController(); return Container( padding: const EdgeInsets.symmetric(horizontal: 43.0), margin: EdgeInsets.only(top: 70, left: 30, right: 30, bottom: 40), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Image(image: AssetImage('assets/images/Group_4.png')), Text("Welcome", style: loginTitleStyle), Container( height: 200, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Theme( data: Theme.of(context) .copyWith(splashColor: Colors.transparent), child: TextField( autofocus: false, style: TextStyle( fontFamily: 'Roboto', fontSize: 22.0, color: blueColor, fontWeight: FontWeight.bold), decoration: InputDecoration( filled: true, fillColor: Colors.white, hintText: 'Username', contentPadding: const EdgeInsets.only( left: 14.0, bottom: 8.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), ), controller: usernameText, ), ), Theme( data: Theme.of(context) .copyWith(splashColor: Colors.transparent), child: TextField( autofocus: false, style: TextStyle( fontFamily: 'Roboto', fontSize: 22.0, color: blueColor, fontWeight: FontWeight.bold), decoration: InputDecoration( filled: true, fillColor: Colors.white, hintText: 'Password', contentPadding: const EdgeInsets.only( left: 14.0, bottom: 8.0, top: 8.0), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(25.7), ), ), controller: passwordText, ), ), FlatButton( child: Text( "Signin", style: yellowSigninStyleU, ), onPressed: () { if (usernameText.text != null || passwordText.text != null) { userBloc.signinUser(usernameText.text, passwordText.text, "").then((_) { widget.login(); }); } }, ) ], ), ), Container( child: Column( children: <Widget>[ Text("Don't have any account", style: yellowSigninStyle), FlatButton( child: Text( "Create Account", style: yellowSigninStyleU, ), onPressed: () {}, ) ], ), ) ], ), ); } Widget getSignupPage() { return Container( margin: EdgeInsets.all(30), child: Column( children: <Widget>[ TextField( controller: emailController, decoration: InputDecoration( hintText: "Email", floatingLabelBehavior: FloatingLabelBehavior.auto, ), ), TextField( controller: usernameController, decoration: InputDecoration( hintText: "Username", floatingLabelBehavior: FloatingLabelBehavior.auto, ), ), TextField( controller: firstNameController, decoration: InputDecoration( hintText: "Firstname", floatingLabelBehavior: FloatingLabelBehavior.auto, ), ), TextField( controller: passwordController, decoration: InputDecoration( hintText: "Password", floatingLabelBehavior: FloatingLabelBehavior.auto, ), ), FlatButton( color: Colors.green, child: Text("Sign up for gods sake"), onPressed: () { if (usernameController.text != null || passwordController.text != null || emailController.text != null) { userBloc .registerUser( usernameController.text, firstNameController.text ?? "", "", passwordController.text, emailController.text) .then((_) { widget.login(); }); } }, ), ], ), ); } }
0
mirrored_repositories/Beacon/App/Beacon_app
mirrored_repositories/Beacon/App/Beacon_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 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:Beacon_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Netsurf-Flutter-App
mirrored_repositories/Netsurf-Flutter-App/lib/generated_plugin_registrant.dart
// // Generated file. Do not edit. // // ignore_for_file: directives_ordering // ignore_for_file: lines_longer_than_80_chars import 'package:cloud_firestore_web/cloud_firestore_web.dart'; import 'package:firebase_analytics_web/firebase_analytics_web.dart'; import 'package:firebase_core_web/firebase_core_web.dart'; import 'package:package_info_plus_web/package_info_plus_web.dart'; import 'package:share_plus_web/share_plus_web.dart'; import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { FirebaseFirestoreWeb.registerWith(registrar); FirebaseAnalyticsWeb.registerWith(registrar); FirebaseCoreWeb.registerWith(registrar); PackageInfoPlugin.registerWith(registrar); SharePlusPlugin.registerWith(registrar); SharedPreferencesPlugin.registerWith(registrar); UrlLauncherPlugin.registerWith(registrar); registrar.registerMessageHandler(); }
0
mirrored_repositories/Netsurf-Flutter-App
mirrored_repositories/Netsurf-Flutter-App/lib/main.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_phoenix/flutter_phoenix.dart'; import 'package:get_it/get_it.dart'; import 'package:project_netsurf/common/analytics.dart'; import 'package:project_netsurf/common/contants.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/display_data.dart'; import 'package:project_netsurf/common/product_constant.dart'; import 'package:project_netsurf/common/ui/loader.dart'; import 'package:project_netsurf/ui/home.dart'; import 'common/ui/theme.dart'; import 'di/singletons.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await setupDependencies(); runApp(Phoenix(child: MyApp())); } class MyApp extends StatelessWidget { static FirebaseAnalytics analytics = GetIt.I.get<FirebaseAnalytics>(); static FirebaseFirestore fireStore = GetIt.I.get<FirebaseFirestore>(); DisplayData? displayData = GetIt.I.get<DisplayData>(); @override Widget build(BuildContext context) { onAppStart(); return MaterialApp( title: APP_NAME, theme: NetsurfAppTheme(), navigatorObservers: [FirebaseAnalyticsObserver(analytics: analytics)], builder: (context, child) => AppContainer(context, child), home: FutureBuilder( future: Products.getAllProducts(fireStore, false), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return navigateToHome(context); } else if (snapshot.hasError) { return showErrorMessage(context); } else { return CustomLoader(); } }, ), ); } void onAppStart() { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); analytics.logAppOpen(); analytics.setCurrentScreen(screenName: CT_HOME_SCREEN); } Widget navigateToHome(BuildContext context) { User? retailUser = GetIt.I.get<User>(); String? billingId = GetIt.I.get<String>(instanceName: BILLING_ID); if (displayData == null) { return showErrorMessage(context); } var userLogin = retailUser.name.isNotEmpty && retailUser.mobileNo.isNotEmpty; print("RetailerData: " + retailUser.name); return HomePage( isRetailer: !userLogin, retailer: userLogin ? retailUser : null, displayData: displayData!, billingIdVal: billingId); } Widget showErrorMessage(BuildContext context) { return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center( child: Text( "Something went wrong. Please check your internet!", style: TextStyle(fontSize: 14), textAlign: TextAlign.center, ), ), IconButton( icon: Icon(Icons.refresh_rounded), onPressed: () { Phoenix.rebirth(context); }), ], ), ); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/di/singletons.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:get_it/get_it.dart'; import '../common/contants.dart'; import '../common/models/customer.dart'; import '../common/models/display_data.dart'; import '../common/product_constant.dart'; import '../common/sp_constants.dart'; import '../common/sp_utils.dart'; Future<void> setupDependencies() async { await setupFirebase(); await setupDisplayData(); await setupBillingID(); await setupRetailerDetails(); } Future<void> setupDisplayData() async { FirebaseFirestore fireStore = GetIt.I.get<FirebaseFirestore>(); DisplayData? displayData = await Products.getDisplayData(fireStore, false); if (displayData != null) GetIt.I.registerSingleton<DisplayData>(displayData); } Future<void> setupFirebase() async { FirebaseApp app = await Firebase.initializeApp(); GetIt.I.registerSingleton<FirebaseApp>(app); GetIt.I.registerSingleton<FirebaseAnalytics>(FirebaseAnalytics.instance); GetIt.I.registerSingleton<FirebaseFirestore>(FirebaseFirestore.instance); } Future<void> setupBillingID() async { String? billingId = await Preference.getItem(SP_BILLING_ID); if (billingId.isNotEmpty) { int lastBillID = int.parse(billingId); billingId = (++lastBillID).toString(); } else { billingId = BILLING_ID_START; } GetIt.I.registerSingleton<String>(billingId, instanceName: BILLING_ID); } Future<void> setupRetailerDetails() async { if (GetIt.instance.isRegistered<User>()) GetIt.instance.unregister<User>(); User? user = await Preference.getRetailer(); if (user == null) user = User("", "", "", "", ""); GetIt.I.registerSingleton<User>(user); }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/common/contants.dart
import 'package:flutter/material.dart'; const String APP_NAME = "Netsurfs Calci"; const String SAVED = "Saved bills"; const String RUPEE_SYMBOL = "\u20B9"; const String TOTAL_AMOUNT = "Total amount (" + RUPEE_SYMBOL +") "; const String DISCOUNT = "Discount (" + RUPEE_SYMBOL +") "; const String FINAL_AMOUNT = "Final Amount (" + RUPEE_SYMBOL +") "; const int PRIMARY_COLOR = 0xFF333366; const int SECONDARY_COLOR = 0xFF5555aa; const int LOADER_COLOR = 0x445555aa; const int LOADER_BASE_COLOR = 0x115555aa; Map<int, Color> THEME_COLOR = { 50: Color.fromRGBO(51, 51, 102, .1), 100: Color.fromRGBO(51, 51, 102, .2), 200: Color.fromRGBO(51, 51, 102, .3), 300: Color.fromRGBO(51, 51, 102, .4), 400: Color.fromRGBO(51, 51, 102, .5), 500: Color.fromRGBO(51, 51, 102, .6), 600: Color.fromRGBO(51, 51, 102, .7), 700: Color.fromRGBO(51, 51, 102, .8), 800: Color.fromRGBO(51, 51, 102, .9), 900: Color.fromRGBO(51, 51, 102, 1), }; const String BILLING_ID = "BillingID"; const String BILLING_ID_START = "1001";
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/common/sp_utils.dart
import 'dart:async'; import 'package:project_netsurf/common/models/billing.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/display_data.dart'; import 'package:project_netsurf/common/sp_constants.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'models/product.dart'; class Preference { Preference._(); static Future<SharedPreferences> _prefs = SharedPreferences.getInstance(); static Future<SharedPreferences> getPref() async { return await _prefs; } static Future<bool> remove(String name) async { return (await _prefs).remove(name); } static Future<String> getItem(String name) async { return (await _prefs).getString(name) ?? ''; } static Future<bool> setItem(String name, String value) async { return (await _prefs).setString(name, value); } static Future<int> getIntItem(String name) async { return (await _prefs).getInt(name) ?? 0; } static Future<bool> setIntItem(String name, int value) async { return (await _prefs).setInt(name, value); } static Future<double> getDoubleItem(String name) async { return (await _prefs).getDouble(name) ?? 0; } static Future<bool> setDoubleItem(String name, double value) async { return (await _prefs).setDouble(name, value); } static Future<bool> getBoolItem(String name) async { return (await _prefs).getBool(name) ?? false; } static Future<bool> setBoolItem(String name, bool value) async { return (await _prefs).setBool(name, value); } static Future<Set<String>> getAll() async { return (await _prefs).getKeys(); } static Future<bool> setListData(String key, List<String> value) async { return (await _prefs).setStringList(key, value); } Future<List<String>?> getListData(String key) async { return (await _prefs).getStringList(key); } static Future<bool> contains(String name) async { return (await _prefs).containsKey(name); } static Future<bool> setDisplayData(DisplayData displayData) async { final String encodedData = DisplayData.encode(displayData); return (await _prefs).setString(SP_DISPLAY, encodedData); } static Future<DisplayData> getDisplayData() async { String displayString = (await _prefs).getString(SP_DISPLAY) ?? ""; final DisplayData decodedData = DisplayData.decode(displayString); return decodedData; } static Future<bool> setProducts(List<Product> products, String name) async { final String encodedData = Product.encode(products); return await (await _prefs).setString(name, encodedData); } static Future<List<Product>> getProducts(String name) async { String productsEncoded = (await _prefs).getString(name) ?? ""; final List<Product> decodedData = Product.decode(productsEncoded); return decodedData; } static Future<bool> setRetailer(User retailer) async { final String encodedData = User.encode(retailer); return (await _prefs).setString(SP_RETAILER, encodedData); } static Future<User?> getRetailer() async { String? decodedData = (await _prefs).getString(SP_RETAILER); if (decodedData == null) return null; final User decodedRetailer = User.decode(decodedData); return decodedRetailer; } static Future<bool> addBill(Billing billing) async { List<Billing> bills = []; if (!(await _prefs).containsKey(SP_BILLING)) { bills.add(billing); } else { bills = await getBills(); bills.insert(0, billing); } final String encodedData = Billing.encodeList(bills); return (await _prefs).setString(SP_BILLING, encodedData); } static Future<bool> addBills(List<Billing> billing) async { final String encodedData = Billing.encodeList(billing); return (await _prefs).setString(SP_BILLING, encodedData); } static Future<List<Billing>> getBills() async { String decodedData = (await _prefs).getString(SP_BILLING) ?? ""; final List<Billing> decodedRetailer = Billing.decodeList(decodedData); return decodedRetailer; } static Future<bool> clearAllBills() async { return (await _prefs).remove(SP_BILLING); } static Future<bool> setDateTime(String key) async { return await (await _prefs).setString(key, DateTime.now().toIso8601String()); } static Future<DateTime> getDateTime(String key) async { String? displayString = (await _prefs).getString(key); if (displayString == null) { var done = await setDateTime(SP_DT_REFRESH); if (done) displayString = (await _prefs).getString(key); } return DateTime.parse(displayString!); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/common/sp_constants.dart
const String SP_CUSTOMER_NAME = "SP_CustomerName"; const String SP_CUSTOMER_M_NO = "SP_CustomerMNo"; const String SP_CUSTOMER_RF_ID = "SP_CustomerRfId"; const String SP_CUSTOMER_ADDRESS = "SP_CustomerAddress"; const String SP_CUSTOMER_EMAIL = "SP_CustomerEmail"; const String SP_PRODUCTS = "SP_Products"; const String SP_CATEGORY_IDS = "SP_CategoryIds"; const String SP_RETAILER = "SP_Retailer"; const String SP_BILLING = "SP_Billing"; const String SP_BILLING_ID = "SP_BillingID"; const String SP_DISPLAY = "SP_Display"; const String SP_DT_REFRESH = "SP_DT_REFRESH";
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/common/fs_constants.dart
const String FSC_PRODUCT_NAMES = "ProductsNames"; const String FSC_PRODUCTS = "Products"; const String FS_S = "/"; const String FS_ID = "id"; const String FS_NAME = "name"; const String FS_DISPLAY_DATA = "DisplayData"; const String FS_DISPLAY = "display";
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/common/analytics.dart
const String CT_HOME_SCREEN = "Home_Screen"; const String CT_DISTRIBUTER_SCREEN = "Distributor_Screen"; const String CT_USER_SCREEN = "User_Screen"; const String CT_PRODUCT_SELECTION = "Product_Selection_Screen"; const String CT_BILLING = "Billing_Screen"; const String CT_PDF_CREATION = "PDF_Screen"; const String CT_DRAWER = "Drawer_Screen"; const String CT_SAVED_BILLS = "Saved_Bills_Screen"; const String CT_DISTRIBUTOR_NAME = "Distributor_Name"; const String CT_DISTRIBUTOR_PH_NO = "Distributor_Ph_No"; const String CT_CUSTOMER_NAME = "Customer_Name"; const String CT_CUSTOMER_PH_NO = "Customer_Ph_No"; const String CT_BILLING_NO = "Billing_No"; const String CT_BILLING_DATE = "Billing_Date"; const String CT_MODEL_NAME = "Model_Name"; const String CT_MANUFACTURER_NAME = "Manufacturer_Name"; const String CT_ANDROID_ID = "Android_Id"; const String CT_ANDROID_VERSION = "Android_Version"; const String CT_ANDROID_VERSION_STRING = "Android_Version_String"; const String CT_DISTRIBUTOR_LOGIN = "Distributor_Login"; const String CT_SAVE_BILL = "Save_Bill"; const String CT_SHARE_APP = "Share_App_Click"; const String CT_REPORT_ISSUE = "Report_Issue_Click"; const String CT_AUTHOR = "Author_Click"; const String CT_LOGOUT = "Log_Out_Click";
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/common/product_constant.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:project_netsurf/common/fs_constants.dart'; import 'package:project_netsurf/common/models/display_data.dart'; import 'package:project_netsurf/common/models/product.dart'; import 'package:project_netsurf/common/sp_constants.dart'; import 'package:project_netsurf/common/sp_utils.dart'; class Products { static Product? getProductCategorys(List<Product?> allCategories, int id) { return allCategories.firstWhere((element) => element?.id == id); } static List<Product> getProductsFromCategorysIds(List<Product?> allProducts, Product? selectedProduct, List<Product?> selectedProducts) { List<Product> products = []; allProducts.forEach((element) { if (element?.productCategoryId == selectedProduct?.id && !productPresent(selectedProducts, element)) { products.add(element!); } }); products.sort((a, b) => a.id.compareTo(b.id)); return products; } static bool productPresent( List<Product?> selectedProducts, Product? product) { return selectedProducts.any((element) { return element?.id == product?.id && element?.productCategoryId == product?.productCategoryId; }); } static List<Product> _productCategories = <Product>[ new Product(1, "Natura More", "Natura More", 0, 0, 0), new Product(2, "Personal Care (Herbs & More)", "Personal Care", 0, 0, 0), new Product(3, "Home Care", "Home Care", 0, 0, 0), new Product(4, "Agriculture - Biofit", "Agriculture", 0, 0, 0) ]; static Product getProductCategory(int id) { return _productCategories[id]; } static List<Product> getProductCategories() { return _productCategories; } static List<Product> getProductsFromCategoryId(Product product) { if (product.name.isEmpty) { return getDefaultProducts(); } List<Product> products = []; switch (product.id) { case 1: products = getNaturaMore(); break; case 2: products = getHerbsAndMore(); break; case 3: products = getHomeCare(); break; case 4: products = getBioFit(); break; } return products; } static List<Product> getDefaultProducts() { return getNaturaMore(); } static List<Product> _naturaMore = <Product>[ new Product(1, "For Women French Venilla Flavour", "400 Gm", 1575, 1, 1), new Product(2, "For Men French Venilla Flavour", "400 Gm", 1700, 1, 1), new Product(3, "Plus French Venilla Flavour", "350 Gm", 1700, 1, 1), new Product(4, "Women Venilla", "350 Gm", 1400, 1, 1), new Product(5, "For Women Masala Milk Flavour", "350 Gm", 1400, 1, 1), new Product(6, "Chocolate C", "350 Gm", 1200, 1, 1), new Product(7, "Joint Care New", "30 Tab", 495, 1, 1), new Product(8, "Immune Plus", "60 Tab", 600, 1, 1), new Product(9, "Women's Wellness", "30 Tab", 600, 1, 1), new Product(10, "Eye Care", "30 Tab", 600, 1, 1), new Product(11, "De Stress", "30 Tab", 600, 1, 1), new Product(12, "Mens Wellness New", "30 Tab", 600, 1, 1), new Product(13, "Easy Detox", "30 Tab", 495, 1, 1), new Product(14, "Nutriheart", "30 Tab", 495, 1, 1), new Product(15, "Nutriliver", "30 Tab", 495, 1, 1), new Product(16, "Lifestyle Plus", "30 Tab", 450, 1, 1), ]; static List<Product> getNaturaMore() { return _naturaMore; } static List<Product> _herbsAndMore = <Product>[ new Product(1, "Vitamin Therapy Face Mist 100 New", "100 MLT", 280, 1, 2), new Product(2, "Herbs & More hygenic Pack", "1 Nos", 785, 1, 2), new Product( 3, "Herbs & More Vitamin Therapy Under Eye Gel", "25 Gm", 225, 1, 2), new Product(4, "Vitamin Therapy Face Wash New", "100 Gm", 220, 1, 2), new Product(5, "Herbs & More Vitamin Therapy Face Wash For Him", "100 Gm", 250, 1, 2), new Product(6, "Herbs & More Vitamin Therapy Face Wash For Her", "100 Gm", 250, 1, 2), new Product( 7, "Herbs & More Vitamin Therapy Night Cream", "50 Gm", 495, 1, 2), new Product( 8, "Herbs & More Vitamin Therapy Day Cream", "50 Gm", 495, 1, 2), new Product( 9, "Herbs & More Vitamin Therapy Lip Butter", "10 Gm", 180, 1, 2), new Product( 10, "Herbs & More Vitamin Therapy BB Cream", "30 Gm", 280, 1, 2), new Product(11, "Vitamin Therapy Shaving Cream", "75 Gm", 150, 1, 2), new Product(12, "Vitamin Therapy Hair Nutriment", "80 Gm", 360, 1, 2), new Product(13, "Herbs & More Vitamin Therapy Anti Dandruff Shampoo", "100 MLT", 220, 1, 2), new Product(14, "Herbs & More Vitamin Therapy Nourishing Shampoo", "100 MLT", 220, 1, 2), new Product( 15, "Herbs & More Vitamin Therapy Hair Serum", "100 MLT", 650, 1, 2), new Product(16, "Oral Cleanser", "100 MLT", 175, 1, 2), new Product( 17, "Herbs & More Vitamin Therapy Body Wash", "100 MLT", 220, 1, 2), new Product( 18, "Herbs & More Vitamin Therapy Body Lotion", "100 MLT", 275, 1, 2), new Product( 19, "Vitamin Therapy Moisturizing Soap 5 Pkt", "350 Gm", 400, 1, 2), new Product(20, "Vitamin Therapy Sunscreen", "100 Gm", 395, 1, 2), new Product(21, "Herbs & More Vitamin Therapy Professional Massage Cream", "100 Gm", 220, 1, 2), new Product( 22, "Herbs & More Vitamin Therapy Professional Cleansing Lotion", "100 Gm", 220, 1, 2), new Product(23, "Herbs & More Vitamin Therapy Professional Face Pack", "100 Gm", 220, 1, 2), new Product(24, "Herbs & More Vitamin Therapy Professional Massage Gel", "100 Gm", 220, 1, 2), new Product(25, "Herbs & More Vitamin Therapy Professional Face Scrub", "100 Gm", 220, 1, 2), new Product(26, "Herbs & More Vitamin Therapy Professional Face Toner", "100 Gm", 220, 1, 2), new Product(27, "Herbal Dental Paste", "125 Gm", 180, 1, 2), new Product(28, "Aloe Turmeric Cream", "75 Gm", 160, 1, 2), new Product(29, "Herbs & More Muscular Pain Cream", "50 Gm", 250, 1, 2), new Product(30, "Herbs & More Crackz Cream", "50 Gm", 170, 1, 2), new Product(31, "Anti Pimple Cream", "75 Gm", 150, 1, 2), new Product(32, "Neem Turmeric Anty Septic Cream", "75 Gm", 150, 1, 2) ]; static List<Product> getHerbsAndMore() { return _herbsAndMore; } static List<Product> _homeCare = <Product>[ new Product( 1, "Clean & More Fabric Wash and Conditioner", "500 MLT", 395, 1, 3), new Product( 2, "Clean & More multi purpose Home Cleaner", "500 MLT", 375, 1, 3) ]; static List<Product> getHomeCare() { return _homeCare; } static List<Product> _bioFit = <Product>[ new Product(1, "SHET", "1 Ltr", 1200, 1, 4), new Product(2, "STIM RICH", "1 Ltr", 1695, 1, 4), new Product(3, "STIM RICH", "500 MLT", 1000, 1, 4), new Product(4, "STIM RICH", "250 MLT", 600, 1, 4), new Product(5, "N", "1 Ltr", 600, 1, 4), new Product(6, "P", "1 Ltr", 600, 1, 4), new Product(7, "K", "1 Ltr", 600, 1, 4), new Product(8, "Bio99", "500 MLT", 1399, 1, 4), new Product(9, "Bio99", "250 MLT", 749, 1, 4), new Product(10, "Intact", "250 MLT", 1500, 1, 4), new Product(11, "Wrapup", "1 Ltr", 1500, 1, 4), new Product(12, "Pet Lotion", "175 MLT", 550, 1, 4), new Product(13, "CFC", "280 Gm", 325, 1, 4), new Product(14, "CFC Plus", "500 Gm", 650, 1, 4), new Product(15, "Aqua Culture", "500 MLT", 350, 1, 4), new Product(16, "Aqua Clear", "250 Gm", 600, 1, 4), new Product(17, "Aqua Feed", "250 Gm", 400, 1, 4) ]; static List<Product> getBioFit() { return _bioFit; } static void saveAllProducts(FirebaseFirestore instance) { saveProducts("ProductsNames/NaturaMore/Products", instance, Products.getNaturaMore()); saveProducts( "ProductsNames/BioFit/Products", instance, Products.getBioFit()); saveProducts( "ProductsNames/HomeCare/Products", instance, Products.getHomeCare()); saveProducts("ProductsNames/HerbsAndMore/Products", instance, Products.getHerbsAndMore()); } static void saveProducts( String path, FirebaseFirestore instance, List<Product> products) { final productRef = instance.collection(path).withConverter<Product>( fromFirestore: (snapshot, _) => Product.fromJson(snapshot.data()), toFirestore: (product, _) => product.toJson(), ); int i = 0; products.forEach((element) { i++; productRef .doc(i.toString()) .set(element) .then((value) => print("Product Added")) .catchError((error) => print("Failed to add Product: $error")); }); } static Future<QuerySnapshot?> getAllProducts( FirebaseFirestore instance, bool forceDownload) async { if (!forceDownload && await Preference.contains(SP_CATEGORY_IDS) && await Preference.contains(SP_PRODUCTS) && await getDurationInDays() < 3) { return null; } await Preference.setDateTime(SP_DT_REFRESH); final QuerySnapshot productNamesCollection = await instance.collection(FSC_PRODUCT_NAMES).get(); List<Product> productsList = []; var paths = []; List<Product> productDetails = []; productNamesCollection.docs.forEach((productName) async { paths .add(FSC_PRODUCT_NAMES + FS_S + productName.id + FS_S + FSC_PRODUCTS); productDetails .add(Product(productName[FS_ID], productName[FS_NAME], "", 0, 0, 0)); }); print("Fetching..."); Preference.setProducts(productDetails, SP_CATEGORY_IDS); paths.forEach((path) async { final QuerySnapshot productsResult = await instance.collection(path).get(); productsResult.docs.forEach((products) async { final productRef = instance.collection(path).withConverter<Product>( fromFirestore: (snapshot, _) => Product.fromJson(snapshot.data()), toFirestore: (product, _) => product.toJson(), ); productsList.add(await productRef .doc(products.id) .get() .then((snapshot) => snapshot.data()!)); productsList.forEach((element) { Preference.setProducts(productsList, SP_PRODUCTS); }); }); }); return productNamesCollection; } static Future<DisplayData?> getDisplayData( FirebaseFirestore instance, bool forceDownload) async { if (!forceDownload && await Preference.contains(SP_DISPLAY) && await getDurationInDays() < 3) { return await Preference.getDisplayData(); } print("Fetching..."); DocumentReference<Map<String, dynamic>> displayDataCollection = instance.collection(FS_DISPLAY_DATA).doc(FS_DISPLAY); final dataRef = displayDataCollection.withConverter<DisplayData>( fromFirestore: (snapshot, _) => DisplayData.fromJson(snapshot.data()), toFirestore: (data, _) => data.toJson()); final data = await dataRef.get(); if (data.data() != null) await Preference.setDisplayData(data.data()!); return data.data(); } static Future<int> getDurationInDays() async { DateTime oldDateTime = await Preference.getDateTime(SP_DT_REFRESH); DateTime timeNow = DateTime.now(); Duration timeDifference = timeNow.difference(oldDateTime); print("Day Dif: " + timeDifference.inDays.toString()); return timeDifference.inDays; } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/models/billing_info.dart
class BillingInfo { String _description = ""; String _number = ""; DateTime? _date; DateTime? _dueDate; String get description => _description; set description(String value) { _description = value; } String get number => _number; DateTime? get date => _date; DateTime? get dueDate => _dueDate; set number(String value) { _number = value; } set dueDate(DateTime? value) { _dueDate = value; } set date(DateTime? value) { _date = value; } BillingInfo(String description, String number, DateTime? date, {DateTime? dueDate}) { _description = description; _number = number; _date = date; _dueDate = dueDate; } BillingInfo.fromJson(dynamic json) { _description = json["description"]; _number = json["number"]; _date = DateTime.tryParse(json["date"]); _dueDate = DateTime.tryParse(json["dueDate"] ?? ""); } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; map["description"] = _description; map["number"] = _number; map["date"] = _date?.toIso8601String(); map["dueDate"] = _dueDate?.toIso8601String(); return map; } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/models/customer.dart
import 'dart:convert'; class User { String _name = ""; String _mobileNo = ""; String _cRefId = ""; String _address = ""; String _email = ""; String get name => _name; String get mobileNo => _mobileNo; String get cRefId => _cRefId; String get address => _address; String get email => _email; set name(String value) { _name = value; } set mobileNo(String value) { _mobileNo = value; } set email(String value) { _email = value; } set address(String value) { _address = value; } set cRefId(String value) { _cRefId = value; } User(String name, String mobileNo, String cRefId, String address, String email) { _name = name; _mobileNo = mobileNo; _cRefId = cRefId; _address = address; _email = email; } User.fromJson(dynamic json) { _name = json["name"]; _mobileNo = json["mobileNo"]; _cRefId = json["cRefId"]; _address = json["address"]; _email = json["email"]; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; map["name"] = _name; map["mobileNo"] = _mobileNo; map["cRefId"] = _cRefId; map["address"] = _address; map["email"] = _email; return map; } factory User.fromJsonSP(Map<String, dynamic> jsonData) { return User( jsonData['name'], jsonData['mobileNo'], jsonData['refId'], jsonData['address'], jsonData['email'], ); } static Map<String, dynamic> toJsonSP(User retailer) => { 'name': retailer.name, 'mobileNo': retailer.mobileNo, 'refId': retailer.cRefId, 'address': retailer.address, 'email': retailer.email, }; static String encode(User retailer) => json.encode(User.toJsonSP(retailer)); static User decode(String retailer) => User.fromJsonSP(json.decode(retailer)); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/models/billing.dart
import 'dart:convert'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/billing_info.dart'; import 'package:project_netsurf/common/models/price.dart'; import 'package:project_netsurf/common/models/product.dart'; /* { "billingInfo": { "description": "", "number": "", "date": "", "dueDate": "" }, "retailer": { "name": "", "mobileNo": "", "refId": "", "address": "", "email": "" }, "customer": { "name": "", "mobileNo": "", "cRefId": "", "address": "", "email": "" }, "productsSelected": [ { "id": 10, "name": "", "weight": "", "price": 10, "quantity": 100, "productCategoryId": 3 }, { "id": 10, "name": "", "weight": "", "price": 10, "quantity": 100, "productCategoryId": 3 } ], "price": { "price": 10, "discountAmt": 10, "finalAmt": 10 } } */ class Billing { BillingInfo? billingInfo; User? retailer; User? customer; List<Product?>? selectedProducts; Price? price; Billing(this.billingInfo, this.retailer, this.customer, this.selectedProducts, this.price); Billing.fromJson(dynamic json) { billingInfo = json["billingInfo"] != null ? BillingInfo.fromJson(json["billingInfo"]) : null; retailer = json["retailer"] != null ? User.fromJson(json["retailer"]) : null; customer = json["customer"] != null ? User.fromJson(json["customer"]) : null; if (json["selectedProducts"] != null) { selectedProducts = []; json["selectedProducts"].forEach((v) { selectedProducts?.add(Product.fromJson(v)); }); } price = json["price"] != null ? Price.fromJson(json["price"]) : null; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; if (billingInfo != null) { map["billingInfo"] = billingInfo?.toJson(); } if (retailer != null) { map["retailer"] = retailer?.toJson(); } if (customer != null) { map["customer"] = customer?.toJson(); } if (selectedProducts != null) { map["selectedProducts"] = selectedProducts?.map((v) => v?.toJson()).toList(); } if (price != null) { map["price"] = price?.toJson(); } return map; } static String encode(Billing billing) => json.encode(billing.toJson()); static Billing decode(String billing) => Billing.fromJson(json.decode(billing)); static String encodeList(List<Billing> products) => json.encode( products.map<Map<String, dynamic>>((bill) => bill.toJson()).toList(), ); static List<Billing> decodeList(String bills) => (json.decode(bills) as List<dynamic>) .map<Billing>((bill) => Billing.fromJson(bill)) .toList(); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/models/display_data.dart
/* { "Aemail": "[email protected]", "Alink": "https://codingcurve.in/", "Aname": "Author", "banner": "", "drawer": "", playlink : "" } */ import 'dart:convert'; class DisplayData { String _aemail = ""; String _alink = ""; String _aname = ""; String _banner = ""; String _drawer = ""; String _playlink = ""; List<String>? _bannerList; String get aemail => _aemail; String get alink => _alink; String get aname => _aname; String get banner => _banner; String get drawer => _drawer; String get playlink => _playlink; List<String>? get bannerList => _bannerList; DisplayData( {required String aemail, required String alink, required String aname, required String banner, required String drawer, required String playlink}) { _aemail = aemail; _alink = alink; _aname = aname; _banner = banner; _drawer = drawer; _playlink = playlink; } DisplayData.fromJson(dynamic json) { _aemail = json["Aemail"]; _alink = json["Alink"]; _aname = json["Aname"]; _banner = json["banner"]; _drawer = json["drawer"]; _playlink = json["playlink"]; _bannerList = json['bannerList'] != null ? json['bannerList'].cast<String>() : []; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; map["Aemail"] = _aemail; map["Alink"] = _alink; map["Aname"] = _aname; map["banner"] = _banner; map["drawer"] = _drawer; map["playlink"] = _playlink; map['bannerList'] = _bannerList; return map; } static String encode(DisplayData displayData) => json.encode(displayData.toJson()); static DisplayData decode(String displayData) => DisplayData.fromJson(json.decode(displayData)); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/models/product.dart
import 'dart:convert'; class Product { num _id = 0; String _name = ""; String _weight = ""; num _price = 0; num _quantity = 0; num _productCategoryId = 0; num get id => _id; String get name => _name; String get weight => _weight; num get price => _price; num get quantity => _quantity; num get productCategoryId => _productCategoryId; set id(num value) { _id = value; } set name(String value) { _name = value; } set productCategoryId(num value) { _productCategoryId = value; } set quantity(num value) { _quantity = value; } set price(num value) { _price = value; } set weight(String value) { _weight = value; } Product(num id, String name, String weight, num price, num quantity, num productCategoryId) { _id = id; _name = name; _weight = weight; _price = price; _quantity = quantity; _productCategoryId = productCategoryId; } Product.fromJson(dynamic json) { _id = json["id"]; _name = json["name"]; _weight = json["weight"]; _price = json["price"]; _quantity = json["quantity"]; _productCategoryId = json["productCategoryId"]; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; map["id"] = _id; map["name"] = _name; map["weight"] = _weight; map["price"] = _price; map["quantity"] = _quantity; map["productCategoryId"] = _productCategoryId; return map; } factory Product.fromJsonSP(Map<String, dynamic> jsonData) { return Product(jsonData['id'], jsonData['name'], jsonData['weight'], jsonData['price'], jsonData['quantity'], jsonData['productCategoryId']); } static Map<String, dynamic> toJsonSP(Product music) => { 'id': music.id, 'name': music.name, 'weight': music.weight, 'price': music.price, 'quantity': music.quantity, 'productCategoryId': music.productCategoryId }; static String encode(List<Product> products) => json.encode( products .map<Map<String, dynamic>>((music) => Product.toJsonSP(music)) .toList(), ); static List<Product> decode(String products) => (json.decode(products) as List<dynamic>) .map<Product>((item) => Product.fromJsonSP(item)) .toList(); String getDisplayName() { if (weight.isEmpty) return name; return name + " - " + weight; } String getDispPrice() { return price.ceil().toString(); } String getDispTotal() { final total = this.price * this.quantity; return total.ceil().toString(); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/models/price.dart
class Price { double _total = 0; double _discountAmt = 0; double _finalAmt = 0; double get total => _total; double get discountAmt => _discountAmt; double get finalAmt => _finalAmt; set total(double value) { _total = value; } set discountAmt(double value) { _discountAmt = value; } set finalAmt(double value) { _finalAmt = value; } Price(double total, double discountAmt, double finalAmt) { _total = total; _discountAmt = discountAmt; _finalAmt = finalAmt; } Price.fromJson(dynamic json) { _total = json["total"]; _discountAmt = json["discountAmt"]; _finalAmt = json["finalAmt"]; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; map["total"] = _total; map["discountAmt"] = _discountAmt; map["finalAmt"] = _finalAmt; return map; } String dispTotal() { return total.ceil().toString(); } String dispDiscAmt() { return discountAmt.ceil().toString(); } String dispFinalAmt() { return finalAmt.ceil().toString(); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/utils/common_utils.dart
import 'package:intl/intl.dart'; formatPrice(double price) => '\$ ${price.toStringAsFixed(2)}'; formatDate(DateTime date) => DateFormat('dd/MM/yyyy').format(date); dynamic myDateSerializer(dynamic object) { if (object is DateTime) { return object.toIso8601String(); } return object; }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/utils/pdf_api.dart
import 'dart:io'; import 'package:open_file_plus/open_file_plus.dart'; import 'package:path_provider/path_provider.dart'; import 'package:pdf/widgets.dart'; class PdfApi { static Future<File> saveDocument({ required String name, required Document pdf, }) async { final bytes = await pdf.save(); final dir = await getApplicationDocumentsDirectory(); final file = File('${dir.path}/$name'); await file.writeAsBytes(bytes); return file; } static Future openFile(File file) async { final url = file.path; await OpenFile.open(url); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/utils/billing_pdf.dart
import 'dart:io'; import 'package:pdf/pdf.dart'; import 'package:pdf/widgets.dart' as pw; import 'package:pdf/widgets.dart'; import 'package:project_netsurf/common/models/billing.dart'; import 'package:project_netsurf/common/models/billing_info.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/utils/common_utils.dart'; import 'package:project_netsurf/common/utils/pdf_api.dart'; class PdfInvoiceApi { static Future<File> generate(Billing invoice) async { final pdf = Document(); pdf.addPage(MultiPage( pageFormat: PdfPageFormat.a4, build: (context) => [ buildHeader(invoice), Divider(), buildTitle(invoice), buildInvoice(invoice), Divider(), buildTotal(invoice), ], footer: (context) => buildFooter(invoice), )); String billNumber = invoice.billingInfo?.number ?? ""; String mbNo = invoice.customer?.mobileNo ?? ""; String fileName = mbNo + "-" + billNumber + ".pdf"; return PdfApi.saveDocument(name: fileName, pdf: pdf); } static Widget buildHeader(Billing invoice) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 1 * PdfPageFormat.mm), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ if (invoice.customer != null) buildCustomerAddress(invoice.customer!), if (invoice.billingInfo != null) buildInvoiceInfo(invoice.billingInfo!), ], ), SizedBox(height: 0.8 * PdfPageFormat.mm), ], ); static Widget buildCustomerAddress(User customer) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Name: " + customer.name, style: TextStyle(fontWeight: FontWeight.bold)), SizedBox(height: 2), Text("Phone: " + customer.mobileNo), SizedBox(height: 2), Text(customer.email), if (customer.cRefId.isNotEmpty) SizedBox(height: 2), if (customer.cRefId.isNotEmpty) Text("Ref: " + customer.cRefId, style: TextStyle(fontWeight: FontWeight.bold)), ], ); static Widget buildInvoiceInfo(BillingInfo info) { // final paymentTerms = '${info.dueDate.difference(info.date).inDays} days'; final titles = <String>[ 'Serial No:', 'Date:', // 'Payment Terms:', // 'Due Date:' ]; final data = <String>[ info.number, if (info.date != null) formatDate(info.date!), // paymentTerms, // formatDate(info.dueDate), ]; return Column( crossAxisAlignment: CrossAxisAlignment.end, children: List.generate(titles.length, (index) { final title = titles[index]; final value = data[index]; return buildText(title: title, value: value, width: 200); }), ); } static Widget buildSupplierAddress(User retailer) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Distributor", style: TextStyle(fontWeight: FontWeight.bold)), SizedBox(height: 1 * PdfPageFormat.mm), Text(retailer.name), SizedBox(height: 1 * PdfPageFormat.mm), Text(retailer.mobileNo), ], ); static Widget buildTitle(Billing invoice) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 0.8 * PdfPageFormat.mm), pw.Center( child: Text( 'ESTIMATE', textAlign: pw.TextAlign.center, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ), if (invoice.billingInfo != null && invoice.billingInfo!.description.isNotEmpty) SizedBox(height: 0.8 * PdfPageFormat.cm), if (invoice.billingInfo != null && invoice.billingInfo!.description.isNotEmpty) Text(invoice.billingInfo!.description), SizedBox(height: 0.8 * PdfPageFormat.mm), ], ); static Widget buildInvoice(Billing invoice) { final headers = ['Title', 'Qty', 'MRP', 'Total']; final data = invoice.selectedProducts?.map((item) { return [ item?.name, '${item?.quantity}', ' ${item?.getDispPrice()}', ' ${item?.getDispTotal()}', ]; }).toList(); if (data == null) return Text("NA"); return Table.fromTextArray( headers: headers, headerAlignment: Alignment.centerRight, data: data, border: null, headerStyle: TextStyle(fontWeight: FontWeight.bold), headerDecoration: BoxDecoration(color: PdfColors.grey300), cellHeight: 30, cellAlignments: { 0: Alignment.centerLeft, 1: Alignment.centerRight, 2: Alignment.centerRight, 3: Alignment.centerRight, }, ); } static Widget buildTotal(Billing invoice) { final netTotal = invoice.price?.dispTotal() ?? "NA"; final discount = invoice.price?.dispDiscAmt() ?? "NA"; final total = invoice.price?.dispFinalAmt() ?? "NA"; return Container( alignment: Alignment.centerRight, child: Row( children: [ Spacer(flex: 6), Expanded( flex: 4, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ buildText( title: 'Total', // TODO: price value: netTotal, unite: true, ), buildText( title: 'Discount', // TODO: price // value: Utils.formatPrice(discount), value: discount, unite: true, ), Divider(), buildText( title: 'Total amount', titleStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, ), // TODO: price // value: Utils.formatPrice(total), value: total, unite: true, ), SizedBox(height: 2 * PdfPageFormat.mm), Container(height: 1, color: PdfColors.grey400), SizedBox(height: 0.5 * PdfPageFormat.mm), Container(height: 1, color: PdfColors.grey400), ], ), ), ], ), ); } static Widget buildFooter(Billing invoice) => Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Divider(), SizedBox(height: 1.3 * PdfPageFormat.mm), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (invoice.retailer != null) buildSupplierAddress(invoice.retailer!), // Barcode Removed for now // Container( // height: 50, // width: 50, // child: BarcodeWidget( // barcode: Barcode.qrCode(), // data: invoice.info.number, // ), // ), ], ), SizedBox(height: 2 * PdfPageFormat.mm) // TODO: Payment info // SizedBox(height: 1 * PdfPageFormat.mm), // buildSimpleText(title: 'Paypal', value: invoice.retailer.paymentInfo), ], ); static buildSimpleText({ required String title, required String value, }) { final style = TextStyle(fontWeight: FontWeight.bold); return pw.Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: pw.CrossAxisAlignment.end, children: [ Text(title, style: style), SizedBox(width: 2 * PdfPageFormat.mm), Text(value), ], ); } static buildText({ required String title, required String value, double width = double.infinity, TextStyle? titleStyle, bool unite = false, }) { final style = titleStyle ?? TextStyle(fontWeight: FontWeight.bold); return Container( width: width, child: Expanded( child: Row( mainAxisAlignment: unite ? MainAxisAlignment.spaceBetween : MainAxisAlignment.spaceBetween, children: [ Text(title, style: style), Text(" " + value, style: unite ? style : null), ], ), ), ); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/edittext.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class EditText extends StatelessWidget { String? editTextName = ""; String? initTextValue = ""; TextInputType? type = TextInputType.name; bool required = false; bool? isPhone = false; int? maxline = 1; Function(String)? onText; TextEditingController? _controller; Function()? onTap; EditText( {Key? key, this.editTextName, this.type, required this.required, this.maxline, this.onText, this.onTap, this.initTextValue, this.isPhone}) : super(key: key); @override Widget build(BuildContext context) { _controller = TextEditingController(); if (isPhone == null) { isPhone = false; } return Container( constraints: BoxConstraints(minHeight: 55, minWidth: double.infinity), padding: EdgeInsets.symmetric(horizontal: 26), child: TextFormField( controller: _controller, textCapitalization: TextCapitalization.characters, maxLines: maxline, decoration: InputDecoration( labelText: editTextName ?? "NA" + (required ? " \*" : ""), border: OutlineInputBorder( borderRadius: BorderRadius.circular(25.0), borderSide: BorderSide(), ), ), inputFormatters: [ if (isPhone ?? false) FilteringTextInputFormatter.allow((RegExp("[.0-9]"))), ], maxLength: isPhone ?? false ? 10 : null, keyboardType: type, onChanged: (value) { onText?.call(_controller?.text ?? "NA"); }, onTap: () { onTap?.call(); }, ), ); } } class InputText extends StatelessWidget { String? keyText = ""; int? maxline = 1; Function(String?)? onText; TextEditingController? controller; InputText( {Key? key, this.maxline, this.onText, this.keyText, this.controller}) : super(key: key); @override Widget build(BuildContext context) { return TextFormField( cursorWidth: 1.3, controller: controller, textAlign: TextAlign.center, inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly ], style: TextStyle( fontSize: 15, ), textAlignVertical: TextAlignVertical.center, decoration: InputDecoration( contentPadding: EdgeInsets.fromLTRB(0, 0, 0, 19), ), keyboardType: TextInputType.number, onChanged: (value) { onText?.call(controller?.text); }, ); } } class CustomButton extends StatelessWidget { String? buttonText = ""; Function? onClick; CustomButton({Key? key, this.buttonText, this.onClick}) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: new EdgeInsets.symmetric(vertical: 2, horizontal: 16), width: MediaQuery.of(context).size.width, child: ElevatedButton( style: ElevatedButton.styleFrom( elevation: 2, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0)), fixedSize: Size(120, 48), ), child: Text( buttonText ?? "", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, height: 1.3, letterSpacing: 1.1), ), onPressed: () { onClick?.call(); }, )); } } class SideButtons extends StatelessWidget { String? buttonText = ""; Function? onClick; SideButtons({Key? key, this.buttonText, this.onClick}) : super(key: key); @override Widget build(BuildContext context) { return ElevatedButton( style: ElevatedButton.styleFrom( elevation: 2, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)), fixedSize: Size(120, 48), ), child: Text( buttonText ?? "NA", textAlign: TextAlign.center, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, height: 1.3, letterSpacing: 1.1), ), onPressed: () { onClick?.call(); }, ); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/loader.dart
import 'package:flutter/material.dart'; Widget CustomLoader() { return Center(child: RefreshProgressIndicator()); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/unused.dart
import 'package:flutter/material.dart'; void elevatedButtonAdd() { ElevatedButton( style: ElevatedButton.styleFrom( foregroundColor: Colors.white, elevation: 1, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)), minimumSize: Size(15, 40), ), child: Icon(Icons.add), onPressed: () { // setState(() { // if (selectedProducts != null) // selectedProducts[index].quantity++; // calculateTotal(); // }); }, ); } void elevatedButtonSub() { ElevatedButton( style: ElevatedButton.styleFrom( foregroundColor: Colors.white, elevation: 1, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)), minimumSize: Size(15, 40), ), child: Icon(Icons.remove), onPressed: () { // setState(() { // if (selectedProducts[index].quantity > 1) // selectedProducts[index].quantity--; // calculateTotal(); // }); }, ); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/error.dart
import 'package:flutter/material.dart'; import 'package:flutter_phoenix/flutter_phoenix.dart'; import 'package:project_netsurf/common/sp_constants.dart'; import 'package:project_netsurf/common/sp_utils.dart'; import 'package:project_netsurf/common/ui/edittext.dart'; import '../../di/singletons.dart'; void showLogoutErrorDialog(BuildContext buildContext) { showDialog( context: buildContext, builder: (BuildContext context) { return AlertDialog( content: Padding( padding: EdgeInsets.only(top: 8), child: Text("Are you sure you want to logout?")), actions: <Widget>[ CustomButton( buttonText: "Logout", onClick: () async { Navigator.of(context).pop(); if (await Preference.remove(SP_RETAILER)){ await setupRetailerDetails(); await Phoenix.rebirth(buildContext); } }, ), ], ); }, ); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/theme.dart
import 'package:flutter/material.dart'; import '../contants.dart'; ThemeData NetsurfAppTheme() { return ThemeData( textTheme: TextTheme( displayLarge: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold), titleLarge: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic), bodyMedium: TextStyle(fontSize: 14.0), ), appBarTheme: AppBarTheme( centerTitle: true, toolbarTextStyle: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), titleTextStyle: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), color: const Color(PRIMARY_COLOR), ), primaryColor: Color(PRIMARY_COLOR), hintColor: Color(SECONDARY_COLOR), primarySwatch: MaterialColor(SECONDARY_COLOR, THEME_COLOR), ); } Widget AppContainer(context, child) { return SafeArea( child: Container( height: MediaQuery.of(context).size.height, decoration: BoxDecoration(color: Colors.white), child: child, ), ); }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/select_product_bottomsheet.dart
import 'package:flutter/material.dart'; import 'package:project_netsurf/common/models/product.dart'; import 'package:project_netsurf/common/ui/edittext.dart'; void selectProductsBottomSheet( BuildContext context, GlobalKey<ScaffoldState> scaffoldKey, List<Product> productList, TextEditingController textController, Function(BuildContext context, Product) onClick) { List<Product>? _listAfterSearch; print("Recreated"); showModalBottomSheet( context: context, isScrollControlled: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)), ), builder: (context) { return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return DraggableScrollableActuator( child: DraggableScrollableSheet( expand: false, builder: (BuildContext context, ScrollController scrollController) { return Column( children: <Widget>[ Padding( padding: EdgeInsets.all(16), child: Row( children: <Widget>[ Expanded( child: TextField( controller: textController, decoration: InputDecoration( contentPadding: EdgeInsets.all(8), border: new OutlineInputBorder( borderRadius: new BorderRadius.circular(15.0), borderSide: new BorderSide(), ), prefixIcon: Icon(Icons.search), ), onChanged: (value) { setState(() { _listAfterSearch = _buildSearchList(value, productList); }); })), IconButton( icon: Icon(Icons.close), onPressed: () { setState(() { textController.clear(); Navigator.pop(context); }); }), ], ), ), if (_getListViewItemCount(_listAfterSearch, productList) < 1) Text("No more products to add!"), Expanded( child: ListView.separated( controller: scrollController, itemCount: _getListViewItemCount( _listAfterSearch, productList), separatorBuilder: (context, int) { return Divider( indent: 10, endIndent: 10, ); }, itemBuilder: (context, index) { return InkWell( child: _getProductListAndWidget( _listAfterSearch, productList, index), onTap: () { setState(() { Product selectedProduct = _getClickedProduct( _listAfterSearch, productList, index); onClick.call(context, selectedProduct); productList.remove(selectedProduct); }); }, ); }, ), ), Padding( padding: EdgeInsets.only(bottom: 8, top: 8), child: CustomButton( buttonText: "DONE", onClick: () { Navigator.of(context).pop(); }, ), ) ], ); }, ), ); }); }); } Widget _showBottomSheetWithSearch(int index, List<Product> productList) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Container( padding: EdgeInsets.only(left: 16, top: 8, right: 16, bottom: 8), child: Text(productList[index].getDisplayName(), style: TextStyle(fontSize: 15, height: 1.3), textAlign: TextAlign.start), )), if (productList[index].price != 0) Container( padding: EdgeInsets.only(left: 16, top: 8, right: 16, bottom: 8), child: Text(productList[index].price.toString(), style: TextStyle(fontSize: 15), textAlign: TextAlign.end), ), ], ); } List<Product> _buildSearchList( String userSearchTerm, List<Product> productList) { List<Product> _searchList = []; for (int i = 0; i < productList.length; i++) { String name = productList[i].getDisplayName(); if (name.toLowerCase().contains(userSearchTerm.toLowerCase())) { _searchList.add(productList[i]); } } return _searchList; } Product _getClickedProduct( List<Product>? _listAfterSearch, List<Product> productList, int index) { if ((_listAfterSearch != null && _listAfterSearch.isNotEmpty)) { return _listAfterSearch[index]; } else { return productList[index]; } } int _getListViewItemCount( List<Product>? _listAfterSearch, List<Product> productList) { if ((_listAfterSearch != null && _listAfterSearch.isNotEmpty)) { return _listAfterSearch.length; } else { return productList.length; } } Widget _getProductListAndWidget( List<Product>? _listAfterSearch, List<Product> productList, int index) { if ((_listAfterSearch != null && _listAfterSearch.isNotEmpty)) { return _showBottomSheetWithSearch(index, _listAfterSearch); } else { return _showBottomSheetWithSearch(index, productList); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib/common
mirrored_repositories/Netsurf-Flutter-App/lib/common/ui/select_category_bottomsheet.dart
import 'package:flutter/material.dart'; import 'package:project_netsurf/common/models/product.dart'; void showSelectCategoryBottomSheet( BuildContext context, GlobalKey<ScaffoldState> scaffoldKey, List<Product?> productList, TextEditingController textController, Function(Product?) onClick) { showModalBottomSheet( context: context, isScrollControlled: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)), ), builder: (context) { return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return DraggableScrollableActuator( child: DraggableScrollableSheet( expand: false, builder: (BuildContext context, ScrollController scrollController) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 26), Padding( padding: EdgeInsets.only(left: 16), child: Text( "Select Category", textAlign: TextAlign.start, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16), ), ), SizedBox(height: 8), Expanded( child: ListView.separated( controller: scrollController, itemCount: productList.length, separatorBuilder: (context, int) { return Divider( indent: 10, endIndent: 10, ); }, itemBuilder: (context, index) { return InkWell( child: _showBottomSheetWithSearch( index, productList), onTap: () { onClick.call(productList[index]); Navigator.of(context).pop(); }); }, ), ) ], ); }, ), ); }); }); } Widget _showBottomSheetWithSearch(int index, List<Product?> productList) { return Container( padding: EdgeInsets.only(left: 16, top: 8, right: 16, bottom: 8), child: Text(productList[index]?.getDisplayName() ?? "NA", style: TextStyle( fontSize: 15, height: 1.5, ), textAlign: TextAlign.start), ); }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/ui/select_products.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:get_it/get_it.dart'; import 'package:project_netsurf/common/analytics.dart'; import 'package:project_netsurf/common/contants.dart'; import 'package:project_netsurf/common/models/billing.dart'; import 'package:project_netsurf/common/models/billing_info.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/price.dart'; import 'package:project_netsurf/common/ui/select_product_bottomsheet.dart'; import 'package:project_netsurf/common/ui/edittext.dart'; import 'package:project_netsurf/common/models/product.dart'; import 'package:project_netsurf/common/product_constant.dart'; import 'package:project_netsurf/common/ui/select_category_bottomsheet.dart'; import 'package:project_netsurf/ui/biller.dart'; class SelectProductsPage extends StatefulWidget { final String? title; final User customerData; final User retailer; final List<Product?> allProducts; final List<Product?> allCategories; final String billingIdVal; SelectProductsPage( {Key? key, this.title, required this.customerData, required this.allProducts, required this.allCategories, required this.retailer, required this.billingIdVal}) : super(key: key); @override SelectProductsPageState createState() => SelectProductsPageState(); } class SelectProductsPageState extends State<SelectProductsPage> { static FirebaseAnalytics analytics = GetIt.I.get<FirebaseAnalytics>(); List<TextEditingController> _controllers = []; final _scaffoldKey = GlobalKey<ScaffoldState>(); final TextEditingController discountedPriceController = new TextEditingController(); final TextEditingController categoryTextController = new TextEditingController(); final TextEditingController itemTextController = new TextEditingController(); final TextEditingController discountController = new TextEditingController(); Price price = Price(0, 0, 0); List<Product?> selectedProducts = []; Product? selectedCategory; bool isFirstTime = true; @override void initState() { super.initState(); print("Selected customer: " + widget.customerData.name); widget.allCategories.sort((a, b) => a!.id.compareTo(b!.id)); selectedCategory = Products.getProductCategorys(widget.allCategories, 1); widget.allCategories.forEach((element) { if (element != null) print("Products Names: " + element.name); }); widget.allProducts.forEach((element) { if (element != null) print("Products: " + element.name); }); } @override Widget build(BuildContext context) { analytics.setCurrentScreen(screenName: CT_PRODUCT_SELECTION); return Scaffold( key: _scaffoldKey, appBar: AppBar( title: Text(APP_NAME, textAlign: TextAlign.center), centerTitle: true, ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ addProductLists(), if (selectedProducts.isEmpty) addInstruction(), Row( children: [ selectProductList(widget.allCategories), selectItemFromProducts(widget.allProducts), ], ), showDoneButton(), SizedBox(height: 5), ], ), ); } Widget addProductLists() { return Expanded( child: Card( child: Container( padding: EdgeInsets.all(5), child: ListView.separated( shrinkWrap: true, physics: ClampingScrollPhysics(), itemCount: selectedProducts.length, separatorBuilder: (context, int) { return Container( padding: EdgeInsets.only(left: 5, top: 0, right: 5, bottom: 0), child: Divider( thickness: 1, height: 6, ), ); }, itemBuilder: (context, index) { _controllers.add(new TextEditingController(text: "1")); return Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Container( padding: EdgeInsets.only( left: 0, top: 8, right: 5, bottom: 8), child: Text( selectedProducts[index]?.getDisplayName() ?? "NA", style: TextStyle( color: Colors.black, fontSize: 14, height: 1.3), textAlign: TextAlign.start), ), ), Container( width: 80, child: Center( child: Text(itemPrice(index), style: TextStyle(color: Colors.black, fontSize: 15), textAlign: TextAlign.left), ), ), Container( padding: EdgeInsets.only(right: 3), width: 80, height: 30, child: InputText( controller: _controllers[index], onText: (value) { setState(() { if (value != null) { print("VALUE: " + value); if (value.isEmpty) { selectedProducts[index]?.quantity = 0; selectedCategory?.quantity = 0; _controllers[index].clear(); } else { int quant = double.parse(value).ceil(); if (quant > 0) { selectedProducts[index]?.quantity = quant; selectedCategory?.quantity = quant; } else { selectedProducts[index]?.quantity = 0; selectedCategory?.quantity = 0; _controllers[index].clear(); } } } calculateTotal(); finalAmountReset(); }); }, ), ), IconButton( onPressed: () { setState(() { selectedProducts.remove(selectedProducts[index]); calculateTotal(); finalAmountReset(); }); }, icon: Icon(Icons.delete_forever_rounded), color: Colors.black87) ], )); }), ), ), ); } Widget addInstruction() { return Padding( padding: EdgeInsets.only(left: 26, right: 26), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Padding( padding: EdgeInsets.only(right: 16, top: 15, bottom: 15), child: Text( "Button below is to select a category, click again to change it.", textAlign: TextAlign.left, style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold), ), ), ), Container(height: 80, child: VerticalDivider(color: Colors.black87)), Expanded( child: Padding( padding: EdgeInsets.only(left: 16, top: 15, bottom: 15), child: Text( "Button below is to add many different products as required.", textAlign: TextAlign.left, style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold), ), ), ), ], ), ); } Widget selectProductList(List<Product?> allCategories) { final buttonText = isFirstTime || selectedCategory?.name == null || selectedCategory!.name.isEmpty ? "Select Category" : selectedCategory?.name; isFirstTime = false; return Expanded( child: Container( padding: new EdgeInsets.only(left: 16, top: 8, bottom: 5, right: 8), child: SideButtons( buttonText: buttonText, onClick: () { showSelectCategoryBottomSheet( context, _scaffoldKey, allCategories, categoryTextController, (product) { if (product != null) { setState(() { selectedCategory = product; calculateTotal(); }); } }); }), ), ); } Widget selectItemFromProducts(List<Product?> allproducts) { return Expanded( child: Container( padding: new EdgeInsets.only(left: 8, top: 8, bottom: 5, right: 16), child: SideButtons( buttonText: _getButtonText(), onClick: () { selectProductsBottomSheet( context, _scaffoldKey, Products.getProductsFromCategorysIds( allproducts, selectedCategory, selectedProducts), itemTextController, (context, product) { setState(() { finalAmountReset(); if (!selectedProducts.contains(product) && !productPresent(product)) { selectedProducts.add(product); } else { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Item is already in the list!"), duration: const Duration(seconds: 3), behavior: SnackBarBehavior.floating, )); } calculateTotal(); }); }); }, ), ), ); } @override void dispose() { super.dispose(); } String _getButtonText() { if (selectedCategory != null && selectedCategory!.name.isNotEmpty) { return "Add products"; } else { return "Select product category first"; } } String itemPrice(int index) { if (selectedProducts[index] == null) return ""; return RUPEE_SYMBOL + " " + (selectedProducts[index]!.price * selectedProducts[index]!.quantity) .ceil() .toString(); } Billing createBilling() { BillingInfo billingInfo = BillingInfo("", widget.billingIdVal, DateTime.now()); Billing billing = Billing(billingInfo, widget.retailer, widget.customerData, selectedProducts, price); print("Final" + price.finalAmt.toString()); return billing; } void modalBottomSheetColor(BuildContext context) { showModalBottomSheet( context: context, isScrollControlled: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)), ), builder: (builder) { return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return SingleChildScrollView( physics: ClampingScrollPhysics(), child: Container( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), margin: EdgeInsets.only(left: 8, top: 26, right: 8, bottom: 8), child: Column( children: [ totalPrice(), discountPrice(setState), SizedBox(height: 5), // billingId(), CustomButton( buttonText: RUPEE_SYMBOL + " " + price.dispFinalAmt(), onClick: () async { if (selectedProducts.isNotEmpty && price.total > 0) { Navigator.push( context, new MaterialPageRoute( builder: (__) => new BillerPage( billing: createBilling(), isAlreadySaved: false, ), ), ); } else { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Add items before moving ahead."), duration: const Duration(seconds: 2), behavior: SnackBarBehavior.floating, )); } }, ), ], ), ), ); }); }, ); } Widget totalPrice() { return Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(left: 12), child: Text( "Total " + RUPEE_SYMBOL + " " + price.dispTotal(), textAlign: TextAlign.center, style: TextStyle( color: Colors.grey[800], fontWeight: FontWeight.bold, fontSize: 15), ), ) ], ); } Widget billingId() { return Padding( padding: EdgeInsets.only(left: 12), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "Bill Id ", textAlign: TextAlign.start, style: TextStyle( color: Colors.grey[800], fontWeight: FontWeight.bold, fontSize: 15), ), Padding( padding: EdgeInsets.only(left: 1), child: Container( width: 70, child: TextField( cursorWidth: 1.3, textAlign: TextAlign.start, inputFormatters: [ FilteringTextInputFormatter.allow((RegExp("[.0-9]"))), ], style: TextStyle( fontSize: 15, ), cursorColor: Colors.black, keyboardType: TextInputType.number, onChanged: (value) { if (value.isNotEmpty) { // TO DO widget.billingIdVal = double.parse(value); } }, ), ), ), ], ), ); } Widget discountPrice(StateSetter setState) { return Padding( padding: EdgeInsets.only(left: 12), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "Discount ", textAlign: TextAlign.start, style: TextStyle( color: Colors.grey[800], fontWeight: FontWeight.bold, fontSize: 15), ), Text( "% ", textAlign: TextAlign.start, style: TextStyle(color: Colors.grey[800], fontSize: 15), ), Container( width: 65, child: TextFormField( cursorWidth: 1.3, controller: discountController, textAlign: TextAlign.start, onTap: () { setState(() { finalAmountReset(); }); }, inputFormatters: [ FilteringTextInputFormatter.allow((RegExp("[.0-9]"))), ], style: TextStyle( fontSize: 15, ), cursorColor: Colors.black, keyboardType: TextInputType.number, onChanged: (value) { setState(() { if (value.isNotEmpty) { double discount = double.parse(value); price.discountAmt = 0; if (discount > 0) { price.discountAmt = price.total * (discount / 100); price.finalAmt = price.total - price.discountAmt; if (price.finalAmt < 0) { price.finalAmt = 0; } } } else { price.discountAmt = 0; price.finalAmt = price.total; } }); }, ), ), Text( RUPEE_SYMBOL + " ", textAlign: TextAlign.start, style: TextStyle(color: Colors.grey[800], fontSize: 15), ), Container( width: 60, child: TextFormField( cursorWidth: 1.3, controller: discountedPriceController, textAlign: TextAlign.start, onTap: () { setState(() { finalAmountReset(); }); }, inputFormatters: [ FilteringTextInputFormatter.allow((RegExp("[.0-9]"))), ], style: TextStyle( fontSize: 15, ), cursorColor: Colors.black, keyboardType: TextInputType.number, onChanged: (value) { setState(() { if (value.isNotEmpty) { double discountPrice = double.parse(value); price.discountAmt = 0; if (discountPrice > 0) { price.discountAmt = discountPrice; price.finalAmt = price.total - discountPrice; if (price.finalAmt < 0) { price.finalAmt = 0; } } } else { price.discountAmt = 0; price.finalAmt = price.total; } }); }, ), ), ], ), ); } Widget showDoneButton() { return CustomButton( buttonText: RUPEE_SYMBOL + " " + price.dispTotal(), onClick: () async { if (selectedProducts.isNotEmpty && price.total > 0) { modalBottomSheetColor(context); } else { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Add items before moving ahead."), duration: const Duration(seconds: 2), behavior: SnackBarBehavior.floating, )); } }, ); } void calculateTotal() { price.total = 0; for (var item in selectedProducts) { print("TOTAL ${item?.price.toString()} Quant: ${item?.quantity}"); if (item == null) return; print("TOTALss ${item.price * item.quantity}"); price.total += item.price * item.quantity; price.finalAmt = price.total; } } void finalAmountReset() { price.finalAmt = price.total; discountController.clear(); discountedPriceController.clear(); } bool productPresent(Product product) { return selectedProducts.any((element) { return element?.id == product.id && element?.productCategoryId == product.productCategoryId; }); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/ui/biller.dart
import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_phoenix/flutter_phoenix.dart'; import 'package:get_it/get_it.dart'; import 'package:intl/intl.dart'; import 'package:project_netsurf/common/analytics.dart'; import 'package:project_netsurf/common/contants.dart'; import 'package:project_netsurf/common/models/billing.dart'; import 'package:project_netsurf/common/models/billing_info.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/sp_constants.dart'; import 'package:project_netsurf/common/sp_utils.dart'; import 'package:project_netsurf/common/ui/edittext.dart'; import 'package:project_netsurf/common/utils/billing_pdf.dart'; import 'package:project_netsurf/common/utils/common_utils.dart'; import 'package:project_netsurf/common/utils/pdf_api.dart'; class BillerPage extends StatefulWidget { final bool isAlreadySaved; final Billing billing; BillerPage({Key? key, required this.billing, this.isAlreadySaved = true}) : super(key: key); @override HomePageState createState() => HomePageState(); } class HomePageState extends State<BillerPage> { static FirebaseAnalytics analytics = GetIt.I.get<FirebaseAnalytics>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { analytics.setCurrentScreen(screenName: CT_BILLING); return Scaffold( key: _scaffoldKey, appBar: AppBar( title: Text(APP_NAME, textAlign: TextAlign.center), centerTitle: true, ), body: Container( padding: EdgeInsets.all(1), child: Card( child: Container( child: Column( children: [ buildHeader(widget.billing), buildTitle(widget.billing), SizedBox(height: 5), buildInvoice(widget.billing), Divider(), buildTotal(context, widget.billing, widget.isAlreadySaved), ], ), ), ), )); } static Widget buildHeader(Billing invoice) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 16), Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (invoice.customer != null) Expanded(child: buildCustomerAddress(invoice.customer!)), if (invoice.billingInfo != null) Expanded(child: buildInvoiceInfo(invoice.billingInfo!)), ], ), ], ); static Widget buildCustomerAddress(User customer) => Container( padding: EdgeInsets.only(left: 16), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("" + customer.name, style: TextStyle(fontWeight: FontWeight.bold)), SizedBox(height: 2), Text("" + customer.mobileNo), if (customer.email.isNotEmpty) SizedBox(height: 2), if (customer.email.isNotEmpty) Text("" + customer.email), SizedBox(height: 2), Text("" + customer.cRefId), ], ), ); static Widget buildInvoiceInfo(BillingInfo info) { // final paymentTerms = '${info.dueDate.difference(info.date).inDays} days'; final titles = <String>[ 'Serial No:', 'Date:', // 'Payment Terms:', // 'Due Date:' ]; final data = <String>[ info.number, if (info.date != null) formatDate(info.date!), // paymentTerms, // formatDate(info.dueDate), ]; return Container( padding: EdgeInsets.only(right: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: List.generate(titles.length, (index) { final title = titles[index]; final value = data[index]; return buildText(title: title, value: value, width: 200); }), ), ); } static Widget buildTitle(Billing invoice) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'ESTIMATE', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), ], ); static Widget buildInvoice(Billing invoice) { final headers = ['TITLE', 'QTY', 'MRP', 'TOTAL']; final data = invoice.selectedProducts?.map((item) { return [ item?.name, '${item?.quantity}', ' ${item?.getDispPrice()}', ' ${item?.getDispTotal()}', ]; }).toList(); if (data == null) return Text("NA"); data.insert(0, headers); return Expanded( child: Container( padding: EdgeInsets.only(left: 5, right: 5), child: ListView.separated( physics: ClampingScrollPhysics(), shrinkWrap: true, itemCount: data.length, separatorBuilder: (context, int) { return Container( padding: EdgeInsets.only(left: 5, top: 0, right: 5, bottom: 0), child: Divider( thickness: 1, height: 4, ), ); }, itemBuilder: (context, index) { return Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( width: 40, child: Center( child: Text(index > 0 ? (index).toString() : "", style: TextStyle(color: Colors.black, fontSize: 15), textAlign: TextAlign.left), ), ), Expanded( child: Container( padding: EdgeInsets.only(left: 0, top: 8, right: 5, bottom: 8), child: Text(data[index][0] ?? "NA", style: TextStyle( color: Colors.black, fontSize: 14, height: 1.3), textAlign: TextAlign.start), ), ), Container( width: 45, child: Center( child: Text(data[index][1] ?? "NA", style: TextStyle(color: Colors.black, fontSize: 15), textAlign: TextAlign.left), ), ), Container( width: 50, child: Center( child: Text(data[index][2] ?? "NA", style: TextStyle(color: Colors.black, fontSize: 15), textAlign: TextAlign.left), ), ), Container( width: 65, child: Center( child: Text(data[index][3] ?? "NA", style: TextStyle(color: Colors.black, fontSize: 15), textAlign: TextAlign.left), ), ), ], )); }), ), ); } static Widget buildTotal( BuildContext context, Billing invoice, bool isAlreadySaved) { final netTotal = invoice.price?.dispTotal() ?? "NA"; final discount = invoice.price?.dispDiscAmt() ?? "NA"; final total = invoice.price?.dispFinalAmt() ?? "NA"; return Container( alignment: Alignment.centerLeft, child: Row( children: [ Expanded( child: Container( padding: EdgeInsets.only(left: 5, right: 5, bottom: 2), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ buildText( title: TOTAL_AMOUNT, titleStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.normal, ), // TODO: price value: netTotal, unite: true, ), buildText( title: DISCOUNT, titleStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.normal, ), // TODO: price // value: Utils.formatPrice(discount), value: discount, unite: true, ), Divider(height: 5), buildText( title: FINAL_AMOUNT, titleStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, ), // TODO: price // value: Utils.formatPrice(total), value: total, unite: true, ), SizedBox(height: 3), ], ), ), ), Expanded( child: CustomButton( buttonText: isAlreadySaved ? "Share PDF" : "SAVE", onClick: () async { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; var formatter = new DateFormat('dd/MM/yyyy – HH:mm'); String formattedDate = ""; if (invoice.billingInfo != null && invoice.billingInfo!.date != null) { formattedDate = formatter.format(invoice.billingInfo!.date!); print("Formated Date" + formattedDate); } analytics.setCurrentScreen(screenName: CT_PDF_CREATION); analytics.logEvent( name: CT_SAVE_BILL, parameters: <String, dynamic>{ CT_DISTRIBUTOR_NAME: invoice.retailer?.name, CT_DISTRIBUTOR_PH_NO: invoice.retailer?.mobileNo, CT_CUSTOMER_NAME: invoice.customer?.name, CT_CUSTOMER_PH_NO: invoice.customer?.mobileNo, CT_BILLING_NO: invoice.billingInfo?.number, CT_BILLING_DATE: formattedDate, CT_MODEL_NAME: androidInfo.model, CT_MANUFACTURER_NAME: androidInfo.manufacturer, CT_ANDROID_VERSION_STRING: androidInfo.version.release, CT_ANDROID_VERSION: androidInfo.version.baseOS }, ); if (!isAlreadySaved) await Preference.setItem( SP_BILLING_ID, invoice.billingInfo?.number ?? ""); if (!isAlreadySaved) await Preference.addBill(invoice); final billings = await Preference.getBills(); billings.forEach((element) { if (element.price != null) print("BILLS" + element.price!.dispFinalAmt()); }); File pdf = await PdfInvoiceApi.generate(invoice); await PdfApi.openFile(pdf); await Phoenix.rebirth(context); }, ), ), ], ), ); } static Widget buildFooter(Billing invoice) => Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Divider(), SizedBox(height: 30), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (invoice.retailer != null) buildSupplierAddress(invoice.retailer!), ], ), SizedBox(height: 6), if (invoice.retailer != null && invoice.retailer!.address.isNotEmpty) buildSimpleText(title: 'Address', value: invoice.retailer!.address), ], ); static buildSimpleText({ required String title, required String value, }) { final style = TextStyle(fontWeight: FontWeight.bold); return Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(title, style: style), SizedBox(width: 6), Text(value), ], ); } static buildText({ required String title, required String value, double width = double.infinity, TextStyle? titleStyle, bool unite = false, }) { final style = titleStyle ?? TextStyle(fontWeight: FontWeight.bold); return Container( width: width, child: Row( mainAxisAlignment: unite ? MainAxisAlignment.spaceBetween : MainAxisAlignment.spaceBetween, children: [ Text("" + title, style: style), Text(" " + value, style: unite ? style : null), ], ), ); } static Widget buildSupplierAddress(User retailer) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Distributor:", style: TextStyle(fontWeight: FontWeight.bold)), SizedBox(height: 3), Text(retailer.name), SizedBox(height: 3), Text(retailer.mobileNo), SizedBox(height: 3), Text(retailer.address), ], ); @override void dispose() { super.dispose(); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/ui/bills.dart
import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:project_netsurf/common/analytics.dart'; import 'package:project_netsurf/common/contants.dart'; import 'package:project_netsurf/common/models/billing.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/display_data.dart'; import 'package:project_netsurf/common/sp_utils.dart'; import 'package:project_netsurf/common/ui/loader.dart'; import 'package:project_netsurf/ui/biller.dart'; class BillsPage extends StatefulWidget { final DisplayData displayData; final User retailer; BillsPage({Key? key, required this.retailer, required this.displayData}) : super(key: key); @override HomePageState createState() => HomePageState(); } class HomePageState extends State<BillsPage> { static FirebaseAnalytics analytics = GetIt.I.get<FirebaseAnalytics>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); Icon actionIcon = new Icon( Icons.search, color: Colors.white, ); late bool _isSearching; String _searchText = ""; final TextEditingController _searchQuery = new TextEditingController(); Widget appBarTitle = new Text( SAVED, style: new TextStyle(color: Colors.white), ); @override void initState() { super.initState(); _isSearching = false; _searchQuery.addListener(() { if (_searchQuery.text.isEmpty) { setState(() { _searchText = ""; }); } else { setState(() { _isSearching = true; _searchText = _searchQuery.text; }); } }); } @override Widget build(BuildContext context) { analytics.setCurrentScreen(screenName: CT_SAVED_BILLS); return Listener( onPointerDown: (_) { WidgetsBinding.instance.focusManager.primaryFocus?.unfocus(); }, child: Scaffold( appBar: AppBar( title: appBarTitle, centerTitle: true, actions: <Widget>[ Container( margin: EdgeInsets.only(right: 8), child: IconButton( icon: actionIcon, onPressed: () { setState(() { if (this.actionIcon.icon == Icons.search) { this.actionIcon = Icon( Icons.close, color: Colors.white, ); this.appBarTitle = Container( decoration: BoxDecoration( color: Colors.black26, borderRadius: BorderRadius.circular(15), ), child: TextField( controller: _searchQuery, style: TextStyle(color: Colors.white), decoration: InputDecoration( border: InputBorder.none, prefixIcon: Icon( Icons.search, size: 20, color: Colors.white, ), prefixIconConstraints: BoxConstraints( minWidth: 30, minHeight: 30, ), hintText: "Search saved bills", hintStyle: TextStyle( color: Colors.white70, fontSize: 13, ), ), ), ); _handleSearchStart(); } else { _handleSearchEnd(); } }); }, ), ), ], ), key: _scaffoldKey, body: SingleChildScrollView( child: Column( children: [ FutureBuilder( future: Preference.getBills(), builder: (context, AsyncSnapshot<List<Billing>> snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.data != null && snapshot.data!.isNotEmpty) { snapshot.data!.forEach((element) { if (element.price != null) print("BILLS: " + element.price!.dispFinalAmt()); }); return inputDataAndNext(_isSearching ? _buildSearchList(snapshot.data!) : snapshot.data!); } else { return Container( margin: EdgeInsets.only( left: 10, right: 10, top: 10, bottom: 0), child: Center( child: Text( "No bills found", style: TextStyle(fontSize: 16), ))); } } else if (snapshot.connectionState == ConnectionState.none) { return Text("No product data found"); } return CustomLoader(); }, ), SizedBox(height: 5), Container( margin: EdgeInsets.only(left: 18, right: 18, bottom: 18, top: 5), child: Text( "You can search the saved bills by name, phone number or bill number!", style: TextStyle(fontSize: 11)), ), ], ), )), ); } List<Billing> _buildSearchList(List<Billing> bills) { print("_searchText"); if (_searchText.isEmpty) { print("isEmpty"); return bills; } else { return bills.where((bill) => checkBill(bill)).toList(); } } bool checkBill(Billing bill) { bool hasSearch = false; if (bill.billingInfo != null) { hasSearch = hasSearch || bill.billingInfo!.number.contains(_searchText); } if (bill.customer != null) { hasSearch = hasSearch || (bill.customer!.mobileNo.contains(_searchText) || bill.customer!.name .toLowerCase() .contains(_searchText.toLowerCase())); } return hasSearch; } void _handleSearchStart() { setState(() { _isSearching = true; }); } void _handleSearchEnd() { setState(() { this.actionIcon = Icon( Icons.search, color: Colors.white, ); this.appBarTitle = Text( SAVED, style: TextStyle(color: Colors.white), ); _isSearching = false; _searchQuery.clear(); }); } Widget inputDataAndNext(List<Billing> bills) { return Container( child: ListView.builder( scrollDirection: Axis.vertical, physics: ClampingScrollPhysics(), shrinkWrap: true, itemCount: bills.length, itemBuilder: (BuildContext context, int index) { return Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), ), elevation: 5.0, margin: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), child: Row( children: [ if (!_isSearching) IconButton( onPressed: () { setState(() { print(bills.length); bills.remove(bills[index]); print(bills.length); bills.forEach((element) { if (element.price != null) print("" + element.price!.dispFinalAmt()); }); Preference.addBills(bills); }); }, icon: Icon( Icons.delete_forever_rounded, size: 30, ), color: Colors.black87, ), Expanded( child: GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (__) => BillerPage(billing: bills[index])), ); }, child: Container( constraints: BoxConstraints(minHeight: 125), decoration: BoxDecoration( color: Color(SECONDARY_COLOR), shape: BoxShape.rectangle, borderRadius: BorderRadius.circular(15.0), boxShadow: <BoxShadow>[ BoxShadow( color: Colors.black12, blurRadius: 10.0, offset: Offset(0.0, 10.0), ), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: Padding( padding: EdgeInsets.only( left: 24, top: 8, bottom: 8, right: 8), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( bills[index].customer?.name ?? "NA", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 15), ), Text( bills[index].customer?.mobileNo ?? "NA", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 15), ), ], ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (bills[index].billingInfo != null) Text( "Bill No: " + bills[index].billingInfo!.number, style: TextStyle( color: Colors.white70, fontSize: 12, ), ), if (bills[index].customer != null && bills[index] .customer! .cRefId .isNotEmpty) Text( "CRef: " + bills[index].customer!.cRefId, style: TextStyle( color: Colors.white70, fontSize: 12, ), ), ], ), SizedBox(height: 10), if (bills[index].price != null) Center( child: Text( RUPEE_SYMBOL + " " + bills[index].price!.dispFinalAmt(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 16), ), ), ], ), ), ), IconButton( onPressed: () { print("Delete click"); }, icon: Icon( Icons.navigate_next, size: 35, ), color: Colors.white70, ), ], ), ), ), ), ], ), ); }, ), ); } @override void dispose() { super.dispose(); } }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/ui/drawer.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_phoenix/flutter_phoenix.dart'; import 'package:get_it/get_it.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:project_netsurf/common/analytics.dart'; import 'package:project_netsurf/common/contants.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/display_data.dart'; import 'package:project_netsurf/common/product_constant.dart'; import 'package:project_netsurf/common/sp_constants.dart'; import 'package:project_netsurf/common/sp_utils.dart'; import 'package:project_netsurf/common/ui/error.dart'; import 'package:project_netsurf/common/ui/loader.dart'; import 'package:project_netsurf/ui/bills.dart'; import 'package:share_plus/share_plus.dart'; import 'package:url_launcher/url_launcher.dart'; class AppDrawer extends StatelessWidget { static FirebaseAnalytics analytics = GetIt.I.get<FirebaseAnalytics>(); final User retailer; final DisplayData displayData; const AppDrawer({Key? key, required this.retailer, required this.displayData}) : super(key: key); @override Widget build(BuildContext buildContext) { analytics.setCurrentScreen(screenName: CT_DRAWER); return FutureBuilder( future: PackageInfo.fromPlatform(), builder: (context, AsyncSnapshot<PackageInfo> snapshot) { if (snapshot.connectionState == ConnectionState.done) { return Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ CachedNetworkImage( height: 170, imageUrl: displayData.drawer, progressIndicatorBuilder: (context, url, downloadProgress) => CustomLoader(), fit: BoxFit.fill, fadeInCurve: Curves.easeInToLinear, errorWidget: (context, url, error) => Icon(Icons.error_outlined), ), if (retailer.name.isNotEmpty) SizedBox(height: 8), if (retailer.name.isNotEmpty) Container( margin: EdgeInsets.only(top: 6, bottom: 6), child: Padding( padding: EdgeInsets.only(left: 14, right: 16), child: Row( children: [ Icon(Icons.account_circle_rounded, size: 32, color: Color(PRIMARY_COLOR)), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(left: 8), child: Text( retailer.name, style: TextStyle( fontSize: 15.0, fontWeight: FontWeight.w600), ), ), SizedBox(height: 2), Padding( padding: EdgeInsets.only(left: 8), child: Text( retailer.mobileNo, style: TextStyle(fontSize: 13.0), ), ), ], ), ], ), ), ), if (retailer.name.isNotEmpty) Divider(), _createDrawerIconItem( icon: Icon( Icons.collections_bookmark_rounded, size: 28, color: Color(PRIMARY_COLOR), ), text: SAVED, onTap: () { Navigator.push( context, MaterialPageRoute( builder: (__) => BillsPage( retailer: retailer, displayData: displayData)), ); }, ), Divider(), _createDrawerItem( icon: Icons.refresh_rounded, text: 'Refresh app', onTap: () async { Navigator.of(context).pop(); if (await Preference.contains(SP_DT_REFRESH)) { DateTime oldDateTime = await Preference.getDateTime(SP_DT_REFRESH); DateTime timeNow = DateTime.now(); Duration timeDifference = timeNow.difference(oldDateTime); print("TimeDif: " + timeDifference.inDays.toString()); if (timeDifference.inDays > 1) { refresh(context); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text("Already updated! No need to refresh."), duration: const Duration(seconds: 2), behavior: SnackBarBehavior.fixed, ), ); } } else { refresh(context); } }, ), _createDrawerItem( icon: Icons.account_box_rounded, text: 'Distributor logout', onTap: () async { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; analytics.logEvent( name: CT_LOGOUT, parameters: <String, dynamic>{ CT_DISTRIBUTOR_NAME: retailer.name, CT_DISTRIBUTOR_PH_NO: retailer.mobileNo, CT_MODEL_NAME: androidInfo.model, CT_MANUFACTURER_NAME: androidInfo.manufacturer, CT_ANDROID_VERSION_STRING: androidInfo.version.release, CT_ANDROID_VERSION: androidInfo.version.baseOS }, ); showLogoutErrorDialog(context); }, ), Divider(), _createDrawerItem( icon: Icons.face_retouching_natural, text: displayData.aname, onTap: () async { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; analytics.logEvent( name: CT_AUTHOR, parameters: <String, dynamic>{ CT_DISTRIBUTOR_NAME: retailer.name, CT_DISTRIBUTOR_PH_NO: retailer.mobileNo, CT_MODEL_NAME: androidInfo.model, CT_MANUFACTURER_NAME: androidInfo.manufacturer, CT_ANDROID_VERSION_STRING: androidInfo.version.release, CT_ANDROID_VERSION: androidInfo.version.baseOS }, ); _launchURL(displayData.alink); }, ), if (snapshot.data != null) _createDrawerItem( icon: Icons.bug_report, text: 'Report issue', onTap: () async { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; analytics.logEvent( name: CT_REPORT_ISSUE, parameters: <String, dynamic>{ CT_DISTRIBUTOR_NAME: retailer.name, CT_DISTRIBUTOR_PH_NO: retailer.mobileNo, CT_MODEL_NAME: androidInfo.model, CT_MANUFACTURER_NAME: androidInfo.manufacturer, CT_ANDROID_VERSION_STRING: androidInfo.version.release, CT_ANDROID_VERSION: androidInfo.version.baseOS }, ); final Uri params = Uri( scheme: 'mailto', path: displayData.aemail, query: 'subject=App Feedback&body=App Version: ' + snapshot.data!.version, //add subject and body here ); _launchURL(params.toString()); }, ), _createDrawerItem( icon: Icons.mobile_screen_share_rounded, text: "Share with friends", onTap: () async { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; analytics.logEvent( name: CT_SHARE_APP, parameters: <String, dynamic>{ CT_DISTRIBUTOR_NAME: retailer.name, CT_DISTRIBUTOR_PH_NO: retailer.mobileNo, CT_MODEL_NAME: androidInfo.model, CT_MANUFACTURER_NAME: androidInfo.manufacturer, CT_ANDROID_VERSION_STRING: androidInfo.version.release, CT_ANDROID_VERSION: androidInfo.version.baseOS }, ); print("Play Link: " + displayData.playlink); Share.share(displayData.playlink); }, ), Divider(), if (snapshot.data != null) ListTile( title: Text( "Version - " + snapshot.data!.version, style: TextStyle(fontSize: 12), ), onTap: () {}, ), ], ), ); } else if (snapshot.hasError) { return Text( "Sorry, Something went wrong.", style: TextStyle(color: Colors.red, fontSize: 14), textAlign: TextAlign.center, ); } else { return CustomLoader(); } }, ); } void refresh(BuildContext context) async { await Preference.setDateTime(SP_DT_REFRESH); FirebaseFirestore fireStore = GetIt.I.get<FirebaseFirestore>(); await Products.getDisplayData(fireStore, true); await Products.getAllProducts(fireStore, true); await Phoenix.rebirth(context); } } Widget _createDrawerItem( {required IconData icon, required String text, required GestureTapCallback onTap}) { return _createDrawerIconItem(icon: Icon(icon), text: text, onTap: onTap); } Widget _createDrawerIconItem( {required Icon icon, required String text, required GestureTapCallback onTap}) { return ListTile( title: Row( children: <Widget>[ icon, Padding( padding: EdgeInsets.only(left: 8.0), child: Text(text), ) ], ), onTap: onTap, ); } void _launchURL(_url) async => await canLaunch(_url) ? await launch(_url) : throw 'Could not launch $_url'; Future<String> getPackageInfo() async { PackageInfo packageInfo = await PackageInfo.fromPlatform(); return packageInfo.version; }
0
mirrored_repositories/Netsurf-Flutter-App/lib
mirrored_repositories/Netsurf-Flutter-App/lib/ui/home.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter/material.dart'; import 'package:flutter_phoenix/flutter_phoenix.dart'; import 'package:get_it/get_it.dart'; import 'package:project_netsurf/common/analytics.dart'; import 'package:project_netsurf/common/contants.dart'; import 'package:project_netsurf/common/models/customer.dart'; import 'package:project_netsurf/common/models/display_data.dart'; import 'package:project_netsurf/common/models/product.dart'; import 'package:project_netsurf/common/sp_constants.dart'; import 'package:project_netsurf/common/sp_utils.dart'; import 'package:project_netsurf/common/ui/edittext.dart'; import 'package:project_netsurf/common/ui/loader.dart'; import 'package:project_netsurf/ui/drawer.dart'; import 'package:project_netsurf/ui/select_products.dart'; import '../di/singletons.dart'; class HomePage extends StatefulWidget { final String billingIdVal; final bool isRetailer; final User? retailer; final DisplayData displayData; HomePage( {Key? key, required this.isRetailer, this.retailer, required this.displayData, required this.billingIdVal}) : super(key: key); @override HomePageState createState() => HomePageState(); } class HomePageState extends State<HomePage> { static FirebaseAnalytics analytics = GetIt.I.get<FirebaseAnalytics>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); final TextEditingController categoryTextController = new TextEditingController(); final TextEditingController itemTextController = new TextEditingController(); late ScrollController _controller; bool silverCollapsed = false; List<Product?>? allCategories; List<Product?>? allProducts; bool isRetailer = false; String textValue = ""; User user = User("", "", "", "", ""); User retailer = User("", "", "", "", ""); @override void initState() { super.initState(); _controller = ScrollController(); isRetailer = widget.isRetailer; if (widget.retailer != null && widget.retailer!.name.isNotEmpty && widget.retailer!.mobileNo.isNotEmpty) retailer = widget.retailer!; _controller.addListener(() { if (_controller.offset > 100 && !_controller.position.outOfRange) { if (!silverCollapsed) { silverCollapsed = true; } } if (_controller.offset <= 100 && !_controller.position.outOfRange) { if (silverCollapsed) { silverCollapsed = false; } } }); } @override Widget build(BuildContext context) { analytics.setCurrentScreen( screenName: isRetailer ? CT_DISTRIBUTER_SCREEN : CT_USER_SCREEN); return Listener( onPointerDown: (_) { WidgetsBinding.instance.focusManager.primaryFocus?.unfocus(); }, child: Scaffold( drawer: AppDrawer(retailer: retailer, displayData: widget.displayData), key: _scaffoldKey, body: FutureBuilder( future: Preference.getProducts(SP_CATEGORY_IDS), builder: (context, AsyncSnapshot<List<Product>> snapshot) { if (snapshot.connectionState == ConnectionState.done) { allCategories = snapshot.data; return FutureBuilder( future: Preference.getProducts(SP_PRODUCTS), builder: (context, AsyncSnapshot<List<Product>> snapshot) { if (snapshot.connectionState == ConnectionState.done) { allProducts = snapshot.data; User? retailUser = GetIt.I.get<User>(); if (retailUser.name.isNotEmpty && retailUser.mobileNo.isNotEmpty) { print("RetailerData: " + retailUser.name); if (retailer.name.isEmpty && retailer.mobileNo.isEmpty) retailer = retailUser; isRetailer = false; return scrollView(); } else { isRetailer = true; return scrollView(); } } else if (snapshot.connectionState == ConnectionState.none) { return Text("No product data found"); } return CustomLoader(); }, ); } else if (snapshot.connectionState == ConnectionState.none) { return Text("No product data found"); } return CustomLoader(); }, )), ); } Widget scrollView() { textValue = isRetailer ? "Distributor" : "Customer"; return CustomScrollView( controller: _controller, slivers: <Widget>[ scrollAppBar(), inputDataAndNext(), ], ); } Widget scrollAppBar() { List<String>? bannerList = widget.displayData.bannerList; int length = 1; if (bannerList != null && bannerList.isNotEmpty) { length = widget.displayData.bannerList!.length; } else { bannerList = []; bannerList.add(widget.displayData.banner); } return SliverAppBar( expandedHeight: 200, pinned: false, iconTheme: IconThemeData(color: Color(PRIMARY_COLOR)), backgroundColor: Colors.white, flexibleSpace: FlexibleSpaceBar( title: Text( "", style: TextStyle(color: Colors.grey[100]), ), centerTitle: true, background: Center( child: CarouselSlider( options: CarouselOptions(height: 400.0), items: Iterable<int>.generate(length).toList().map((i) { return Builder( builder: (BuildContext context) { return Container( width: MediaQuery.of(context).size.width, margin: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0), decoration: BoxDecoration( color: Colors.blueGrey.shade50, borderRadius: BorderRadius.all(Radius.circular(8))), child: CachedNetworkImage( imageUrl: bannerList![i], progressIndicatorBuilder: (context, url, downloadProgress) => CustomLoader(), fit: BoxFit.contain, fadeInCurve: Curves.easeInToLinear, errorWidget: (context, url, error) => Icon(Icons.error), ), ); }, ); }).toList(), ), ), ), ); } Widget inputDataAndNext() { return SliverFillRemaining( child: Container( color: Colors.white, child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ if (isRetailer) Flexible( child: Text( "Before moving forward, let's update the distributor details!", textAlign: TextAlign.center, style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold), ), ), Flexible( child: EditText( required: true, initTextValue: user.name, type: TextInputType.name, editTextName: textValue + " Name", onText: (text) async { user.name = text; Preference.setItem(SP_CUSTOMER_NAME, text); print(text); }, onTap: () { _controller.jumpTo(_controller.position.maxScrollExtent); }), ), Flexible( child: EditText( required: true, initTextValue: user.mobileNo, type: TextInputType.phone, isPhone: true, editTextName: textValue + " Mobile Number", onText: (text) async { user.mobileNo = text; Preference.setItem(SP_CUSTOMER_M_NO, text); print(text); }, onTap: () { _controller.jumpTo(_controller.position.maxScrollExtent); }), ), Flexible( child: EditText( required: false, initTextValue: user.cRefId, editTextName: textValue + " Reference ID", onText: (text) async { user.cRefId = text; await Preference.setItem(SP_CUSTOMER_RF_ID, text); print(text); }, onTap: () { _controller.jumpTo(_controller.position.maxScrollExtent); }), ), // Flexible( // child: EditText( // required: false, // editTextName: "Address", // initTextValue: user.address ?? "", // type: TextInputType.streetAddress, // maxline: 3, // onText: (text) async { // user.address = text; // await Preference.setItem(SP_CUSTOMER_ADDRESS, text); // print(text); // }, // onTap: () { // _controller.jumpTo(_controller.position.maxScrollExtent); // }), // ), if (!isRetailer) Flexible( child: EditText( required: false, initTextValue: user.email, editTextName: "Email", type: TextInputType.emailAddress, onText: (text) async { user.email = text; await Preference.setItem(SP_CUSTOMER_EMAIL, text); print(text); }, onTap: () { _controller.jumpTo(_controller.position.maxScrollExtent); }), ), CustomButton( buttonText: isRetailer ? "Save" : "Next", onClick: () async { if (user.name.isEmpty) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Please fill the " + textValue + " name!"), duration: const Duration(seconds: 2), behavior: SnackBarBehavior.fixed, backgroundColor: Colors.red, )); return; } if (user.mobileNo.length != 10) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Please fill the 10 digit " + textValue + " mobile number!"), duration: const Duration(seconds: 2), behavior: SnackBarBehavior.fixed, backgroundColor: Colors.red, )); return; } if (isRetailer) { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; analytics.logEvent( name: CT_DISTRIBUTOR_LOGIN, parameters: <String, dynamic>{ CT_DISTRIBUTOR_NAME: retailer.name, CT_DISTRIBUTOR_PH_NO: retailer.mobileNo, CT_MODEL_NAME: androidInfo.model, CT_MANUFACTURER_NAME: androidInfo.manufacturer, CT_ANDROID_VERSION_STRING: androidInfo.version.release, CT_ANDROID_VERSION: androidInfo.version.baseOS }, ); await Preference.setRetailer(user); await setupRetailerDetails(); await Phoenix.rebirth(context); } else { if (allCategories == null || allCategories!.isEmpty || allProducts == null || allProducts!.isEmpty) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text("Products "), duration: const Duration(seconds: 2), behavior: SnackBarBehavior.fixed, backgroundColor: Colors.red, )); return; } Navigator.push( context, MaterialPageRoute( builder: (__) => new SelectProductsPage( customerData: user, allCategories: allCategories!, allProducts: allProducts!, retailer: retailer, billingIdVal: widget.billingIdVal, ), ), ); } }, ), ], ), ), ); } @override void dispose() { super.dispose(); } }
0
mirrored_repositories/Netsurf-Flutter-App
mirrored_repositories/Netsurf-Flutter-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 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. void main() { }
0
mirrored_repositories/puzzles
mirrored_repositories/puzzles/lib/main_staging.dart
import 'package:puzzles/app/app.dart'; import 'package:puzzles/bootstrap.dart'; void main() { bootstrap(() => const App()); }
0
mirrored_repositories/puzzles
mirrored_repositories/puzzles/lib/main_production.dart
import 'package:puzzles/app/app.dart'; import 'package:puzzles/bootstrap.dart'; void main() { bootstrap(() => const App()); }
0
mirrored_repositories/puzzles
mirrored_repositories/puzzles/lib/bootstrap.dart
import 'dart:async'; import 'dart:developer'; import 'package:bloc/bloc.dart'; import 'package:flutter/widgets.dart'; class AppBlocObserver extends BlocObserver { const AppBlocObserver(); @override void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) { super.onChange(bloc, change); log('onChange(${bloc.runtimeType}, $change)'); } @override void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) { log('onError(${bloc.runtimeType}, $error, $stackTrace)'); super.onError(bloc, error, stackTrace); } } Future<void> bootstrap(FutureOr<Widget> Function() builder) async { FlutterError.onError = (details) { log(details.exceptionAsString(), stackTrace: details.stack); }; Bloc.observer = const AppBlocObserver(); await runZonedGuarded( () async => runApp(await builder()), (error, stackTrace) => log(error.toString(), stackTrace: stackTrace), ); }
0
mirrored_repositories/puzzles
mirrored_repositories/puzzles/lib/main_development.dart
import 'package:puzzles/app/app.dart'; import 'package:puzzles/bootstrap.dart'; void main() { bootstrap(() => const App()); }
0