repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/bytebank_2_alura/lib
mirrored_repositories/bytebank_2_alura/lib/screens/dashboard.dart
import 'package:bytebank_2/theme/theme.dart'; import 'package:flutter/material.dart'; class Dashboard extends StatelessWidget { const Dashboard({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: appTheme().backgroundColor, appBar: AppBar( title: Text('Dashboard'), ), body: OrientationBuilder(builder: (context, orientation) { return GridView.count( crossAxisCount: orientation == Orientation.portrait ? 1 : 2, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Image.asset( 'assets/images/bytebank_logo.png', fit: BoxFit.fitHeight, ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ FeatureItem( key: Key('transfer'), name: 'Transfer', icon: Icons.monetization_on, route: '/contacts_list', ), FeatureItem( key: Key('transaction_feed'), name: 'Transaction Feed', icon: Icons.description, route: '/transactions_list', ), ], ), ) ], ); }), ); } } class FeatureItem extends StatelessWidget { final String name; final IconData icon; final String route; const FeatureItem( {Key key, @required this.name, this.icon, @required this.route}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Material( color: Theme.of(context).primaryColor, child: InkWell( child: Container( padding: const EdgeInsets.all(8.0), height: 100, width: 150, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Icon( icon, color: Colors.white, size: 24.0, ), Text( name, style: TextStyle( color: Colors.white, fontSize: 16.0, ), ) ], ), ), onTap: () { Navigator.pushNamed(context, route); }, ), ), ); } }
0
mirrored_repositories/bytebank_2_alura/lib
mirrored_repositories/bytebank_2_alura/lib/screens/transactions_list.dart
import 'package:bytebank_2/components/centered_message.dart'; import 'package:bytebank_2/components/progress.dart'; import 'package:bytebank_2/extensions/string_extension.dart'; import 'package:bytebank_2/models/transaction.dart'; import 'package:bytebank_2/widgets/app_dependencies.dart'; import 'package:flutter/material.dart'; class TransactionsList extends StatelessWidget { final List<Transaction> transactions = List(); @override Widget build(BuildContext context) { final dependencies = AppDependencies.of(context); return Scaffold( appBar: AppBar( title: Text('Transactions'), ), body: FutureBuilder<List<Transaction>>( initialData: List(), future: Future.delayed(Duration(milliseconds: 500)) .then((value) => dependencies.transactionWebClient.findAll()), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: break; case ConnectionState.waiting: return Progress(); break; case ConnectionState.active: break; case ConnectionState.done: if (snapshot.hasData) { final List<Transaction> transactions = snapshot.data; if (transactions.isNotEmpty) { return ListView.builder( itemBuilder: (context, index) { final Transaction transaction = transactions[index]; return Card( child: ListTile( leading: Icon(Icons.monetization_on), title: Text( transaction.value.toString(), style: TextStyle( fontSize: 24.0, fontWeight: FontWeight.bold, ), ), subtitle: Text( transaction.contact.name.toString().capitalize() + ': ' + transaction.contact.accountNumber.toString(), style: TextStyle( fontSize: 16.0, ), ), ), ); }, itemCount: transactions.length, ); } } return CenteredMessage('No transactions found', icon: Icons.warning); break; } return CenteredMessage('Unknown Error'); }, ), ); } }
0
mirrored_repositories/bytebank_2_alura/lib
mirrored_repositories/bytebank_2_alura/lib/screens/transaction_form.dart
import 'dart:async'; import 'package:bytebank_2/components/progress.dart'; import 'package:bytebank_2/components/response_dialog.dart'; import 'package:bytebank_2/components/transaction_auth_dialog.dart'; import 'package:bytebank_2/http/webclients/transaction_webclient.dart'; import 'package:bytebank_2/models/contact.dart'; import 'package:bytebank_2/models/transaction.dart'; import 'package:bytebank_2/widgets/app_dependencies.dart'; import 'package:flutter/material.dart'; import 'package:uuid/uuid.dart'; class TransactionFormArguments { final Contact contact; TransactionFormArguments(this.contact); } class TransactionForm extends StatefulWidget { @override _TransactionFormState createState() => _TransactionFormState(); } class _TransactionFormState extends State<TransactionForm> { final TextEditingController _valueController = TextEditingController(); final String transactionId = Uuid().v4(); bool _sending = false; GlobalKey _scaffold = GlobalKey(); @override Widget build(BuildContext context) { final dependencies = AppDependencies.of(context); final TransactionFormArguments args = ModalRoute.of(context).settings.arguments; return Scaffold( key: _scaffold, appBar: AppBar( title: Text('New transaction'), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Visibility( visible: _sending, child: Padding( padding: const EdgeInsets.all(8.0), child: Progress( message: 'Sending transaction...', ), ), ), Text( args.contact.name, style: TextStyle( fontSize: 24.0, ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: Text( args.contact.accountNumber.toString(), style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.bold, ), ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: TextField( controller: _valueController, style: TextStyle(fontSize: 24.0), decoration: InputDecoration(labelText: 'Value'), keyboardType: TextInputType.numberWithOptions(decimal: true), ), ), Padding( padding: const EdgeInsets.only(top: 16.0), child: SizedBox( width: double.maxFinite, child: RaisedButton( child: Text('Transfer'), onPressed: () { final double value = double.tryParse(_valueController.text); final transactionCreated = Transaction(transactionId, value, args.contact); showDialog( context: context, builder: (contextDialog) { return TransactionAuthDialog( onConfirm: (String password) { _save( dependencies.transactionWebClient, transactionCreated, password, _scaffold.currentContext); }, ); }); }, ), ), ) ], ), ), ), ); } Future<void> _save( TransactionWebClient webClient, Transaction transactionCreated, String password, BuildContext context, ) async { setState(() { _sending = true; }); final Transaction newTransaction = await _send( webClient, transactionCreated, password, context, ); _showSuccessfullMessage(newTransaction, context); } Future _showSuccessfullMessage( Transaction newTransaction, BuildContext context) async { if (newTransaction != null) { await showDialog( context: context, builder: (contextDialog) { return SuccessDialog('Successfull transfer'); }); Navigator.pop(context, newTransaction); } } Future<Transaction> _send( TransactionWebClient webClient, Transaction transactionCreated, String password, BuildContext context) async { return await webClient.save(transactionCreated, password).catchError( (error) { _showFailureMessage(context, error); }, test: (e) => e is HttpExceptionDif).catchError((error) { _showFailureMessage(context, error, message: 'Timeout'); }, test: (e) => e is TimeoutException).catchError((error) { _showFailureMessage(context, error); }, test: (e) => e is Exception).whenComplete(() { setState(() { _sending = false; }); }); } void _showFailureMessage(BuildContext context, error, {String message}) { showDialog( context: context, builder: (contextDialog) { return FailureDialog((message == null ? error.message : message)); }, ); } }
0
mirrored_repositories/bytebank_2_alura
mirrored_repositories/bytebank_2_alura/test/widget_test.dart
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/flows/save_contact_flow_test.dart
import 'package:bytebank_2/main.dart'; import 'package:bytebank_2/models/contact.dart'; import 'package:bytebank_2/screens/contact_form.dart'; import 'package:bytebank_2/screens/contacts_list.dart'; import 'package:bytebank_2/screens/dashboard.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import '../matchers/matchers.dart'; import '../mocks/mocks.dart'; import 'actions.dart'; void main() { MockContactDao mockContactDao; MockTransactionWebClient mockTransactionWebClient; setUp(() async { mockContactDao = MockContactDao(); mockTransactionWebClient = MockTransactionWebClient(); }); group('Save Contact Group: ', () { testWidgets('Finding transfer icon', (tester) async { await tester.runAsync(() async { await tester.pumpWidget(BytebankApp( contactDao: mockContactDao, transactionWebClient: mockTransactionWebClient, )); final dashboard = find.byType(Dashboard); expect(dashboard, findsOneWidget); final transferFeatureItem = find.byWidgetPredicate((widget) => featureItemMatcher( widget, 'Transfer', Icons.monetization_on, 'transfer')); expect(transferFeatureItem, findsOneWidget); }); }); testWidgets('Saving a contact', (tester) async { final contact = Contact('Flavio', 1000, id: 1); await tester.pumpWidget(BytebankApp( contactDao: mockContactDao, transactionWebClient: mockTransactionWebClient, )); final dashboard = find.byType(Dashboard); expect(dashboard, findsOneWidget); await clickOnTransferFeatureItem(tester); await tester.pumpAndSettle(); final contactsList = find.byType(ContactsList); expect(contactsList, findsOneWidget); verify(mockContactDao.findAll()).called(1); await clickOnTheFabNew(tester); await tester.pumpAndSettle(); final contactForm = find.byType(ContactForm); expect(contactForm, findsOneWidget); await fillTextFieldWithTextLabel(tester, labelText: 'Full name', text: contact.name); await fillTextFieldWithTextLabel(tester, labelText: 'Account Number', text: contact.accountNumber.toString()); await clickOntheRaisedButtonWithText(tester, 'Create'); await tester.pumpAndSettle(); verify(mockContactDao.save(contact)).called(1); final contactsListBack = find.byType(ContactsList); expect(contactsListBack, findsOneWidget); verify(mockContactDao.findAll()).called(1); }); }); }
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/flows/transfer_flow_test.dart
import 'package:bytebank_2/components/response_dialog.dart'; import 'package:bytebank_2/components/transaction_auth_dialog.dart'; import 'package:bytebank_2/main.dart'; import 'package:bytebank_2/models/contact.dart'; import 'package:bytebank_2/models/transaction.dart'; import 'package:bytebank_2/screens/contacts_list.dart'; import 'package:bytebank_2/screens/dashboard.dart'; import 'package:bytebank_2/screens/transaction_form.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import '../matchers/matchers.dart'; import '../mocks/mocks.dart'; import 'actions.dart'; void main() { MockContactDao mockContactDao; MockTransactionWebClient mockTransactionWebClient; setUp(() async { mockContactDao = MockContactDao(); mockTransactionWebClient = MockTransactionWebClient(); }); group('Transfer Flow Group: ', () { testWidgets('Should transfer to a contact', (tester) async { await tester.pumpWidget(BytebankApp( contactDao: mockContactDao, transactionWebClient: mockTransactionWebClient, )); final contact = Contact('Flavio', 1000, id: 1); final transaction = Transaction(null, 200, contact); final dashboard = find.byType(Dashboard); expect(dashboard, findsOneWidget); when(mockContactDao.findAll()).thenAnswer((realInvocation) async { return [contact]; }); await clickOnTransferFeatureItem(tester); await tester.pumpAndSettle(); final contactsList = find.byType(ContactsList); expect(contactsList, findsOneWidget); verify(mockContactDao.findAll()).called(1); final contactItem = find.byWidgetPredicate((widget) { if (widget is ContactItem) { return widget.contact.name == contact.name && widget.contact.accountNumber == contact.accountNumber; } return false; }); expect(contactItem, findsOneWidget); await tester.tap(contactItem); await tester.pumpAndSettle(); final transactionForm = find.byType(TransactionForm); expect(transactionForm, findsOneWidget); final contactName = find.text(contact.name); expect(contactName, findsOneWidget); final contactAccountNumber = find.text(contact.accountNumber.toString()); expect(contactAccountNumber, findsOneWidget); await fillTextFieldWithTextLabel(tester, labelText: 'Value', text: transaction.value.toString()); await clickOntheRaisedButtonWithText(tester, 'Transfer'); await tester.pumpAndSettle(); final transactionAuthDialog = find.byType(TransactionAuthDialog); expectSync(transactionAuthDialog, findsOneWidget); final authField = find.byKey(Key('transactionAuthField')); expect(authField, findsOneWidget); await tester.enterText(authField, 1000.toString()); final cancelButton = find.widgetWithText(FlatButton, 'Cancel'); expect(cancelButton, findsOneWidget); final confirmButton = find.widgetWithText(FlatButton, 'Confirm'); expect(confirmButton, findsOneWidget); when(mockTransactionWebClient.save(transaction, '1000')) .thenAnswer((_) async => Future.value(transaction)); await tester.tap(confirmButton); await tester.pumpAndSettle(); final successDialog = find.byType(SuccessDialog); expect(successDialog, findsOneWidget); // final okButton = find.widgetWithText(FlatButton, 'Ok'); // expect(okButton, findsOneWidget); // await tester.tap(okButton); // await tester.pumpAndSettle(); // final contactsListBack = find.byType(ContactsList); // expect(contactsListBack, findsOneWidget); }); }); }
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/flows/actions.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../matchers/matchers.dart'; Future<void> clickOnTransferFeatureItem(WidgetTester tester) async { final transferFeatureItem = find.byWidgetPredicate((widget) => featureItemMatcher( widget, 'Transfer', Icons.monetization_on, 'transfer')); expect(transferFeatureItem, findsOneWidget); return tester.tap(transferFeatureItem); }
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/mocks/mocks.dart
import 'package:bytebank_2/dao/contact_dao.dart'; import 'package:bytebank_2/http/webclients/transaction_webclient.dart'; import 'package:mockito/mockito.dart'; class MockContactDao extends Mock implements ContactDao {} class MockTransactionWebClient extends Mock implements TransactionWebClient {}
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/widgets/dashboard_widget_test.dart
import 'package:bytebank_2/screens/dashboard.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../matchers/matchers.dart'; void main() { group('When Dashboard opens', () { testWidgets('Should display main image when Dashboard screen is opened', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(home: Dashboard())); final mainImage = find.byType(Image); expect(mainImage, findsOneWidget); }); testWidgets( 'Should display Transfer FeatureItem when Dashboard screen is opened', (tester) async { await tester.pumpWidget(MaterialApp(home: Dashboard())); final transferFeatureItem = find.byWidgetPredicate((widget) => featureItemMatcher( widget, 'Transfer', Icons.monetization_on, 'transfer')); expect(transferFeatureItem, findsOneWidget); }); testWidgets( 'Should display Transaction Feed FeatureItem when Dashboard screen is opened', (tester) async { await tester.pumpWidget(MaterialApp(home: Dashboard())); final transactionFeedFeatureItem = find.byWidgetPredicate((widget) => featureItemMatcher(widget, 'Transaction Feed', Icons.description, 'transaction_feed')); expect(transactionFeedFeatureItem, findsOneWidget); }); }); }
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/unit/transaction_test.dart
import 'package:bytebank_2/models/transaction.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('Should return the value when creatingg a transaction', () { final Transaction transaction = Transaction(null, 200, null); expect(transaction.value, 200); }); test('Should return error when creating transaction with value lower than 1', () { expect(() => Transaction(null, 0, null), throwsAssertionError); }); }
0
mirrored_repositories/bytebank_2_alura/test
mirrored_repositories/bytebank_2_alura/test/matchers/matchers.dart
import 'package:bytebank_2/screens/dashboard.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; bool featureItemMatcher(Widget widget, String name, IconData icon, String key) { if (widget is FeatureItem) { return widget.name == name && widget.icon == icon && widget.key == Key(key); } return false; } bool textFieldByLabelTextMatcher(Widget widget, String labelText) { if (widget is TextField) { return widget.decoration.labelText == labelText; } return false; } Future<void> clickOntheRaisedButtonWithText( WidgetTester tester, String text) async { final createButton = find.widgetWithText(RaisedButton, text); expect(createButton, findsOneWidget); return tester.tap(createButton); } Future<void> fillTextFieldWithTextLabel( WidgetTester tester, { String text = '', @required String labelText, }) async { final nameTextField = find.byWidgetPredicate( (widget) => textFieldByLabelTextMatcher(widget, labelText)); expect(nameTextField, findsOneWidget); return tester.enterText(nameTextField, text); } Future<void> clickOnTheFabNew(WidgetTester tester) async { final fabNewContact = find.widgetWithIcon(FloatingActionButton, Icons.add); expect(fabNewContact, findsOneWidget); return tester.tap(fabNewContact); }
0
mirrored_repositories/Flutter-home-service-app
mirrored_repositories/Flutter-home-service-app/lib/main.dart
import 'package:day35/pages/home.dart'; import 'package:day35/pages/select_service.dart'; import 'package:day35/pages/start.dart'; import 'package:flutter/material.dart'; void main () { runApp(MaterialApp( home: StartPage(), debugShowCheckedModeBanner: false, )); }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/pages/cleaning.dart
import 'package:day35/animation/FadeAnimation.dart'; import 'package:day35/pages/date_time.dart'; import 'package:flutter/material.dart'; class CleaningPage extends StatefulWidget { const CleaningPage({ Key? key }) : super(key: key); @override _CleaningPageState createState() => _CleaningPageState(); } class _CleaningPageState extends State<CleaningPage> { // Rooms to clean List<dynamic> _rooms =[ ['Living Room', 'https://img.icons8.com/officel/2x/living-room.png', Colors.red, 0], ['Bedroom', 'https://img.icons8.com/fluency/2x/bedroom.png', Colors.orange, 1], ['Bathroom', 'https://img.icons8.com/color/2x/bath.png', Colors.blue, 1], ['Kitchen', 'https://img.icons8.com/dusk/2x/kitchen.png', Colors.purple, 0], ['Office', 'https://img.icons8.com/color/2x/office.png', Colors.green, 0] ]; List<int> _selectedRooms = []; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, floatingActionButton: _selectedRooms.length > 0 ? FloatingActionButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => DateAndTime() ), ); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('${_selectedRooms.length}', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), SizedBox(width: 2), Icon(Icons.arrow_forward_ios, size: 18,), ], ), backgroundColor: Colors.blue, ) : null, body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverToBoxAdapter( child: FadeAnimation(1, Padding( padding: EdgeInsets.only(top: 120.0, right: 20.0, left: 20.0), child: Text( 'Where do you want \ncleaned?', style: TextStyle( fontSize: 35, color: Colors.grey.shade900, fontWeight: FontWeight.bold, ), ), ), )) ]; }, body: Padding( padding: EdgeInsets.all(20.0), child: ListView.builder( physics: NeverScrollableScrollPhysics(), itemCount: _rooms.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation((1.2 + index) / 4, room(_rooms[index], index)); } ), ), ) ); } room(List room, int index) { return GestureDetector( onTap: () { setState(() { if (_selectedRooms.contains(index)) _selectedRooms.remove(index); else _selectedRooms.add(index); }); }, child: Container( padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10), margin: EdgeInsets.only(bottom: 20.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: _selectedRooms.contains(index) ? room[2].shade50.withOpacity(0.5) : Colors.grey.shade100, ), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Row( children: [ Image.network(room[1], width: 35, height: 35,), SizedBox(width: 10.0,), Text(room[0], style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),), ], ), Spacer(), _selectedRooms.contains(index) ? Container( padding: EdgeInsets.all(5.0), decoration: BoxDecoration( color: Colors.greenAccent.shade100.withOpacity(0.3), borderRadius: BorderRadius.circular(10.0), ), child: Icon(Icons.check, color: Colors.green, size: 20,) ) : SizedBox() ], ), (_selectedRooms.contains(index) && room[3] >= 1) ? Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 20.0,), Text("How many ${room[0]}s?", style: TextStyle(fontSize: 15),), SizedBox(height: 10.0,), Container( height: 45, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 4, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () { setState(() { room[3] = index + 1; }); }, child: Container( margin: EdgeInsets.only(right: 10.0), padding: EdgeInsets.all(10.0), width: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: room[3] == index + 1 ? room[2].withOpacity(0.5) : room[2].shade200.withOpacity(0.5), ), child: Center(child: Text((index + 1).toString() , style: TextStyle(fontSize: 22, color: Colors.white),)), ), ); } ), ) ], ), ) : SizedBox() ], ) ), ); } }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/pages/select_service.dart
import 'package:day35/animation/FadeAnimation.dart'; import 'package:day35/models/service.dart'; import 'package:day35/pages/cleaning.dart'; import 'package:flutter/material.dart'; class SelectService extends StatefulWidget { const SelectService({ Key? key }) : super(key: key); @override _SelectServiceState createState() => _SelectServiceState(); } class _SelectServiceState extends State<SelectService> { List<Service> services = [ Service('Cleaning', 'https://img.icons8.com/external-vitaliy-gorbachev-flat-vitaly-gorbachev/2x/external-cleaning-labour-day-vitaliy-gorbachev-flat-vitaly-gorbachev.png'), Service('Plumber', 'https://img.icons8.com/external-vitaliy-gorbachev-flat-vitaly-gorbachev/2x/external-plumber-labour-day-vitaliy-gorbachev-flat-vitaly-gorbachev.png'), Service('Electrician', 'https://img.icons8.com/external-wanicon-flat-wanicon/2x/external-multimeter-car-service-wanicon-flat-wanicon.png'), Service('Painter', 'https://img.icons8.com/external-itim2101-flat-itim2101/2x/external-painter-male-occupation-avatar-itim2101-flat-itim2101.png'), Service('Carpenter', 'https://img.icons8.com/fluency/2x/drill.png'), Service('Gardener', 'https://img.icons8.com/external-itim2101-flat-itim2101/2x/external-gardener-male-occupation-avatar-itim2101-flat-itim2101.png'), Service('Tailor', 'https://img.icons8.com/fluency/2x/sewing-machine.png'), Service('Maid', 'https://img.icons8.com/color/2x/housekeeper-female.png'), Service('Driver', 'https://img.icons8.com/external-sbts2018-lineal-color-sbts2018/2x/external-driver-women-profession-sbts2018-lineal-color-sbts2018.png'), Service('Cook', 'https://img.icons8.com/external-wanicon-flat-wanicon/2x/external-cooking-daily-routine-wanicon-flat-wanicon.png'), ]; int selectedService = -1; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, floatingActionButton: selectedService >= 0 ? FloatingActionButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => CleaningPage(), ), ); }, child: Icon(Icons.arrow_forward_ios, size: 20,), backgroundColor: Colors.blue, ) : null, body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverToBoxAdapter( child: FadeAnimation(1.2, Padding( padding: EdgeInsets.only(top: 120.0, right: 20.0, left: 20.0), child: Text( 'Which service \ndo you need?', style: TextStyle( fontSize: 40, color: Colors.grey.shade900, fontWeight: FontWeight.bold, ), ), ), )) ]; }, body: Padding( padding: EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 1.0, crossAxisSpacing: 20.0, mainAxisSpacing: 20.0, ), physics: NeverScrollableScrollPhysics(), itemCount: services.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation((1.0 + index) / 4, serviceContainer(services[index].imageURL, services[index].name, index)); } ), ), ] ), ), ) ); } serviceContainer(String image, String name, int index) { return GestureDetector( onTap: () { setState(() { if (selectedService == index) selectedService = -1; else selectedService = index; }); }, child: AnimatedContainer( duration: Duration(milliseconds: 300), padding: EdgeInsets.all(10.0), decoration: BoxDecoration( color: selectedService == index ? Colors.blue.shade50 : Colors.grey.shade100, border: Border.all( color: selectedService == index ? Colors.blue : Colors.blue.withOpacity(0), width: 2.0, ), borderRadius: BorderRadius.circular(20.0), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.network(image, height: 80), SizedBox(height: 20,), Text(name, style: TextStyle(fontSize: 20),) ] ), ), ); } }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/pages/home.dart
import 'package:day35/animation/FadeAnimation.dart'; import 'package:day35/models/service.dart'; import 'package:flutter/material.dart'; class HomePage extends StatefulWidget { const HomePage({ Key? key }) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { List<Service> services = [ Service('Cleaning', 'https://img.icons8.com/external-vitaliy-gorbachev-flat-vitaly-gorbachev/2x/external-cleaning-labour-day-vitaliy-gorbachev-flat-vitaly-gorbachev.png'), Service('Plumber', 'https://img.icons8.com/external-vitaliy-gorbachev-flat-vitaly-gorbachev/2x/external-plumber-labour-day-vitaliy-gorbachev-flat-vitaly-gorbachev.png'), Service('Electrician', 'https://img.icons8.com/external-wanicon-flat-wanicon/2x/external-multimeter-car-service-wanicon-flat-wanicon.png'), Service('Painter', 'https://img.icons8.com/external-itim2101-flat-itim2101/2x/external-painter-male-occupation-avatar-itim2101-flat-itim2101.png'), Service('Carpenter', 'https://img.icons8.com/fluency/2x/drill.png'), Service('Gardener', 'https://img.icons8.com/external-itim2101-flat-itim2101/2x/external-gardener-male-occupation-avatar-itim2101-flat-itim2101.png'), ]; List<dynamic> workers = [ ['Alfredo Schafer', 'Plumber', 'https://images.unsplash.com/photo-1506803682981-6e718a9dd3ee?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&s=c3a31eeb7efb4d533647e3cad1de9257', 4.8], ['Michelle Baldwin', 'Cleaner', 'https://uifaces.co/our-content/donated/oLkb60i_.jpg', 4.6], ['Brenon Kalu', 'Driver', 'https://uifaces.co/our-content/donated/VUMBKh1U.jpg', 4.4] ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.transparent, title: Text('Dashboard', style: TextStyle(color: Colors.black),), elevation: 0, actions: [ IconButton( onPressed: () {}, icon: Icon(Icons.notifications_none, color: Colors.grey.shade700, size: 30,), ) ], leading: GestureDetector( onTap: () { Navigator.pushNamed(context, '/login'); }, child: Padding( padding: const EdgeInsets.all(10.0), child: CircleAvatar( backgroundImage: NetworkImage('https://uifaces.co/our-content/donated/NY9hnAbp.jpg'), ), ) ), ), body: SingleChildScrollView( child: Column( children: [ FadeAnimation(1, Padding( padding: EdgeInsets.only(left: 20.0, top: 10.0, right: 10.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Recent', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),), TextButton( onPressed: () {}, child: Text('View all',) ) ], ), )), FadeAnimation(1.2, Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Container( padding: EdgeInsets.all(20.0), height: 180, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20.0), boxShadow: [ BoxShadow( color: Colors.grey.shade200, offset: Offset(0, 4), blurRadius: 10.0, ), ], ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: BorderRadius.circular(15.0), child: Image.network('https://images.pexels.com/photos/355164/pexels-photo-355164.jpeg?crop=faces&fit=crop&h=200&w=200&auto=compress&cs=tinysrgb', width: 70,) ), SizedBox(width: 15,), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Isabel Kirkland", style: TextStyle(color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold),), SizedBox(height: 5,), Text("Cleaner", style: TextStyle(color: Colors.black.withOpacity(0.7), fontSize: 18),), ], ) ], ), SizedBox(height: 20,), Container( height: 50, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(15.0) ), child: Center(child: Text('View Profile', style: TextStyle(color: Colors.white, fontSize: 18),)), ) ], ), ), )), SizedBox(height: 20,), FadeAnimation(1.3, Padding( padding: EdgeInsets.only(left: 20.0, right: 10.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Categories', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),), TextButton( onPressed: () {}, child: Text('View all',) ) ], ), )), Container( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), height: 300, child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 1.0, crossAxisSpacing: 10.0, mainAxisSpacing: 10.0, ), physics: NeverScrollableScrollPhysics(), itemCount: services.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation((1.0 + index) / 4, serviceContainer(services[index].imageURL, services[index].name, index)); } ), ), SizedBox(height: 20,), FadeAnimation(1.3, Padding( padding: EdgeInsets.only(left: 20.0, right: 10.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Top Rated', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),), TextButton( onPressed: () {}, child: Text('View all',) ) ], ), )), Container( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10), height: 120, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: workers.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation((1.0 + index) / 4, workerContainer(workers[index][0], workers[index][1], workers[index][2], workers[index][3])); } ), ), SizedBox(height: 150,), ] ) ) ); } serviceContainer(String image, String name, int index) { return GestureDetector( child: Container( margin: EdgeInsets.only(right: 20), padding: EdgeInsets.all(10.0), decoration: BoxDecoration( color: Colors.grey.shade100, border: Border.all( color: Colors.blue.withOpacity(0), width: 2.0, ), borderRadius: BorderRadius.circular(20.0), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.network(image, height: 45), SizedBox(height: 20,), Text(name, style: TextStyle(fontSize: 15),) ] ), ), ); } workerContainer(String name, String job, String image, double rating) { return GestureDetector( child: AspectRatio( aspectRatio: 3.5, child: Container( margin: EdgeInsets.only(right: 20), padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 15.0), decoration: BoxDecoration( color: Colors.white, border: Border.all( color: Colors.grey.shade200, width: 2.0, ), borderRadius: BorderRadius.circular(20.0), ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(15.0), child: Image.network(image) ), SizedBox(width: 20,), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Text(name, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),), SizedBox(height: 5,), Text(job, style: TextStyle(fontSize: 15),) ], ), Spacer(), Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text(rating.toString(), style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),), SizedBox(height: 5,), Icon(Icons.star, color: Colors.orange, size: 20,) ], ) ] ), ), ), ); } }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/pages/start.dart
import 'dart:async'; import 'dart:math'; import 'package:day35/animation/FadeAnimation.dart'; import 'package:day35/models/service.dart'; import 'package:day35/pages/select_service.dart'; import 'package:flutter/material.dart'; class StartPage extends StatefulWidget { const StartPage({ Key? key }) : super(key: key); @override _StartPageState createState() => _StartPageState(); } class _StartPageState extends State<StartPage> { List<Service> services = [ Service('Cleaning', 'https://img.icons8.com/external-vitaliy-gorbachev-flat-vitaly-gorbachev/2x/external-cleaning-labour-day-vitaliy-gorbachev-flat-vitaly-gorbachev.png'), Service('Plumber', 'https://img.icons8.com/external-vitaliy-gorbachev-flat-vitaly-gorbachev/2x/external-plumber-labour-day-vitaliy-gorbachev-flat-vitaly-gorbachev.png'), Service('Electrician', 'https://img.icons8.com/external-wanicon-flat-wanicon/2x/external-multimeter-car-service-wanicon-flat-wanicon.png'), Service('Painter', 'https://img.icons8.com/external-itim2101-flat-itim2101/2x/external-painter-male-occupation-avatar-itim2101-flat-itim2101.png'), Service('Carpenter', 'https://img.icons8.com/fluency/2x/drill.png'), Service('Gardener', 'https://img.icons8.com/external-itim2101-flat-itim2101/2x/external-gardener-male-occupation-avatar-itim2101-flat-itim2101.png'), Service('Tailor', 'https://img.icons8.com/fluency/2x/sewing-machine.png'), Service('Maid', 'https://img.icons8.com/color/2x/housekeeper-female.png'), Service('Driver', 'https://img.icons8.com/external-sbts2018-lineal-color-sbts2018/2x/external-driver-women-profession-sbts2018-lineal-color-sbts2018.png'), ]; int selectedService = 4; @override void initState() { // Randomly select from service list every 2 seconds Timer.periodic(Duration(seconds: 2), (timer) { setState(() { selectedService = Random().nextInt(services.length); }); }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ SizedBox(height: 100,), Container( padding: EdgeInsets.symmetric(horizontal: 50), height: MediaQuery.of(context).size.height * 0.45, width: MediaQuery.of(context).size.width, child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 1.0, crossAxisSpacing: 8.0, mainAxisSpacing: 8.0, ), physics: NeverScrollableScrollPhysics(), itemCount: services.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation((1.0 + index) / 4, serviceContainer(services[index].imageURL, services[index].name, index)); } ), ), Expanded( child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(80), topRight: Radius.circular(80), ) ), child: Column( children: [ SizedBox(height: 50,), FadeAnimation(1.5, Container( padding: EdgeInsets.symmetric(horizontal: 40), child: Center( child: Text( 'Easy, reliable way to take \ncare of your home', textAlign: TextAlign.center, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.grey.shade900, ), ), ), )), SizedBox(height: 20,), FadeAnimation(1.5, Container( padding: EdgeInsets.symmetric(horizontal: 60), child: Center( child: Text( 'We provide you with the best people to help take care of your home.', textAlign: TextAlign.center, style: TextStyle( fontSize: 16, color: Colors.grey.shade600, ), ), ), )), FadeAnimation(1.5, Padding( padding: EdgeInsets.all(50.0), child: MaterialButton( elevation: 0, color: Colors.black, onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => SelectService(), ), ); }, height: 55, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10) ), child: Center( child: Text( 'Get Started', style: TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500, ), ), ), ), )), ], ), ), ) ], ) ); } serviceContainer(String image, String name, int index) { return GestureDetector( onTap: () { }, child: AnimatedContainer( duration: Duration(milliseconds: 500), padding: EdgeInsets.all(8.0), decoration: BoxDecoration( color: selectedService == index ? Colors.white : Colors.grey.shade100, border: Border.all( color: selectedService == index ? Colors.blue.shade100 : Colors.grey.withOpacity(0), width: 2.0, ), borderRadius: BorderRadius.circular(15.0), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.network(image, height: 30), SizedBox(height: 10,), Text(name, style: TextStyle(fontSize: 14),) ] ), ), ); } }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/pages/date_time.dart
import 'package:day35/animation/FadeAnimation.dart'; import 'package:day35/pages/home.dart'; import 'package:flutter/material.dart'; import 'package:scrollable_positioned_list/scrollable_positioned_list.dart'; class DateAndTime extends StatefulWidget { const DateAndTime({ Key? key }) : super(key: key); @override _DateAndTimeState createState() => _DateAndTimeState(); } class _DateAndTimeState extends State<DateAndTime> { int _selectedDay = 2; int _selectedRepeat = 0; String _selectedHour = '13:30'; List<int> _selectedExteraCleaning = []; ItemScrollController _scrollController = ItemScrollController(); final List<dynamic> _days = [ [1, 'Fri'], [2, 'Sat'], [3, 'Sun'], [4, 'Mon'], [5, 'Tue'], [6, 'Wed'], [7, 'Thu'], [8, 'Fri'], [9, 'Sat'], [10, 'Sun'], [11, 'Mon'], [12, 'Tue'], [13, 'Wed'], [14, 'Thu'], [15, 'Fri'], [16, 'Sat'], [17, 'Sun'], [18, 'Mon'], [19, 'Tue'], [20, 'Wed'], [21, 'Thu'], [22, 'Fri'], [23, 'Sat'], [24, 'Sun'], [25, 'Mon'], [26, 'Tue'], [27, 'Wed'], [28, 'Thu'], [29, 'Fri'], [30, 'Sat'], [31, 'Sun'] ]; final List<String> _hours = <String>[ '01:00', '01:30', '02:00', '02:30', '03:00', '03:30', '04:00', '04:30', '05:00', '05:30', '06:00', '06:30', '07:00', '07:30', '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30', '22:00', '22:30', '23:00', '23:30', ]; final List<String> _repeat = [ 'No repeat', 'Every day', 'Every week', 'Every month' ]; final List<dynamic> _exteraCleaning = [ ['Washing', 'https://img.icons8.com/office/2x/washing-machine.png', '10'], ['Fridge', 'https://img.icons8.com/cotton/2x/fridge.png', '8'], ['Oven', 'https://img.icons8.com/external-becris-lineal-color-becris/2x/external-oven-kitchen-cooking-becris-lineal-color-becris.png', '8'], ['Vehicle', 'https://img.icons8.com/external-vitaliy-gorbachev-blue-vitaly-gorbachev/2x/external-bycicle-carnival-vitaliy-gorbachev-blue-vitaly-gorbachev.png', '20'], ['Windows', 'https://img.icons8.com/external-kiranshastry-lineal-color-kiranshastry/2x/external-window-interiors-kiranshastry-lineal-color-kiranshastry-1.png', '20'], ]; @override void initState() { Future.delayed(Duration(milliseconds: 500), () { _scrollController.scrollTo( index: 24, duration: Duration(seconds: 3), curve: Curves.easeInOut, ); }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, floatingActionButton: FloatingActionButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => HomePage(), ), ); }, child: Icon(Icons.arrow_forward_ios), ), body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverToBoxAdapter( child: FadeAnimation(1, Padding( padding: EdgeInsets.only(top: 120.0, right: 20.0, left: 20.0), child: Text( 'Select Date \nand Time', style: TextStyle( fontSize: 35, color: Colors.grey.shade900, fontWeight: FontWeight.bold, ), ), ), )) ]; }, body: Padding( padding: EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 30,), FadeAnimation(1, Row( children: [ Text("October 2021"), Spacer(), IconButton( padding: EdgeInsets.all(0), onPressed: () {}, icon: Icon(Icons.arrow_drop_down_circle_outlined, color: Colors.grey.shade700,), ) ], )), Container( height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, border: Border.all(width: 1.5, color: Colors.grey.shade200), ), child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: _days.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation((1 + index) / 6, GestureDetector( onTap: () { setState(() { _selectedDay = _days[index][0]; }); }, child: AnimatedContainer( duration: Duration(milliseconds: 300), width: 62, decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: _selectedDay == _days[index][0] ? Colors.blue.shade100.withOpacity(0.5) : Colors.blue.withOpacity(0), border: Border.all( color: _selectedDay == _days[index][0] ? Colors.blue : Colors.white.withOpacity(0), width: 1.5, ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_days[index][0].toString(), style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),), SizedBox(height: 10,), Text(_days[index][1], style: TextStyle(fontSize: 16),), ], ), ), )); } ), ), SizedBox(height: 10,), FadeAnimation(1.2, Container( height: 60, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, border: Border.all(width: 1.5, color: Colors.grey.shade200), ), child: ScrollablePositionedList.builder( itemScrollController: _scrollController, scrollDirection: Axis.horizontal, itemCount: _hours.length, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () { setState(() { _selectedHour = _hours[index]; }); }, child: AnimatedContainer( duration: Duration(milliseconds: 300), width: 100, decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: _selectedHour == _hours[index] ? Colors.orange.shade100.withOpacity(0.5) : Colors.orange.withOpacity(0), border: Border.all( color: _selectedHour == _hours[index] ? Colors.orange : Colors.white.withOpacity(0), width: 1.5, ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_hours[index], style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),), ], ), ), ); } ), )), SizedBox(height: 40,), FadeAnimation(1.2, Text("Repeat", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),)), SizedBox(height: 10,), Container( height: 50, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, ), child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: _repeat.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { setState(() { _selectedRepeat = index; }); }, child: FadeAnimation((1.2 + index) / 4, Container( padding: EdgeInsets.symmetric(horizontal: 20), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: _selectedRepeat == index ? Colors.blue.shade400 : Colors.grey.shade100, ), margin: EdgeInsets.only(right: 20), child: Center(child: Text(_repeat[index], style: TextStyle(fontSize: 18, color: _selectedRepeat == index ? Colors.white : Colors.grey.shade800),) ), )), ); }, ) ), SizedBox(height: 40,), FadeAnimation(1.4, Text("Additional Service", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),)), SizedBox(height: 10,), Container( height: 120, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, ), child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: _exteraCleaning.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { setState(() { if (_selectedExteraCleaning.contains(index)) { _selectedExteraCleaning.remove(index); } else { _selectedExteraCleaning.add(index); } }); }, child: FadeAnimation((1.4 + index) / 4, Container( width: 110, decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: _selectedExteraCleaning.contains(index) ? Colors.blue.shade400 : Colors.transparent, ), margin: EdgeInsets.only(right: 20), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Image.network(_exteraCleaning[index][1], height: 40,), SizedBox(height: 10,), Text(_exteraCleaning[index][0], style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: _selectedExteraCleaning.contains(index) ? Colors.white : Colors.grey.shade800),), SizedBox(height: 5,), Text("+${_exteraCleaning[index][2]}\$", style: TextStyle(color: Colors.black),) ], ) )) ); }, ) ), ], ), ), ) ); } }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/models/service.dart
class Service { final String name; final String imageURL; Service(this.name, this.imageURL); }
0
mirrored_repositories/Flutter-home-service-app/lib
mirrored_repositories/Flutter-home-service-app/lib/animation/FadeAnimation.dart
import 'package:flutter/material.dart'; import 'package:simple_animations/simple_animations.dart'; class FadeAnimation extends StatelessWidget { final double delay; final Widget child; FadeAnimation(this.delay, this.child); @override Widget build(BuildContext context) { final tween = MultiTrackTween([ Track("opacity").add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)), Track("translateY").add( Duration(milliseconds: 500), Tween(begin: -30.0, end: 0.0), curve: Curves.easeOut) ]); return ControlledAnimation( delay: Duration(milliseconds: (500 * delay).round()), duration: tween.duration, tween: tween, child: child, builderWithChild: (context, child, animation) => Opacity( opacity: (animation as Map)["opacity"], child: Transform.translate( offset: Offset(0, animation["translateY"]), child: child ), ), ); } }
0
mirrored_repositories/Flutter-home-service-app
mirrored_repositories/Flutter-home-service-app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility 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:day35/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/quittle
mirrored_repositories/quittle/lib/main.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:timezone/data/latest.dart' as tz; import 'package:workmanager/workmanager.dart'; import 'package:provider/provider.dart'; import 'package:rxdart/subjects.dart'; import 'package:quittle/helpers/db_helper.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/providers/settings_provider.dart'; import 'package:quittle/screens/addiction_item_screen.dart'; import 'package:quittle/screens/addictions_screen.dart'; import 'package:quittle/screens/create_addiction_screen.dart'; import 'package:quittle/util/custom_localizations.dart'; import 'package:quittle/util/quotes_constants.dart'; import 'package:quittle/util/progress_constants.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); final BehaviorSubject<ReceivedNotification> didReceiveLocalNotificationSubject = BehaviorSubject<ReceivedNotification>(); final BehaviorSubject<String?> selectNotificationSubject = BehaviorSubject<String?>(); class ReceivedNotification { ReceivedNotification({ required this.id, required this.title, required this.body, required this.payload, }); final int id; final String title; final String body; final String payload; } String? selectedNotificationPayload; // String _initialRoute; void main() async { WidgetsFlutterBinding.ensureInitialized(); Workmanager().initialize( callbackDispatcher, ); tz.initializeTimeZones(); // final NotificationAppLaunchDetails notificationAppLaunchDetails = // await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails(); // _initialRoute = AddictionsScreen.routeName; // if (notificationAppLaunchDetails?.didNotificationLaunchApp ?? false) { // selectedNotificationPayload = notificationAppLaunchDetails.payload; // _initialRoute = AddictionItemScreen.routeName; // } const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('font_awesome_chain'); final InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, ); await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: (String? payload) async { if (payload != null) { debugPrint('notification payload: $payload'); } selectedNotificationPayload = payload; selectNotificationSubject.add(payload); }); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider( create: (_) => new SettingsProvider(), ), ChangeNotifierProvider( create: (_) => new AddictionsProvider(), ), ], child: MaterialApp( localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, AppLocalizations.delegate ], supportedLocales: [ const Locale('en', 'US'), const Locale('tr', 'TR'), ], title: 'Quittle', theme: ThemeData( fontFamily: 'Rubik', primaryColorLight: Color.fromRGBO(230, 86, 81, .8), primaryColor: Color.fromRGBO(230, 86, 81, 1), primaryColorDark: Color.fromRGBO(182, 85, 81, 1), primarySwatch: Colors.red, //TODO custom swatch accentColor: Color.fromRGBO(46, 105, 153, 1), buttonColor: Color.fromRGBO(247, 244, 243, 1), canvasColor: Color.fromRGBO(247, 244, 243, 1), cardColor: Color.fromRGBO(230, 230, 230, 1), hintColor: Colors.blueGrey[800], textTheme: Theme.of(context).textTheme.copyWith( bodyText2: TextStyle( color: Colors.grey[200], ), ), visualDensity: VisualDensity.adaptivePlatformDensity, ), darkTheme: ThemeData( brightness: Brightness.dark, primaryColorLight: Color.fromRGBO(230, 86, 81, .8), primaryColor: Color.fromRGBO(182, 85, 81, 1), primarySwatch: Colors.red, accentColor: Color.fromRGBO(40, 100, 140, 1), buttonColor: Color.fromRGBO(247, 244, 243, 1), cardColor: Color.fromRGBO(55, 55, 55, 1), textTheme: Theme.of(context).textTheme.copyWith( bodyText1: TextStyle( color: Colors.grey[400], ), bodyText2: TextStyle( color: Colors.grey[400], ), headline6: TextStyle( color: Colors.grey[300], ), headline5: TextStyle( color: Colors.grey[300], ), caption: TextStyle( color: Colors.grey[500], ), ), visualDensity: VisualDensity.adaptivePlatformDensity, ), themeMode: ThemeMode.system, // initialRoute: _initialRoute, home: Builder( builder: (context) => FutureBuilder( future: _fetchStartupData(context), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Scaffold( body: Center( child: CircularProgressIndicator(), ), ); } else { _setDailyQuoteNotification(context); return AddictionsScreen(); } }, ), ), routes: { CreateAddictionScreen.routeName: (ctx) => CreateAddictionScreen(), AddictionsScreen.routeName: (ctx) => AddictionsScreen(), AddictionItemScreen.routeName: (ctx) => AddictionItemScreen(), }, ), ); } } Future<void> _fetchStartupData(BuildContext context) async { await Provider.of<AddictionsProvider>(context, listen: false) .fetchAddictions(); await Provider.of<SettingsProvider>(context, listen: false).loadPrefs(); } void _setDailyQuoteNotification(BuildContext context) async { if (Provider.of<SettingsProvider>(context, listen: false) .receiveQuoteNotifs!) { Workmanager().registerPeriodicTask( 'quote-notification', 'quote-notification', inputData: { 'locale': AppLocalizations.of(context)!.localeName, }, frequency: Duration(days: 1), existingWorkPolicy: ExistingWorkPolicy.keep, constraints: Constraints( requiresDeviceIdle: false, requiresBatteryNotLow: false, requiresCharging: false, requiresStorageNotLow: false, networkType: NetworkType.not_required, ), ); } else { Workmanager().cancelByUniqueName('quote-notification'); } } void callbackDispatcher() { Workmanager().executeTask((taskName, inputData) async { switch (taskName) { case 'progress-notification': final addictionData = await DBHelper.getData('addictions', 'id', inputData!['id']); final addiction = Addiction( id: addictionData[0]['id'] as String, name: addictionData[0]['name'] as String, quitDate: addictionData[0]['quit_date'] as String, consumptionType: addictionData[0]['consumption_type'] as int, dailyConsumption: addictionData[0]['daily_consumption'] as double, unitCost: addictionData[0]['unit_cost'] as double, level: addictionData[0]['level'] as int?, ); final nextLevel = addiction.level! + 1; if (addiction.abstinenceTime.inSeconds >= levelDurations[nextLevel].inSeconds) { await DBHelper.update( 'addictions', 'level', addiction.id, nextLevel, ); showProgressNotification( addiction.name.toUpperCase(), progressNotificationMsg(nextLevel, inputData['locale']), ); } // if last achievement level, cancel if (addiction.level == 8) { Workmanager().cancelByUniqueName(addiction.id); } break; case 'quote-notification': final quoteList = quotes[inputData!['locale']]!; Random random = new Random(DateTime.now().millisecondsSinceEpoch); int rndi = random.nextInt(quoteList.length); showQuoteNotification( quoteOfTheDayLocs[inputData['locale']], quoteList[rndi]['quote'], ); break; default: } return Future.value(true); }); } void showProgressNotification( String notificationTitle, String notificationBody) { final androidDetails = AndroidNotificationDetails( 'quitAllProgress', 'progressNotifications', 'quitAllProgressNotifications', ); final genNotDetails = NotificationDetails( android: androidDetails, ); flutterLocalNotificationsPlugin.show( 2, notificationTitle, notificationBody, genNotDetails, ); } void showQuoteNotification( String? notificationTitle, String? notificationBody) { final androidDetails = AndroidNotificationDetails( 'quitAllProgress', 'progressNotifications', 'quitAllProgressNotifications', styleInformation: BigTextStyleInformation(''), ); final genNotDetails = NotificationDetails( android: androidDetails, ); flutterLocalNotificationsPlugin.show( 3, notificationTitle, notificationBody, genNotDetails, ); }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/gifts.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:reorderables/reorderables.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/models/gift.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/providers/settings_provider.dart'; import 'package:quittle/widgets/gifts_create.dart'; class Gifts extends StatefulWidget { final Addiction? data; Gifts({ this.data, }); @override _GiftsState createState() => _GiftsState(); } class _GiftsState extends State<Gifts> { List<Widget>? _tiles; String? currency; List<Widget>? _getTiles(Addiction data) { _tiles = data.gifts! .map<Widget>( (gift) => GiftCard( gift: gift, availableMoney: data.availableMoney, dailyGain: (data.dailyConsumption * data.unitCost), ), ) .toList() ..add( AddGiftButton( id: data.id, ), ); return _tiles; } void _onReorder(int oldIndex, int newIndex) { setState(() { if (_tiles!.elementAt(oldIndex).runtimeType == AddGiftButton || newIndex == _tiles!.length - 1) { return; } Provider.of<AddictionsProvider>(context, listen: false) .reorderGifts(oldIndex, newIndex, widget.data!.id); }); } @override void initState() { Future.delayed(Duration.zero, () { setState(() { Provider.of<AddictionsProvider>(context, listen: false) .fetchGifts(widget.data!.id); }); }); currency = Provider.of<SettingsProvider>(context, listen: false).currency; super.initState(); } @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context); final deviceSize = MediaQuery.of(context).size; return SingleChildScrollView( child: Consumer<AddictionsProvider>(builder: (_, addictionsData, _ch) { return Padding( padding: const EdgeInsets.only(bottom: 8.0), child: ReorderableWrap( direction: Axis.horizontal, scrollDirection: Axis.vertical, alignment: WrapAlignment.start, padding: EdgeInsets.symmetric( horizontal: deviceSize.width * .02, ), maxMainAxisCount: 2, spacing: deviceSize.width * .0399, runSpacing: deviceSize.width * .04, children: _getTiles(widget.data!)!, onReorder: _onReorder, needsLongPressDraggable: true, header: [ Padding( padding: const EdgeInsets.all(16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Row( children: [ Text( local!.available + ' ', style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), ), Text( NumberFormat.simpleCurrency( name: currency, locale: local.localeName, ).format(widget.data!.availableMoney), style: TextStyle( color: Colors.green[800], fontWeight: FontWeight.bold, ), ), ], ), Row( children: [ Text( local.spent + ' ', style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), ), Text( NumberFormat.simpleCurrency( name: currency, locale: local.localeName, ).format(widget.data!.totalSpent), style: TextStyle( color: Colors.green[800], fontWeight: FontWeight.bold, ), ), ], ), ], ), ) ], ), ); }), ); } } class GiftCard extends StatefulWidget { const GiftCard({ Key? key, required this.gift, required this.availableMoney, required this.dailyGain, }) : super(key: key); final Gift gift; final double availableMoney; final double dailyGain; @override _GiftCardState createState() => _GiftCardState(); } class _GiftCardState extends State<GiftCard> { double? percentage; String? currency; @override void initState() { percentage = (widget.availableMoney / widget.gift.price!).clamp(0.0, 1.0); currency = Provider.of<SettingsProvider>(context, listen: false).currency; super.initState(); } @override void didUpdateWidget(covariant GiftCard oldWidget) { percentage = (widget.availableMoney / widget.gift.price!).clamp(0.0, 1.0); super.didUpdateWidget(oldWidget); } @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context)!; final materialLocal = MaterialLocalizations.of(context); final deviceSize = MediaQuery.of(context).size; final giftPrice = NumberFormat.compactSimpleCurrency( name: currency, locale: local.localeName, ).format(widget.gift.price); final daysLeft = ((widget.gift.price! - widget.availableMoney) / widget.dailyGain); final daysLeftClamped = daysLeft.clamp(1, 365); _deleteDialog() { showDialog( context: context, builder: (context) => new AlertDialog( title: Text( local.areYouSure, ), content: Text( local.deleteGiftWarningMsg, ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text( materialLocal.cancelButtonLabel, ), ), TextButton( onPressed: () { Provider.of<AddictionsProvider>(context, listen: false) .deleteGift(widget.gift); Navigator.of(context).pop(); }, child: Text( materialLocal.deleteButtonTooltip, ), ), ], ), ); } return Stack( children: [ SizedBox( height: deviceSize.width * .46, width: deviceSize.width * .46, child: Material( type: MaterialType.transparency, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), side: BorderSide( width: 8, color: t.highlightColor, ), ), child: InkWell( onTap: () => showDialog( context: context, builder: (context) => new AlertDialog( title: Text( widget.availableMoney >= widget.gift.price! ? local.purchaseGiftMsg(giftPrice, widget.gift.name!) : local.notEnoughMoney, ), //'Purchase \"${widget.gift.name!}\" for $giftPrice' actions: [ widget.availableMoney >= widget.gift.price! ? TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text( materialLocal.cancelButtonLabel, ), ) : SizedBox.shrink(), TextButton( onPressed: () { if (widget.availableMoney >= widget.gift.price!) { Provider.of<AddictionsProvider>(context, listen: false) .buyGift(widget.gift); } Navigator.of(context).pop(); }, child: Text( materialLocal.okButtonLabel, ), ), ], ), ), child: DefaultTextStyle( style: t.textTheme.bodyText1!, child: Padding( padding: const EdgeInsets.all(16.0), child: Flex( mainAxisSize: MainAxisSize.max, direction: Axis.vertical, children: [ Flexible( flex: 3, fit: FlexFit.tight, child: Text( widget.gift.name!, style: TextStyle( fontWeight: FontWeight.bold, ), ), ), Flexible( flex: 2, fit: FlexFit.tight, child: Text( giftPrice.toString(), style: TextStyle( color: Colors.green, fontWeight: FontWeight.bold, ), ), ), Flexible( flex: 2, fit: FlexFit.tight, child: Text( (daysLeft < 1 ? '>' : '') + daysLeftClamped.toStringAsFixed(0) + (daysLeft > 365 ? '+' : '') + ' ' + local.daysLeft( daysLeftClamped.toInt(), ), ), ), Flexible( flex: 2, fit: FlexFit.tight, child: Center( child: Text( widget.gift.count.toString() + ' ' + local.purchased, ), ), ), Flexible( flex: 1, child: Stack( alignment: Alignment.center, fit: StackFit.expand, children: [ ClipRRect( borderRadius: BorderRadius.circular(5), child: LinearProgressIndicator( backgroundColor: t.cardColor, valueColor: AlwaysStoppedAnimation( t.accentColor.withOpacity(.8), ), value: percentage, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( (percentage! * 100) .toStringAsFixed(2) .padLeft(6) + "%", style: TextStyle( color: Theme.of(context) .textTheme .bodyText1! .color, fontWeight: percentage == 1 ? FontWeight.w900 : null, fontSize: Theme.of(context) .textTheme .subtitle2! .fontSize, ), ), ], ), ], ), ), Flexible( flex: 1, child: Icon( Icons.drag_handle_rounded, color: t.highlightColor, ), ), ], ), ), ), ), ), ), Positioned( top: 0, right: 0, child: Material( type: MaterialType.circle, color: Colors.transparent, child: InkWell( splashColor: t.errorColor, customBorder: CircleBorder(), child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( Icons.delete, color: t.errorColor.withOpacity(.8), size: t.textTheme.headline6!.fontSize, ), ), onLongPress: _deleteDialog, onTap: _deleteDialog, ), ), ), ], ); } } class AddGiftButton extends StatelessWidget { const AddGiftButton({required this.id}); final String? id; @override Widget build(BuildContext context) { final t = Theme.of(context); final deviceSize = MediaQuery.of(context).size; return ClipRRect( borderRadius: BorderRadius.circular(5), child: Container( height: deviceSize.width * .46, width: deviceSize.width * .46, color: t.highlightColor, child: Material( type: MaterialType.transparency, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), side: BorderSide( width: 8, color: t.highlightColor, ), ), child: InkWell( onTap: () { showModalBottomSheet( backgroundColor: Colors.transparent, useRootNavigator: true, isScrollControlled: true, context: context, builder: (context) => CreateGift(addictionId: id), ); }, child: Center( child: Icon( Icons.add, size: t.textTheme.headline4!.fontSize, // color: t.hintColor, ), ), ), ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/personal_notes_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/models/personal_note.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/widgets/personal_note_create.dart'; import 'package:quittle/widgets/note.dart'; class PersonalNotesView extends StatefulWidget { PersonalNotesView({ required this.addictionData, }); final Addiction addictionData; @override _PersonalNotesViewState createState() => _PersonalNotesViewState(); } class _PersonalNotesViewState extends State<PersonalNotesView> { @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context)!; return Stack( alignment: Alignment.topCenter, children: [ Padding( padding: const EdgeInsets.only(top: 24.0), child: FutureBuilder( future: Provider.of<AddictionsProvider>(context, listen: false) .fetchNotes( widget.addictionData.id, ), builder: (_, snapshot) { return snapshot.error != null ? Center( child: Text(local.genericErrorMessage), ) : Consumer<AddictionsProvider>( builder: (_, addictionsData, _child) => widget.addictionData.personalNotes!.length == 0 ? Note( data: PersonalNote( title: local.yourJourneyBegins, text: local.initialNoteMsg, date: DateTime.now().toString(), ), ) : ListView.builder( shrinkWrap: true, physics: BouncingScrollPhysics(), itemCount: widget.addictionData.personalNotes!.length, itemBuilder: (_, index) { return Padding( padding: const EdgeInsets.only(top: 8.0), child: Note( data: widget.addictionData .personalNotesDateSorted[ index], // todo date sort ascend descend button ), ); }, ), ); }, ), ), FloatingActionButton( heroTag: null, elevation: 12.0, highlightElevation: 8.0, tooltip: local.newNote, onPressed: () { showModalBottomSheet( backgroundColor: Colors.transparent, useRootNavigator: true, isScrollControlled: true, context: context, builder: (_) { return CreatePersonalNote( addictionId: widget.addictionData.id, ); }, ); }, backgroundColor: t.primaryColor, child: Icon( Icons.add, color: Colors.white, ), ), ], ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/target_duration_indicator.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:sleek_circular_slider/sleek_circular_slider.dart'; import 'package:quittle/models/addiction.dart'; class TargetDurationIndicator extends StatelessWidget { TargetDurationIndicator({ required this.data, required this.local, }); final Addiction data; final AppLocalizations local; @override Widget build(BuildContext context) { final t = Theme.of(context); final Duration time = data.abstinenceTime; String targetUnit; int targetValue; double percentage; if (time.inHours < 24) { if (time.inHours < 1) { targetValue = 1; targetUnit = local.hour(1); percentage = time.inMinutes / Duration.minutesPerHour; } else { targetValue = 24; targetUnit = local.hour(targetValue); percentage = time.inMinutes / Duration.minutesPerDay; } } else if (time.inDays < 30) { if (time.inDays < 3) { targetValue = 3; targetUnit = local.day(targetValue); percentage = time.inMinutes / (3 * Duration.minutesPerDay); } else if (time.inDays < 7) { targetValue = 1; targetUnit = local.week(targetValue); percentage = time.inMinutes / (7 * Duration.minutesPerDay); } else { targetValue = 1; targetUnit = local.month(targetValue); percentage = time.inMinutes / (30 * Duration.minutesPerDay); } } else if (time.inDays ~/ 30 < 12) { targetValue = (time.inDays ~/ 30) + 1; targetUnit = local.month(targetValue); percentage = time.inMinutes / (targetValue * 30 * Duration.minutesPerDay); } else { targetValue = (time.inDays ~/ 360) + 1; if (time.inDays / 360 < 1) { targetUnit = local.year(targetValue); percentage = time.inMinutes / 360 * Duration.minutesPerDay; } else { targetUnit = local.year(targetValue); percentage = time.inMinutes / (360 * Duration.minutesPerDay * targetValue); } } return SleekCircularSlider( appearance: CircularSliderAppearance( infoProperties: InfoProperties( bottomLabelText: targetValue.toString() + ' ' + targetUnit, bottomLabelStyle: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), mainLabelStyle: TextStyle( color: t.primaryColor, fontSize: t.textTheme.headline5!.fontSize, fontWeight: FontWeight.bold, ), ), customWidths: CustomSliderWidths( handlerSize: 0, progressBarWidth: t.textTheme.bodyText1!.fontSize, trackWidth: t.textTheme.bodyText1!.fontSize, ), customColors: CustomSliderColors( hideShadow: true, progressBarColors: [ t.accentColor, t.accentColor.withOpacity(.5), ], trackColor: t.accentColor.withAlpha(100), ), animationEnabled: false, ), min: 0, max: 100, initialValue: percentage * 100, ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/duration_counter.dart
import 'dart:async'; import 'package:flutter/material.dart'; class DurationCounter extends StatefulWidget { const DurationCounter({ required this.duration, }); final Duration duration; @override _DurationCounterState createState() => _DurationCounterState(); } class _DurationCounterState extends State<DurationCounter> { String durationAsString = ''; late Duration updatedDuration; String durationString(Duration duration) { String twoDigits(int n) => n.toString().padLeft(2, '0'); String twoDigitHours = twoDigits(duration.inHours.remainder(24)); String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60)); return '${duration.inDays} | $twoDigitHours:$twoDigitMinutes:$twoDigitSeconds'; } @override void initState() { updatedDuration = widget.duration; durationAsString = durationString(updatedDuration); Timer.periodic(Duration(seconds: 1), (timer) { if (mounted) { setState(() { updatedDuration = updatedDuration + Duration(seconds: 1); durationAsString = durationString(updatedDuration); }); } }); super.initState(); } @override Widget build(BuildContext context) { return Text( durationAsString, ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/gifts_create.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/widgets/custom_text_form_field.dart'; class CreateGift extends StatefulWidget { CreateGift({ required this.addictionId, }); final String? addictionId; @override _CreateGiftNoteState createState() => _CreateGiftNoteState(); } class _CreateGiftNoteState extends State<CreateGift> { final GlobalKey<FormState> _formKey = GlobalKey(); late FocusNode formFocusNode; var giftData = { 'name': '', 'price': 0.0, }; void trySubmit(BuildContext ctx) { final isValid = _formKey.currentState!.validate(); FocusScope.of(context).unfocus(); if (isValid) { _formKey.currentState!.save(); Provider.of<AddictionsProvider>(context, listen: false).createGift( giftData, widget.addictionId, ); Navigator.of(ctx).pop(); } } @override void initState() { formFocusNode = FocusNode(); formFocusNode.requestFocus(); super.initState(); } @override void dispose() { formFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context)!; final inputBackgroundColor = t.canvasColor; final buttonHeight = t.buttonTheme.height * 2; return DefaultTextStyle( style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), child: Form( key: _formKey, child: Container( decoration: BoxDecoration( color: t.cardColor, borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), ), ), padding: EdgeInsets.only( top: 20, bottom: 8, left: 8, right: 8, ), child: Wrap( runSpacing: 20, children: [ CustomTextFormField( valKey: 'name', data: giftData, inputName: local.title, focusNode: null, inputType: TextInputType.name, backgroundColor: inputBackgroundColor, ), CustomTextFormField( valKey: 'price', data: giftData, inputName: local.price, focusNode: null, inputType: TextInputType.number, backgroundColor: inputBackgroundColor, validator: (value) { if (double.tryParse(value) == null) { return local.pleaseEnterANumber; } else if (double.parse(value) < 0) { return local.valueMustBePositive; } else { return null; } }, ), SizedBox( height: buttonHeight, child: TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(inputBackgroundColor), ), onPressed: () { trySubmit(context); }, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.save, color: t.primaryColorLight, ), Text( local.save, style: TextStyle( color: t.primaryColorLight, fontWeight: FontWeight.bold, ), ), ], ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/addiction_item_card.dart
import 'dart:async'; import 'dart:io'; import 'dart:ui' as ui; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:animations/animations.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share/share.dart'; import 'package:uuid/uuid.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/models/addiction_item_screen_args.dart'; import 'package:quittle/screens/addiction_item_screen.dart'; import 'package:quittle/widgets/addiction_progress.dart'; class AddictionItemCard extends StatelessWidget { AddictionItemCard({ required this.addictionData, required this.onDelete, required key, }) : super(key: key); final Addiction addictionData; final Function onDelete; final GlobalKey _cardKey = GlobalKey(); @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context); final isDark = MediaQuery.of(context).platformBrightness == Brightness.dark; _share() async { RenderRepaintBoundary boundary = _cardKey.currentContext!.findRenderObject() as RenderRepaintBoundary; ui.Image image = await boundary.toImage(pixelRatio: 2.0); ByteData byteData = await (image.toByteData( format: ui.ImageByteFormat.png) as FutureOr<ByteData>); Uint8List pngBytes = byteData.buffer.asUint8List(); final directory = (await getApplicationDocumentsDirectory()).path; File imgFile = File('$directory/screenshot_shared.png'); await imgFile.writeAsBytes(pngBytes); Share.shareFiles( ['$directory/screenshot_shared.png'], text: local!.shareMsg, subject: local.shareMsgSubject, ); } return Container( margin: const EdgeInsets.all(8.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), border: Border.all( width: 0, style: BorderStyle.none, ), color: isDark ? t.highlightColor.withOpacity(.1) : t.accentColor, ), padding: const EdgeInsets.only(bottom: 4), child: OpenContainer( closedColor: isDark ? t.highlightColor.withOpacity(.1) : t.accentColor, closedShape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), side: BorderSide( width: 3, color: t.highlightColor, ), ), transitionDuration: Duration(milliseconds: 250), openBuilder: (context, action) => AddictionItemScreen(), routeSettings: RouteSettings( arguments: AddictionItemScreenArgs(addictionData), ), closedBuilder: (context, action) => Slidable( key: ValueKey(Uuid().v1()), actionPane: SlidableDrawerActionPane(), actionExtentRatio: .25, fastThreshold: .1, dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), dismissThresholds: <SlideActionType, double>{ SlideActionType.primary: 1.0, SlideActionType.secondary: .5 }, onDismissed: (actionType) { if (actionType == SlideActionType.primary) return; onDelete(addictionData.id); }, ), actions: [ IconSlideAction( caption: local!.share, color: t.accentColor, icon: Icons.share, onTap: _share, ), ], secondaryActions: [ IconSlideAction( caption: local.delete, color: t.errorColor, icon: Icons.delete, ), ], child: RepaintBoundary( key: _cardKey, child: Material( type: MaterialType.card, shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: t.highlightColor, ), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Flex( direction: Axis.horizontal, children: [ Flexible( flex: 1, child: Center( child: Text( addictionData.name.toUpperCase(), overflow: TextOverflow.ellipsis, style: TextStyle( fontWeight: FontWeight.bold, fontSize: Theme.of(context) .textTheme .headline5! .fontSize, color: t.textTheme.bodyText1!.color, ), ), ), ), Spacer( flex: 1, ) ], ), AddictionProgress( addictionData: addictionData, ) ], ), ), ), ), ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/addiction_item.dart
import 'package:flutter/material.dart'; import 'package:quittle/models/addiction_item_screen_args.dart'; import 'package:quittle/widgets/addiction_details.dart'; import 'package:quittle/widgets/addiction_progress.dart'; import 'package:quittle/widgets/personal_notes_view.dart'; class AddictionItem extends StatelessWidget { const AddictionItem({ required this.args, }); final AddictionItemScreenArgs args; @override Widget build(BuildContext context) { final t = Theme.of(context); final isDark = MediaQuery.of(context).platformBrightness == Brightness.dark; return Container( color: isDark ? t.highlightColor.withOpacity(.1) : t.accentColor, child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( color: t.canvasColor, child: AddictionProgress( addictionData: args.data, ), ), AddictionDetails( addictionData: args.data, ), PersonalNotesView( addictionData: args.data, ), ], ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/addiction_progress.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/providers/settings_provider.dart'; import 'package:quittle/util/progress_constants.dart'; import 'package:quittle/widgets/target_duration_indicator.dart'; class AddictionProgress extends StatelessWidget { const AddictionProgress({ Key? key, required this.addictionData, }) : super(key: key); final Addiction addictionData; @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context)!; final consumptionType = (addictionData.consumptionType == 1) ? local.hour(addictionData.notUsedCount.toInt()) : local.times(addictionData.notUsedCount.toInt()); return Padding( padding: const EdgeInsets.only(top: 16.0), child: Flex( direction: Axis.horizontal, mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ Flexible( flex: 1, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ DefaultTextStyle( style: t.textTheme.bodyText1!.copyWith( fontSize: t.textTheme.subtitle1!.fontSize, fontWeight: FontWeight.bold, ), child: Column( children: [ Text( local.level + ' ' + (addictionData.level! + 1).toString(), ), Text( getLevelNames(local.localeName)[addictionData.level!], ) ], ), ), Divider( color: Colors.transparent, thickness: 0, ), DefaultTextStyle( style: t.textTheme.bodyText1!.copyWith( fontSize: t.textTheme.subtitle1!.fontSize, fontWeight: FontWeight.bold, ), child: FittedBox( fit: BoxFit.contain, child: addictionData.unitCost == 0 ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(local.savedFor), Text( addictionData.consumptionType == 0 ? addictionData.notUsedCount .toStringAsFixed(2) : addictionData.notUsedCount .toStringAsFixed(0) + ' ' + consumptionType, style: TextStyle( color: Colors.red, ), ), ], ) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( local.moneySaved, ), Consumer<SettingsProvider>( builder: (_, settings, _ch) => Text( NumberFormat.simpleCurrency( name: settings.currency, locale: local.localeName, decimalDigits: 2, ).format( addictionData.totalSaved, ), style: TextStyle( color: Colors.green[800], ), ), ), ], ), ), ), ], ), ), Flexible( flex: 2, child: TargetDurationIndicator( data: addictionData, local: local, ), ), ], ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/note.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:quittle/models/personal_note.dart'; class Note extends StatelessWidget { final PersonalNote data; Note({ required this.data, }); @override Widget build(BuildContext context) { final t = Theme.of(context); final _controller = TextEditingController(text: data.text); final local = AppLocalizations.of(context)!; final quitDateFormatted = DateFormat.yMMMd(local.localeName).format(DateTime.parse(data.date!)); return Container( decoration: BoxDecoration( color: t.canvasColor, borderRadius: BorderRadius.circular(5.0), border: Border.all( color: t.highlightColor, width: 1, ), ), margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Flex( direction: Axis.horizontal, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Flexible( flex: 2, fit: FlexFit.tight, child: Text( data.title!, style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), ), ), Flexible( flex: 3, fit: FlexFit.tight, child: Text( quitDateFormatted, textAlign: TextAlign.right, style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), ), ), ], ), Container( child: TextField( maxLines: null, minLines: 1, controller: _controller, readOnly: true, scrollController: new ScrollController(), scrollPhysics: PageScrollPhysics(), enabled: true, style: TextStyle( color: t.hintColor, fontWeight: FontWeight.normal, ), decoration: InputDecoration( border: InputBorder.none, ), ), ), ], ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/settings_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:quittle/providers/settings_provider.dart'; import 'package:quittle/widgets/currency_picker.dart'; class SettingsView extends StatefulWidget { @override _SettingsViewState createState() => _SettingsViewState(); } class _SettingsViewState extends State<SettingsView> { bool? _progressCheck = false; bool? _quoteCheck = false; late SettingsProvider settings; String? currency; @override void initState() { settings = Provider.of<SettingsProvider>(context, listen: false); _progressCheck = settings.receiveProgressNotifs; _quoteCheck = settings.receiveQuoteNotifs; currency = settings.currency; super.initState(); } void _updateCurrency(String newCurrency) { setState(() { currency = newCurrency; }); } @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context); return Drawer( child: LayoutBuilder( builder: (context, constraints) => SingleChildScrollView( child: Container( child: ConstrainedBox( constraints: constraints.copyWith( minHeight: constraints.maxHeight, maxHeight: double.infinity, ), child: IntrinsicHeight( child: SafeArea( child: Column( children: [ Column( children: [ Container( height: kToolbarHeight, width: double.infinity, child: DrawerHeader( decoration: BoxDecoration( border: Border( bottom: BorderSide( width: 0, color: t.primaryColor, ), ), ), child: Text( local!.settings, style: TextStyle( fontSize: Theme.of(context) .textTheme .headline6! .fontSize, fontWeight: FontWeight.bold, color: t.primaryColor, ), ), ), ), SwitchListTile( contentPadding: const EdgeInsets.symmetric( vertical: 24, horizontal: 8), title: Text( local.progressNotification, ), subtitle: Text( local.progressNotificationDesc, style: TextStyle( color: t.hintColor, ), ), value: _progressCheck!, activeColor: t.accentColor, onChanged: (value) { if (mounted) { setState(() { settings.allowProgressNotif(value); _progressCheck = value; }); } }, ), Divider( height: 0, thickness: 1, ), SwitchListTile( contentPadding: const EdgeInsets.symmetric( vertical: 24, horizontal: 8), title: Text( local.quoteOfTheDay, ), subtitle: Text( local.quoteOfTheDayDesc, style: TextStyle( color: t.hintColor, ), ), value: _quoteCheck!, activeColor: t.accentColor, onChanged: (value) { if (mounted) { setState(() { settings.allowQuoteNotif(value); _quoteCheck = value; }); } }, ), Divider( height: 0, thickness: 1, ), ListTile( dense: true, onTap: () => showDialog( context: context, builder: (context) => CurrencyPicker(onUpdate: _updateCurrency), ), contentPadding: const EdgeInsets.symmetric( vertical: 24, horizontal: 8), leading: FaIcon(FontAwesomeIcons.moneyBillWave), title: Text( local.currency, style: TextStyle( fontSize: Theme.of(context) .textTheme .subtitle2! .fontSize, color: t.hintColor, ), ), trailing: Text( '$currency (${NumberFormat.simpleCurrency( name: currency, locale: local.localeName, ).currencySymbol})', style: TextStyle( color: t.accentColor, fontWeight: FontWeight.bold, fontSize: Theme.of(context) .textTheme .subtitle1! .fontSize, ), ), ), Divider( height: 0, thickness: 1, ), ], ), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( local.appName.toUpperCase(), style: TextStyle( color: t.primaryColor, fontWeight: FontWeight.bold, ), ), Row( children: [ IconButton( icon: FaIcon( FontAwesomeIcons.infoCircle, color: t.primaryColor, ), tooltip: local.licenses, onPressed: () { showDialog( context: context, builder: (context) => AboutDialog( applicationName: local.appName, applicationIcon: SizedBox.fromSize( size: Size.square(16.0), child: Image.asset( 'assets/images/font_awesome_chain.png', ), ), applicationVersion: '1.0.1', children: [ Column( crossAxisAlignment: CrossAxisAlignment .stretch, children: [ TextButton( onPressed: () { _launchURL( 'https://fontawesome.com/license/free'); }, child: Text( 'FontAwesome Free License', ), ), TextButton( onPressed: () { _launchURL( 'https://fontawesome.com/icons/link?style=solid'); }, child: Text( local.appIcon, ), ), ], ) ], applicationLegalese: local.applicationLegalese, ), ); }, ), IconButton( icon: FaIcon( FontAwesomeIcons.twitter, color: Color.fromRGBO(29, 161, 242, 1), ), tooltip: 'Twitter', onPressed: () { _launchURL( 'https://twitter.com/onur_ldz'); }, ), IconButton( icon: FaIcon( FontAwesomeIcons.github, ), tooltip: 'GitHub', onPressed: () { _launchURL( 'https://github.com/onur-yildiz'); }, ), ], ), ], ), ], ), ), ), ], ), ), ), ), ), ), ), ); } } void _launchURL(url) async => await canLaunch(url) ? await launch(url) : throw 'Could not launch $url';
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/achievements.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:confetti/confetti.dart'; import 'package:liquid_progress_indicator_ns/liquid_progress_indicator.dart'; import 'package:quittle/extensions/duration_extension.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/util/progress_constants.dart'; class Achievements extends StatefulWidget { final Addiction? data; const Achievements({ this.data, }); @override _AchievementsState createState() => _AchievementsState(); } class _AchievementsState extends State<Achievements> { int? maxAchLevel; late List localizedAchDurations; int? achLevel; late double percentage; initialAnimation() { final num targetPercentage = (widget.data!.abstinenceTime.inMinutes / achievementDurations.last.inMinutes) .clamp(0.0, 1.0); final targetLevel = widget.data!.achievementLevel; int nextAchLevel = 1; Timer.periodic(Duration(milliseconds: 100), (timer) { if (percentage < targetPercentage && mounted) { setState(() { percentage += .01; if ((achievementDurations[nextAchLevel].inMinutes / achievementDurations.last.inMinutes) <= percentage && achLevel! < targetLevel!) { achLevel = nextAchLevel; nextAchLevel++; } }); } else { percentage.clamp(0.0, 1.0); timer.cancel(); } }); } @override void initState() { percentage = 0.0; achLevel = 0; maxAchLevel = achievementDurations.length - 1; initialAnimation(); localizedAchDurations = List.filled(achievementDurations.length, ''); Future.delayed(Duration.zero, () { setState(() { _getLocalizedAchievementDurations(AppLocalizations.of(context)); }); }); super.initState(); } double getVerticalPosition(double height, int level) { double pos = 0.0; for (var i = 0; i < level; i++) { pos += ((achievementDurations[(i + 1)].inDays - achievementDurations[(i)].inDays) / 30) * height; } return pos; } void _getLocalizedAchievementDurations(AppLocalizations? local) { localizedAchDurations[0] = 'A New Start!'; for (var i = 1; i < achievementDurations.length; i++) { if (achievementDurations[i].inDays < 30) { localizedAchDurations[i] = ('${achievementDurations[i].inDays} ${local!.day(achievementDurations[i].inDays)}'); } else if (achievementDurations[i].inDays < 360) { final int inMonths = (achievementDurations[i].inDays / 30).floor(); localizedAchDurations[i] = ('$inMonths ${local!.month(inMonths)}'); } else { final int inYears = (achievementDurations[i].inDays / 360).floor(); localizedAchDurations[i] = ('$inYears ${local!.year(inYears)}'); } } } @override void didUpdateWidget(covariant Achievements oldWidget) { percentage = (widget.data!.abstinenceTime.inMinutes / achievementDurations.last.inMinutes) .clamp(0.0, 1.0); super.didUpdateWidget(oldWidget); } @override Widget build(BuildContext context) { final deviceSize = MediaQuery.of(context).size; final t = Theme.of(context); final double tileHeight = deviceSize.width; double totalHeight = 0.0; List achievementHeights = []; for (var i = 0; i < maxAchLevel!; i++) { achievementHeights.add( tileHeight * (achievementDurations[i + 1] - achievementDurations[i]).in30s, ); totalHeight += achievementHeights[i]; } // LiquidLinearProgressIndicator is not used exclusively because when height grows waves get too steep, //so an AnimatedContainer is used as a progress bar and LiquidLinearProgressIndicator is put to the top of the bar to give liquid effect. return Scaffold( body: SingleChildScrollView( reverse: true, child: Stack( children: [ AnimatedPositioned( duration: Duration(milliseconds: 100), // TODO make a custom liquidprogressindicator that eliminates the need of the AnimatedContainer // LiquidLinearProgressIndicator has an unremovable border -.17 overlaps it (Pixel 4) bottom: totalHeight * percentage - .17, child: Container( width: deviceSize.width, height: tileHeight * .2, child: Stack( clipBehavior: Clip.none, children: [ LiquidLinearProgressIndicator( value: .8, valueColor: AlwaysStoppedAnimation( t.accentColor.withOpacity(.5), ), backgroundColor: Colors.transparent, direction: Axis.vertical, borderWidth: 0, borderColor: Colors.transparent, borderRadius: 0, ), ], ), ), ), Column( children: [ Container( height: tileHeight, width: deviceSize.width, child: Center( child: FaIcon( FontAwesomeIcons.checkCircle, color: achLevel == maxAchLevel ? Colors.amber : t.highlightColor, size: tileHeight / 2, ), ), ), Container( height: totalHeight, child: Stack( alignment: Alignment.bottomCenter, children: [ AnimatedContainer( duration: Duration(milliseconds: 100), height: totalHeight * percentage, decoration: BoxDecoration( gradient: LinearGradient( colors: [ t.accentColor, t.accentColor.withOpacity(.5), ], stops: [percentage.clamp(.0, .8), 1], begin: Alignment.bottomCenter, end: Alignment.topCenter, ), ), ), ...List<Widget>.generate( maxAchLevel!, (index) => Positioned( bottom: getVerticalPosition(tileHeight, index), child: Trophy( title: localizedAchDurations[index + 1], // subtitle: localizedAchDurations[index + 1], level: index + 1, height: achievementHeights[index], trophySize: t.textTheme.headline3!.fontSize! * (index + 1).clamp(0.0, deviceSize.width * .5), active: index + 1 <= achLevel! ? true : false, ), ), ).reversed ], ), ), ], ), ], ), ), ); } } class Trophy extends StatefulWidget { final int level; final double height; final double trophySize; final bool active; final String title; final String subtitle; Trophy({ this.level = 1, this.height = 100, this.trophySize = 60, this.active = true, this.title = '', this.subtitle = '', }); @override _TrophyState createState() => _TrophyState(); } class _TrophyState extends State<Trophy> { late ConfettiController _confettiController; bool _isPlayed = false; @override void initState() { _confettiController = ConfettiController( duration: Duration(seconds: 1), ); super.initState(); } @override void dispose() { _confettiController.dispose(); super.dispose(); } @override void didUpdateWidget(covariant Trophy oldWidget) { if (widget.active && !_isPlayed) { _confettiController.play(); // _isPlayed = true; } super.didUpdateWidget(oldWidget); } @override Widget build(BuildContext context) { final t = Theme.of(context); final color = widget.active ? Colors.amber : t.highlightColor; final stars = List<FaIcon>.filled( widget.level, FaIcon( FontAwesomeIcons.solidStar, color: color, size: widget.trophySize * .25, ), ); final bool isTitleOverflowed = widget.trophySize / widget.title.length < t.textTheme.bodyText1!.fontSize!; final bool isSubtitleOverflowed = widget.trophySize / widget.subtitle.length < t.textTheme.bodyText1!.fontSize!; return ConfettiWidget( confettiController: _confettiController, blastDirectionality: BlastDirectionality.explosive, colors: [ t.primaryColor, Colors.amber, ], numberOfParticles: widget.level, particleDrag: .1, gravity: .4, child: Container( height: widget.height, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Stack( alignment: Alignment.topCenter, clipBehavior: Clip.none, children: [ Padding( padding: EdgeInsets.only( top: isTitleOverflowed ? t.textTheme.bodyText1!.fontSize! * (isSubtitleOverflowed ? 2 : 1) : 0.0, ), child: FaIcon( FontAwesomeIcons.trophy, color: color, size: widget.trophySize, ), ), Positioned( top: isTitleOverflowed ? 0 : widget.trophySize * .25, child: Text( widget.title, style: TextStyle( color: !widget.active ? t.hintColor.withOpacity(.5) : isTitleOverflowed ? Colors.amber : t.accentColor, ), ), ), Positioned( top: isSubtitleOverflowed ? t.textTheme.bodyText1!.fontSize : widget.trophySize * .4, child: Text( widget.subtitle, style: TextStyle( color: widget.active ? Colors.amber : t.hintColor.withOpacity(.5), ), ), ), ], ), SizedBox( width: widget.trophySize, child: Wrap( alignment: WrapAlignment.center, direction: Axis.horizontal, children: [ ...stars, ], ), ), ], ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/custom_text_form_field.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class CustomTextFormField extends StatelessWidget { const CustomTextFormField( {Key? key, required this.valKey, required this.data, required this.inputName, this.focusNode, this.inputType, this.validator, this.inputAction, this.backgroundColor, this.onSubmit, this.maxLength}) : super(key: key); final String valKey; final Map<String, Object?> data; final String inputName; final TextInputType? inputType; final Function? validator; final FocusNode? focusNode; final TextInputAction? inputAction; final Color? backgroundColor; final Function? onSubmit; final int? maxLength; @override Widget build(BuildContext context) { if (onSubmit == null && inputAction == TextInputAction.done) throw 'Error: onSubmit == null && inputAction == TextInputAction.done. Provide an onSubmit function.'; final t = Theme.of(context); return TextFormField( onFieldSubmitted: (_) { if (inputAction != TextInputAction.done) return; onSubmit!(); }, focusNode: focusNode, key: ValueKey(valKey), decoration: InputDecoration( filled: true, fillColor: backgroundColor != null ? backgroundColor : t.canvasColor, border: OutlineInputBorder( borderRadius: BorderRadius.circular(5), borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(5), borderSide: BorderSide( width: 0, color: t.primaryColorDark, style: BorderStyle.solid, ), ), labelText: inputName, labelStyle: TextStyle( fontWeight: FontWeight.bold, ), ), style: TextStyle( color: t.hintColor, ), cursorColor: t.primaryColor, keyboardType: inputType, validator: validator as String? Function(String?)?, textInputAction: inputAction, maxLength: maxLength, maxLengthEnforcement: MaxLengthEnforcement.enforced, textCapitalization: TextCapitalization.sentences, onEditingComplete: () => inputAction == TextInputAction.done ? FocusScope.of(context).unfocus() : FocusScope.of(context).nextFocus(), onSaved: (input) { var value; switch (data[valKey].runtimeType) { case int: value = input is int ? input : int.parse(input!); break; case double: value = input is double ? input : double.parse(input!); break; case String: value = input is String ? input : input.toString(); break; default: break; } data[valKey] = value; }, ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/currency_picker.dart
import 'dart:convert' show json; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:quittle/providers/settings_provider.dart'; class CurrencyPicker extends StatefulWidget { final Function? onUpdate; const CurrencyPicker({ this.onUpdate, }); @override _CurrencyPickerState createState() => _CurrencyPickerState(); } class _CurrencyPickerState extends State<CurrencyPicker> { List? _currencies = []; Future<void> getJson() async { final String response = await rootBundle.loadString('assets/data/currencies.json'); _currencies = await json.decode(response); setState(() {}); } @override void initState() { getJson(); super.initState(); } @override Widget build(BuildContext context) { final t = Theme.of(context); final mediaQuery = MediaQuery.of(context); final deviceHeight = mediaQuery.size.height; final deviceWidth = mediaQuery.size.width; return new SimpleDialog( backgroundColor: t.cardColor, contentPadding: EdgeInsets.zero, children: [ SingleChildScrollView( physics: BouncingScrollPhysics(), child: SizedBox( height: deviceHeight * .8, width: deviceWidth * .4, child: ListView.builder( itemCount: _currencies!.length, itemBuilder: (context, index) => TextButton( style: ButtonStyle( shape: MaterialStateProperty.all( BeveledRectangleBorder(), ), backgroundColor: MaterialStateProperty.all( t.canvasColor, ), foregroundColor: MaterialStateProperty.all( t.hintColor, ), tapTargetSize: MaterialTapTargetSize.shrinkWrap, padding: MaterialStateProperty.all( const EdgeInsets.all(16.0), ), ), onPressed: () { Provider.of<SettingsProvider>(context, listen: false) .updateCurrency(_currencies![index]['code']); widget.onUpdate!(_currencies![index]['code']); Navigator.of(context).pop(_currencies![index]['code']); }, child: Text( _currencies![index]['code'], style: TextStyle( color: t.accentColor, ), ), ), ), ), ), ], ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/personal_note_create.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/widgets/custom_text_form_field.dart'; class CreatePersonalNote extends StatefulWidget { CreatePersonalNote({ required this.addictionId, }); final String? addictionId; @override _CreatePersonalNoteState createState() => _CreatePersonalNoteState(); } class _CreatePersonalNoteState extends State<CreatePersonalNote> { final GlobalKey<FormState> _formKey = GlobalKey(); late FocusNode formFocusNode; var noteData = { 'title': '', 'text': '', 'date': DateTime.now().toString(), }; Future<void> _selectDate(context) async { final date = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime.now().subtract(Duration(days: 365)), lastDate: DateTime.now(), ); if (mounted) { setState(() { if (date != null) { noteData['date'] = date.toString(); } else { noteData['date'] = DateTime.now().toString(); } }); } } void trySubmit(BuildContext ctx) { final isValid = _formKey.currentState!.validate(); FocusScope.of(context).unfocus(); if (isValid) { _formKey.currentState!.save(); Provider.of<AddictionsProvider>(context, listen: false).createNote( noteData, widget.addictionId, ); Navigator.of(ctx).pop(); } } @override void initState() { formFocusNode = FocusNode(); formFocusNode.requestFocus(); super.initState(); } @override void dispose() { formFocusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context)!; final deviceWidth = MediaQuery.of(context).size.width; final inputBackgroundColor = t.canvasColor; final buttonHeight = t.buttonTheme.height * 2; return DefaultTextStyle( style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), child: Form( key: _formKey, child: Container( decoration: BoxDecoration( color: t.cardColor, borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), ), ), padding: EdgeInsets.only( bottom: 8, top: 20, left: 8, right: 8, ), child: Wrap( runSpacing: 20, children: [ CustomTextFormField( valKey: 'title', data: noteData, inputName: local.title, focusNode: null, inputType: TextInputType.name, backgroundColor: inputBackgroundColor, ), TextFormField( cursorColor: t.primaryColor, decoration: InputDecoration( filled: true, fillColor: inputBackgroundColor, border: OutlineInputBorder( borderRadius: BorderRadius.circular(5), borderSide: BorderSide( width: 0, style: BorderStyle.none, ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(5), borderSide: BorderSide( width: 0, color: t.primaryColorLight, style: BorderStyle.solid, ), ), hintText: local.note, ), style: TextStyle( color: t.hintColor, ), keyboardType: TextInputType.multiline, textInputAction: TextInputAction.newline, minLines: 8, maxLines: null, maxLength: 100, maxLengthEnforcement: MaxLengthEnforcement.enforced, onSaved: (newValue) => noteData['text'] = newValue!.trim(), ), SizedBox( height: buttonHeight, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Material( type: MaterialType.button, color: inputBackgroundColor, borderRadius: BorderRadius.circular(5), child: InkWell( onTap: () { if (mounted) { setState(() { _selectDate(context); }); } }, splashColor: t.primaryColor, borderRadius: BorderRadius.circular(5), child: Padding( padding: const EdgeInsets.all(10), child: Center( child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( DateFormat('dd/MM/yyyy').format( DateTime.parse(noteData['date']!), ), style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold), ), SizedBox( width: deviceWidth * .1, child: Icon( Icons.date_range, color: t.primaryColor, ), ), ], ), ), ), ), ), SizedBox( height: double.maxFinite, child: TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(inputBackgroundColor), ), onPressed: () { trySubmit(context); }, child: Padding( padding: EdgeInsets.symmetric( horizontal: t.textTheme.headline6!.fontSize!, ), child: Row( children: [ Icon( Icons.save, color: t.primaryColor, ), Text( local.save, style: TextStyle( color: t.primaryColor, fontWeight: FontWeight.bold, ), ), ], ), ), ), ) ], ), ), ], ), ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/widgets/addiction_details.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:intl/intl.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/providers/settings_provider.dart'; import 'package:quittle/widgets/duration_counter.dart'; class AddictionDetails extends StatelessWidget { const AddictionDetails({ required this.addictionData, }); final Addiction addictionData; @override Widget build(BuildContext context) { final t = Theme.of(context); final double notUsedCount = addictionData.notUsedCount; final Duration abstinenceTime = addictionData.abstinenceTime; final double dailySavings = addictionData.dailyConsumption * addictionData.unitCost; final local = AppLocalizations.of(context)!; final currency = Provider.of<SettingsProvider>(context).currency; final String quitDateFormatted = DateFormat.yMMMd(local.localeName).format(addictionData.quitDateTime); final consumptionType = ((addictionData.consumptionType == 1) ? local.hour( notUsedCount.toInt(), ) : local.times( notUsedCount.toInt(), )); return DefaultTextStyle( style: t.textTheme.bodyText2!.copyWith( fontWeight: FontWeight.bold, ), child: Padding( padding: const EdgeInsets.all(16.0), child: Wrap( direction: Axis.horizontal, alignment: WrapAlignment.spaceBetween, runSpacing: 8.0, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.startDate), Text(quitDateFormatted), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.duration), DurationCounter(duration: abstinenceTime), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.dailyUse), Text( (addictionData.dailyConsumption % 1 == 0 ? addictionData.dailyConsumption.toStringAsFixed(0) : addictionData.dailyConsumption.toString()) + ' ' + consumptionType, ), ], ), Divider(), Text(local.futureSavings), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.daily), Text( NumberFormat.simpleCurrency( name: currency, locale: local.localeName, ).format(dailySavings), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.weekly), Text( NumberFormat.simpleCurrency( name: currency, locale: local.localeName, ).format(dailySavings * 7), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.monthly), Text( NumberFormat.simpleCurrency( name: currency, locale: local.localeName, ).format(dailySavings * 30), ), ], ), Divider(), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(local.totalNotUsed), Text( addictionData.consumptionType == 1 ? addictionData.notUsedCount.toStringAsFixed(0) : addictionData.notUsedCount.toStringAsFixed(1) + ' ' + consumptionType, ), ], ), ], ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/models/addiction.dart
import 'package:flutter/foundation.dart'; import 'package:quittle/models/personal_note.dart'; import 'package:quittle/models/gift.dart'; enum ConsumptionType { quantity, hour } class Addiction { final String id; final String name; final String quitDate; final int consumptionType; final double dailyConsumption; final double unitCost; List<PersonalNote>? personalNotes; List<Gift>? gifts; int? level; int? achievementLevel; int? sortOrder; Addiction({ required this.id, required this.name, required this.quitDate, required this.consumptionType, required this.dailyConsumption, required this.unitCost, this.personalNotes, this.gifts, this.level, this.achievementLevel, this.sortOrder, }); DateTime get quitDateTime { return DateTime.parse(quitDate); } Duration get abstinenceTime { return DateTime.now().difference(quitDateTime); } double get notUsedCount { if (consumptionType == 0) { return (dailyConsumption / Duration.secondsPerDay) * abstinenceTime.inSeconds; } return ((dailyConsumption / Duration.secondsPerDay) * abstinenceTime.inSeconds) .floorToDouble(); } double get totalSaved { return notUsedCount * unitCost; } double get totalSpent { double total = 0.0; gifts!.forEach((gift) { total += gift.price! * gift.count!; }); return total; } double get availableMoney { return totalSaved - totalSpent; } List<PersonalNote> get personalNotesDateSorted { List<PersonalNote> list = [...personalNotes!]; list.sort((a, b) { return DateTime.parse(b.date!).compareTo(DateTime.parse(a.date!)); }); return list; } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/models/gift.dart
import 'package:flutter/foundation.dart'; class Gift { final String? id; final String? addictionId; final String? name; final double? price; int? sortOrder; int? count; Gift({ required this.id, required this.addictionId, required this.name, required this.price, required this.sortOrder, int? count, }) { this.count = count ?? 0; } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/models/personal_note.dart
import 'package:flutter/foundation.dart'; class PersonalNote { final String? title; final String? text; final String? date; PersonalNote({ required this.title, required this.text, required this.date, }); }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/models/addiction_item_screen_args.dart
import 'package:quittle/models/addiction.dart'; class AddictionItemScreenArgs { final Addiction data; AddictionItemScreenArgs(this.data); }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/extensions/string_extension.dart
extension StringExtension on String { String capitalizeWords() { if (this.length == 0) return ''; final List words = this.split(' '); List capitalizedWords = []; words.forEach((word) { capitalizedWords .add('${word[0].toUpperCase()}${word.substring(1).toLowerCase()}'); }); return capitalizedWords.join(' '); } String capitalizeFirstLetter() { return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}'; } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/extensions/duration_extension.dart
extension DurationExtension on Duration { int get in30s { return (this.inDays / 30).floor(); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/extensions/timeofday_extension.dart
import 'package:flutter/material.dart'; extension TimeOfDayExtension on TimeOfDay { Duration get asDuration { return Duration(hours: this.hour, minutes: this.minute); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/extensions/datetime_extension.dart
extension DateTimeExtension on DateTime { bool isSameDate(DateTime other) { return this.year == other.year && this.month == other.month && this.day == other.day; } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/util/progress_constants.dart
const _levelDurations = [ Duration(days: 0), Duration(days: 1), Duration(days: 3), Duration(days: 7), Duration(days: 30), Duration(days: 60), Duration(days: 90), Duration(days: 180), Duration(days: 270), Duration(days: 360), ]; List<Duration> get levelDurations { return [..._levelDurations]; } const _levelNames = { 'en': [ '', 'Novice', 'Eager', 'Hardworking', 'Determined', 'Experienced', 'Expert', 'Free Mind', 'Free Body', 'Free Spirit', ], 'tr': [ '', 'Acemi', 'istekli', 'Çalışkan', 'Kararlı', 'Deneyimli', 'Uzman', 'Özgür zihin', 'Özgür beden', 'Özgür ruh', ] }; List<String> getLevelNames(String locale) { return [..._levelNames[locale]!]; } const _achievementDurations = [ Duration(days: 0), Duration(days: 30), Duration(days: 60), Duration(days: 90), Duration(days: 180), Duration(days: 270), Duration(days: 360), ]; List<Duration> get achievementDurations { return [..._achievementDurations]; } Duration tillNextAchievement(int achievementIndex) { return _achievementDurations[achievementIndex + 1] - _achievementDurations[achievementIndex]; }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/util/quotes_constants.dart
const quoteOfTheDayLocs = { 'en': 'Quote of the Day', 'tr': 'Günün Sözü', }; const quotes = { 'en': [ { 'quote': 'Recovery is hard. Regret is harder.', 'author': 'Brittany Burgunder', }, { 'quote': 'The greatest mistake to make in life is to continually be afraid you will make one.', 'author': 'Elbert Hubbard', }, { 'quote': 'Great acts are made up of small deeds.', 'author': 'Lao Tzu', }, { 'quote': 'Don’t let the past steal your present.', 'author': 'Terri Guillemets', }, { 'quote': 'Our greatest glory consists not in never falling, but in rising up every time we fall.', 'author': 'Oliver Goldsmith', }, { 'quote': 'Courage isn’t having the strength to go on – it is going on when you have no strength.', 'author': 'Napoleon Bonaparte', }, { 'quote': 'If you can quit for a day, you can quit for a lifetime.', 'author': 'Benjamin Alire Saenz', }, { 'quote': 'It does not matter how slowly you go as long as you do not stop.', 'author': 'Confucius', }, { 'quote': 'When your past calls, don’t answer. It has nothing new to say.', 'author': 'Anonymous', }, { 'quote': 'The only person you are destined to become is the person you decide to be.', 'author': 'Ralph Waldo Emerson', }, ], 'tr': [ { 'quote': 'İyileşmek zordur. Pişmanlık daha zor.', 'author': 'Brittany Burgunder', }, { 'quote': 'Hayatta yapılabilecek en büyük hata, sürekli bir hata yapacağınızdan korkmaktır. ', 'author': 'Elbert Hubbard', }, { 'quote': 'Büyük eylemler küçük eylemlerden oluşur.', 'author': 'Lao Tzu', }, { 'quote': 'Geçmişin bugününüzü çalmasına izin vermeyin.', 'author': 'Terri Guillemets', }, { 'quote': 'En büyük ihtişamımız asla düşmemekte değil, her düştüğümüzde yükselmektir.', 'author': 'Oliver Goldsmith', }, { 'quote': 'Cesaret, devam edecek güce sahip olmak değildir - gücünüz olmadığında da devam etmektir.', 'author': 'Napoleon Bonaparte', }, { 'quote': 'Bir günlüğüne bırakabilirseniz, bir ömür boyu bırakabilirsiniz.', 'author': 'Benjamin Alire Saenz', }, { 'quote': 'Durmadığın sürece ne kadar yavaş gittiğin önemli değildir.', 'author': 'Confucius', }, { 'quote': 'Geçmişiniz aradığında cevap vermeyin. Söyleyecek yeni bir şeyi yok.', 'author': 'Anonim', }, { 'quote': 'Olmanız gereken tek kişi, olmaya karar verdiğiniz kişidir.', 'author': 'Ralph Waldo Emerson', }, ], };
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/util/custom_localizations.dart
String progressNotificationMsg(int newLevel, String? locale) { switch (locale) { case 'en': return 'You have reached level $newLevel!'; break; case 'tr': return '$newLevel. seviyeye ulaştın!'; break; default: return ''; } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/helpers/db_helper.dart
import 'package:sqflite/sqflite.dart' as sql; import 'package:sqflite/sqlite_api.dart'; import 'package:path/path.dart' as path; class DBHelper { static Future<Database> database() async { final dbPath = await sql.getDatabasesPath(); return sql.openDatabase( path.join(dbPath, 'user.db'), onCreate: (db, version) async { await db.execute( 'CREATE TABLE addictions(id TEXT PRIMARY KEY, name TEXT, quit_date TEXT, consumption_type INTEGER, daily_consumption REAL, unit_cost REAL, level INTEGER, achievement_level INTEGER, sort_order INTEGER)'); await db.execute( 'CREATE TABLE settings(id INTEGER, currency TEXT, allow_progress_notification INTEGER, allow_quote_notification INTEGER)'); await db.execute( 'CREATE TABLE personal_notes(id TEXT, title TEXT, text TEXT, date TEXT)'); await db.execute( 'CREATE TABLE gifts(id TEXT PRIMARY KEY, addiction_id TEXT, name TEXT, price REAL, count INTEGER, sort_order INTEGER)'); }, version: 1, ); } static Future<int> insert(String table, Map<String, Object?> data) async { final db = await DBHelper.database(); return db.insert( table, data, conflictAlgorithm: ConflictAlgorithm.replace, ); } static Future<int> update( String table, String column, String? id, dynamic data, ) async { final db = await DBHelper.database(); return db .rawUpdate('UPDATE $table SET $column = ? WHERE id = ?', [data, id]); } static Future<void> reorder( String table, String column, int oldIndex, int newIndex, [ String? groupingColStr = '', String groupingCol = '', ]) async { final db = await DBHelper.database(); String groupingQuery = ''; if (groupingCol != '') { groupingQuery = ' AND $groupingCol = "$groupingColStr"'; } await db.rawUpdate( 'UPDATE $table SET $column = ? WHERE $column = ?' + groupingQuery, [-1, oldIndex], ); if (oldIndex < newIndex) { await db.rawUpdate( 'UPDATE $table SET $column = $column + ? WHERE $column > ? AND $column <= ?' + groupingQuery, [-1, oldIndex, newIndex], ); } else { await db.rawUpdate( 'UPDATE $table SET $column = $column + ? WHERE $column < ? AND $column >= ?' + groupingQuery, [1, oldIndex, newIndex], ); } await db.rawUpdate( 'UPDATE $table SET $column = ? WHERE $column = ?' + groupingQuery, [newIndex, -1], ); } static Future<int> reorderGroupedBy( String table, String column, String groupingColVal, String groupingCol, int oldIndex, int newIndex, ) async { final db = await DBHelper.database(); await db.rawUpdate( 'UPDATE $table SET $column = ? WHERE $column = ? AND $groupingCol = ?', [-1, oldIndex, groupingColVal], ); await db.rawUpdate( 'UPDATE $table SET $column = ? WHERE $column = ? AND $groupingCol = ?', [oldIndex, newIndex, groupingColVal], ); return db.rawUpdate( 'UPDATE $table SET $column = ? WHERE $column = ? AND $groupingCol = ?', [newIndex, -1, groupingColVal], ); } static Future<int> delete(String table, String? id) async { final db = await DBHelper.database(); return db.rawDelete('DELETE FROM $table WHERE id = ?', [id]); } static Future<List<Map<String, Object?>>> getData( String table, [ String column = '', String? id = '', ]) async { final db = await DBHelper.database(); if (id == '' || column == '') { return db.query(table); } return db.rawQuery('SELECT * FROM $table WHERE $column = ?', [id]); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/screens/addictions_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:provider/provider.dart'; import 'package:workmanager/workmanager.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/providers/settings_provider.dart'; import 'package:quittle/screens/create_addiction_screen.dart'; import 'package:quittle/util/progress_constants.dart'; import 'package:quittle/widgets/addiction_item_card.dart'; import 'package:quittle/widgets/settings_view.dart'; class AddictionsScreen extends StatefulWidget { static const routeName = '/addictions'; @override _AddictionsScreenState createState() => _AddictionsScreenState(); } class _AddictionsScreenState extends State<AddictionsScreen> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey(); _setProgNotifTasks(List<Addiction> addictions) async { if (Provider.of<SettingsProvider>(context, listen: false) .receiveProgressNotifs!) { for (var addiction in addictions) { if (addiction.level! < levelDurations.length - 1) { Workmanager().registerPeriodicTask( addiction.id, 'progress-notification', inputData: { 'id': addiction.id, 'locale': AppLocalizations.of(context)!.localeName, }, frequency: Duration(minutes: 15), existingWorkPolicy: ExistingWorkPolicy.keep, constraints: Constraints( requiresDeviceIdle: false, requiresBatteryNotLow: false, requiresCharging: false, requiresStorageNotLow: false, networkType: NetworkType.not_required, ), ); } else { Workmanager().cancelByUniqueName(addiction.id); } } } } void _onDelete(String id) async { final local = AppLocalizations.of(context); final removedAddiction = await Provider.of<AddictionsProvider>(context, listen: false) .deleteAddiction(id); setState(() { ScaffoldMessenger.of(context) ..removeCurrentSnackBar() ..showSnackBar( SnackBar( content: Text( '${removedAddiction.name} deleted.', ), action: SnackBarAction( label: local!.undo, onPressed: () { Provider.of<AddictionsProvider>(context, listen: false) .insertAddiction(removedAddiction); }, ), ), ); }); } void _onReorder(int oldIndex, int newIndex) { setState(() { if (newIndex > oldIndex) { newIndex--; } Provider.of<AddictionsProvider>(context, listen: false) .reorderAddictions(oldIndex, newIndex); }); } @override Widget build(BuildContext context) { final t = Theme.of(context); final deviceSize = MediaQuery.of(context).size; final local = AppLocalizations.of(context)!; void pushCreateAddictionScreen() { Navigator.of(context).push( PageRouteBuilder( transitionDuration: Duration(milliseconds: 400), reverseTransitionDuration: Duration(milliseconds: 250), pageBuilder: (_, __, ___) => CreateAddictionScreen(), ), ); } return Scaffold( key: _scaffoldKey, appBar: AppBar( leading: IconButton( icon: Icon(Icons.menu), onPressed: () { _scaffoldKey.currentState!.openDrawer(); }, ), ), floatingActionButton: Consumer<AddictionsProvider>( child: FloatingActionButton( heroTag: 'newAddiction', onPressed: pushCreateAddictionScreen, backgroundColor: t.primaryColor, tooltip: local.newMsg, child: Icon(Icons.add), ), builder: (_, addictionsData, child) { return addictionsData.addictions.length == 0 ? SizedBox() : SizedBox( child: child, ); }, ), floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, drawer: SettingsView(), body: Consumer<AddictionsProvider>( builder: (ctx, addictionsData, child) { _setProgNotifTasks(addictionsData.addictions); return addictionsData.addictions.length > 0 ? Theme( data: t.copyWith( cardColor: t.canvasColor, canvasColor: Colors.transparent, shadowColor: Colors.black26, ), child: ReorderableListView( padding: const EdgeInsets.symmetric(horizontal: 8.0), children: [ for (Addiction addiction in addictionsData.addictions) AddictionItemCard( addictionData: addiction, onDelete: _onDelete, key: ValueKey(addiction.id), ), ], onReorder: _onReorder, ), ) : child!; }, child: InkWell( onTap: pushCreateAddictionScreen, child: Container( height: deviceSize.height, width: deviceSize.width, child: Stack( alignment: Alignment.center, children: [ Center( child: SizedBox.fromSize( size: Size.square(deviceSize.width * .5), child: FloatingActionButton( heroTag: 'newAddiction', elevation: 0, backgroundColor: t.primaryColor, foregroundColor: t.canvasColor, child: Icon( Icons.add, size: t.textTheme.headline1!.fontSize, ), onPressed: null, ), ), ), Padding( padding: const EdgeInsets.all(16.0), child: Align( alignment: Alignment.bottomCenter, child: Text( local.appName, style: TextStyle( fontSize: t.textTheme.headline2!.fontSize, color: t.primaryColor, fontWeight: FontWeight.bold, ), ), ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/screens/addiction_item_screen.dart
import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:persistent_bottom_nav_bar/persistent-tab-view.dart'; import 'package:quittle/models/addiction_item_screen_args.dart'; import 'package:quittle/widgets/addiction_item.dart'; import 'package:quittle/widgets/gifts.dart'; import 'package:quittle/widgets/achievements.dart'; const _refreshInterval = Duration(seconds: 60); class AddictionItemScreen extends StatefulWidget { static const routeName = '/addiction-item'; @override _AddictionItemState createState() => _AddictionItemState(); } class _AddictionItemState extends State<AddictionItemScreen> { PersistentTabController _controller = PersistentTabController(initialIndex: 0); final tabLength = 3; @override void initState() { Timer.periodic(_refreshInterval, (timer) { if (mounted) { setState(() {}); } else { timer.cancel(); } }); super.initState(); } @override Widget build(BuildContext context) { final t = Theme.of(context); final AddictionItemScreenArgs args = ModalRoute.of(context)!.settings.arguments as AddictionItemScreenArgs; final local = AppLocalizations.of(context); List<Widget> _buildScreens() { return [ AddictionItem(args: args), Gifts(data: args.data), Achievements(data: args.data), ]; } List<PersistentBottomNavBarItem> _navBarItems() { return [ PersistentBottomNavBarItem( icon: FaIcon(FontAwesomeIcons.infoCircle), title: (local!.overview), activeColorPrimary: t.primaryColor, inactiveColorPrimary: t.hintColor, ), PersistentBottomNavBarItem( icon: FaIcon(FontAwesomeIcons.gifts), title: (local.rewards), activeColorPrimary: t.primaryColor, inactiveColorPrimary: t.hintColor, ), PersistentBottomNavBarItem( icon: FaIcon(FontAwesomeIcons.trophy), title: (local.achievements), activeColorPrimary: t.primaryColor, inactiveColorPrimary: t.hintColor, ), ]; } return Scaffold( appBar: AppBar( title: Text( args.data.name.toUpperCase(), overflow: TextOverflow.ellipsis, ), ), body: GestureDetector( onHorizontalDragEnd: (details) { if (details.primaryVelocity! < -400 && _controller.index < tabLength - 1) { _controller.jumpToTab(_controller.index + 1); } else if (details.primaryVelocity! > 400 && _controller.index > 0) { _controller.jumpToTab(_controller.index - 1); } }, child: PersistentTabView( context, controller: _controller, screens: _buildScreens(), items: _navBarItems(), confineInSafeArea: true, backgroundColor: t.cardColor, handleAndroidBackButtonPress: true, resizeToAvoidBottomInset: true, stateManagement: true, hideNavigationBarWhenKeyboardShows: true, decoration: NavBarDecoration( borderRadius: BorderRadius.circular(0.0), colorBehindNavBar: t.canvasColor, ), popAllScreensOnTapOfSelectedTab: true, popActionScreens: PopActionScreensType.all, itemAnimationProperties: ItemAnimationProperties( duration: Duration(milliseconds: 250), curve: Curves.ease, ), screenTransitionAnimation: ScreenTransitionAnimation( animateTabTransition: true, curve: Curves.ease, duration: Duration(milliseconds: 250), ), navBarStyle: NavBarStyle.style4, ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/screens/create_addiction_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:animations/animations.dart'; import 'package:quittle/extensions/datetime_extension.dart'; import 'package:quittle/extensions/timeofday_extension.dart'; import 'package:quittle/models/addiction_item_screen_args.dart'; import 'package:quittle/providers/addictions_provider.dart'; import 'package:quittle/screens/addiction_item_screen.dart'; import 'package:quittle/util/progress_constants.dart'; import 'package:quittle/widgets/custom_text_form_field.dart'; class CreateAddictionScreen extends StatelessWidget { static const routeName = '/create-addiction'; @override Widget build(BuildContext context) { final t = Theme.of(context); final statusBarHeight = MediaQuery.of(context).padding.top; return Hero( tag: 'newAddiction', transitionOnUserGestures: true, child: Scaffold( appBar: AppBar( backgroundColor: t.primaryColor, ), body: AddictionCard(statusBarHeight), ), ); } } class AddictionCard extends StatefulWidget { AddictionCard( this.statusBarHeight, ); @override _AddictionCardState createState() => _AddictionCardState(); final statusBarHeight; } class _AddictionCardState extends State<AddictionCard> with SingleTickerProviderStateMixin { final GlobalKey<FormState> _formKey = GlobalKey(); String? _consumptionType; FocusNode? _focusNode; late AnimationController _dpAnimController; var addictionData = { 'name': '', 'quit_date': DateTime.now().toString(), 'consumption_type': 0, 'daily_consumption': 1.0, 'unit_cost': 1.0, 'level': 0, 'achievement_level': 0, }; void _selectDate(context, DateTime currentlyPicked) async { //pick date DateTime? date = await showDatePicker( context: context, builder: (context, child) { _dpAnimController.forward(); return FadeScaleTransition( animation: _dpAnimController, child: child, ); }, initialDate: DateTime.now(), firstDate: DateTime.now().subtract(Duration(days: 900)), lastDate: DateTime.now(), ); _dpAnimController.reset(); // check if datepicker canceled if (date != null) { TimeOfDay? time = await showTimePicker( context: context, builder: (context, child) { _dpAnimController.forward(); return FadeScaleTransition( animation: _dpAnimController, child: child, ); }, initialTime: TimeOfDay.now(), ); _dpAnimController.reset(); // check if timepicker canceled if (time != null) { // if date is today, check if picked time is in future // if it is, cancel and reset the date. if (date.isSameDate(DateTime.now())) { if (time.asDuration.inSeconds <= TimeOfDay.now().asDuration.inSeconds) { date = date.add(time.asDuration); } else { ScaffoldMessenger.of(context) ..removeCurrentSnackBar() ..showSnackBar( SnackBar( content: Text( AppLocalizations.of(context)!.cantPickFutureTime, ), ), ); date = date.add(TimeOfDay.now().asDuration); } } else // if date is not today, add picked time date = date.add(time.asDuration); } else // if time = null (canceled) date = currentlyPicked; } else // if date = null (canceled) date = currentlyPicked; addictionData['quit_date'] = date.toString(); Duration quitDuration = DateTime.now().difference(date); setState(() { int temp = levelDurations .indexWhere((element) => quitDuration.inSeconds < element.inSeconds); addictionData['level'] = temp == -1 ? levelDurations.length - 1 : temp - 1; temp = achievementDurations .indexWhere((element) => quitDuration.inSeconds < element.inSeconds); addictionData['achievement_level'] = temp == -1 ? achievementDurations.length - 1 : temp - 1; }); } void trySubmit() async { final isValid = _formKey.currentState!.validate(); FocusScope.of(context).unfocus(); if (isValid) { _formKey.currentState!.save(); final newAddiction = await Provider.of<AddictionsProvider>(context, listen: false) .createAddiction(addictionData); Navigator.of(context).pushReplacement( PageRouteBuilder( transitionDuration: Duration(milliseconds: 250), reverseTransitionDuration: Duration(milliseconds: 250), pageBuilder: (_, __, ___) => AddictionItemScreen(), settings: RouteSettings( arguments: AddictionItemScreenArgs(newAddiction), ), transitionsBuilder: (context, animation, secondaryAnimation, child) { var begin = 0.0; var end = 1.0; var tween = Tween(begin: begin, end: end); return FadeTransition( opacity: animation.drive(tween), child: child, ); }, ), ); } } @override void initState() { _dpAnimController = AnimationController( value: 0.0, duration: const Duration(milliseconds: 200), vsync: this, ); _focusNode = new FocusNode(); super.initState(); } @override void dispose() { _dpAnimController.dispose(); _focusNode!.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final t = Theme.of(context); final local = AppLocalizations.of(context)!; final deviceSize = MediaQuery.of(context).size; return Container( margin: EdgeInsets.zero, color: t.cardColor, child: Form( key: _formKey, child: SingleChildScrollView( child: Container( height: deviceSize.height - (kToolbarHeight + widget.statusBarHeight), padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 20), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ CustomTextFormField( valKey: 'name', data: addictionData, inputName: local.addictionName, inputType: TextInputType.name, inputAction: TextInputAction.next, ), SizedBox( width: deviceSize.width, child: FittedBox( fit: BoxFit.fitWidth, child: Wrap( direction: Axis.horizontal, crossAxisAlignment: WrapCrossAlignment.center, spacing: 24.0, children: [ Material( type: MaterialType.button, color: t.canvasColor, borderRadius: BorderRadius.circular(5), child: InkWell( borderRadius: BorderRadius.circular(5), splashColor: t.highlightColor, onTap: () { setState(() { FocusScope.of(context).unfocus(); _selectDate( context, DateTime.parse(addictionData['quit_date'] as String), ); }); }, child: Container( height: t.buttonTheme.height * 2, padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( local.date, style: TextStyle( fontSize: Theme.of(context) .textTheme .subtitle2! .fontSize, fontWeight: FontWeight.bold, color: t.hintColor, ), ), Wrap( direction: Axis.horizontal, crossAxisAlignment: WrapCrossAlignment.center, spacing: 8.0, children: [ Text( DateFormat('dd/MM/yyyy').format( DateTime.parse( addictionData['quit_date'] as String), ), style: TextStyle( color: t.hintColor, ), ), Icon( Icons.date_range, color: t.hintColor, ), ], ), ], ), ), ), ), Material( type: MaterialType.button, color: t.canvasColor, borderRadius: BorderRadius.circular(5), child: InkWell( focusNode: _focusNode, borderRadius: BorderRadius.circular(5), splashColor: t.highlightColor, onTap: () { setState(() { showModalBottomSheet( backgroundColor: Colors.transparent, context: context, builder: (context) => Container( decoration: BoxDecoration( color: t.cardColor, borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), ), ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextButton.icon( style: ButtonStyle( padding: MaterialStateProperty.all( EdgeInsets.all(32.0), ), ), onPressed: () { setState(() { FocusScope.of(context).unfocus(); addictionData[ 'consumption_type'] = 0; _consumptionType = local.quantity; Navigator.of(context).pop(); }); }, icon: Icon( Icons.iso_outlined, color: t.hintColor, ), label: Text( local.quantity, style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), ), ), Divider( thickness: 1, indent: 8, endIndent: 8, height: 0, ), TextButton.icon( style: ButtonStyle( padding: MaterialStateProperty.all( EdgeInsets.all(32.0), ), ), onPressed: () { setState(() { addictionData[ 'consumption_type'] = 1; _consumptionType = local.hour(0); Navigator.of(context).pop(); }); }, icon: Icon( Icons.hourglass_bottom_rounded, color: t.hintColor, ), label: Text( local.hour(0), style: TextStyle( color: t.hintColor, fontWeight: FontWeight.bold, ), ), ), ], ), ), ); }); }, child: Container( height: t.buttonTheme.height * 2, padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: t.canvasColor, ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( local.consumptionType, style: TextStyle( fontSize: Theme.of(context) .textTheme .subtitle2! .fontSize, fontWeight: FontWeight.bold, color: t.hintColor, ), ), Text( _consumptionType != null ? _consumptionType! : local.quantity, style: TextStyle( fontSize: Theme.of(context) .textTheme .subtitle2! .fontSize, color: t.hintColor, ), ), ], ), ), ), ), ], ), ), ), CustomTextFormField( valKey: 'daily_consumption', data: addictionData, inputName: local.dailyConsumption, inputType: TextInputType.number, validator: (value) { if (double.tryParse(value) == null) { return local.pleaseEnterANumber; } else if (double.parse(value) < 0) { return local.valueMustBePositive; } else { return null; } }, maxLength: 10, inputAction: TextInputAction.next, ), CustomTextFormField( valKey: 'unit_cost', data: addictionData, inputName: local.unitCost, inputType: TextInputType.number, onSubmit: trySubmit, validator: (value) { if (double.tryParse(value) == null) { return local.pleaseEnterANumber; } else if (double.parse(value) < 0) { return local.valueMustBePositive; } else { return null; } }, maxLength: 10, inputAction: TextInputAction.done, ), ElevatedButton( onPressed: trySubmit, child: Container( width: deviceSize.width, height: deviceSize.height * .1, alignment: Alignment.center, child: Text( local.quitAddiction, style: TextStyle( fontSize: t.textTheme.headline6!.fontSize, ), ), ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/providers/addictions_provider.dart
import 'package:flutter/material.dart'; import 'package:uuid/uuid.dart'; import 'package:quittle/helpers/db_helper.dart'; import 'package:quittle/models/addiction.dart'; import 'package:quittle/models/gift.dart'; import 'package:quittle/models/personal_note.dart'; class AddictionsProvider with ChangeNotifier { List<Addiction> _addictions = []; List<Addiction> get addictions { return [..._addictions]; } void insertAddiction(Addiction addiction) async { if (addiction.sortOrder == _addictions.length) _addictions.add(addiction); else _addictions.insert(addiction.sortOrder!, addiction); notifyListeners(); await DBHelper.insert( 'addictions', { 'id': addiction.id, 'name': addiction.name, 'quit_date': addiction.quitDate, 'consumption_type': addiction.consumptionType, 'daily_consumption': addiction.dailyConsumption, 'unit_cost': addiction.unitCost, 'level': addiction.level, 'achievement_level': addiction.achievementLevel, 'sort_order': _addictions.length, }, ); reorderAddictions(_addictions.length, addiction.sortOrder!); } Future<Addiction> createAddiction(Map<String, dynamic> data) async { data['id'] = Uuid().v1(); final newAddiction = Addiction( id: data['id'], name: data['name'], quitDate: data['quit_date'], consumptionType: data['consumption_type'], dailyConsumption: data['daily_consumption'], unitCost: data['unit_cost'], level: data['level'], achievementLevel: data['achievement_level'], sortOrder: _addictions.length, personalNotes: [], gifts: [], ); await DBHelper.insert( 'addictions', { 'id': data['id'], 'name': data['name'], 'quit_date': data['quit_date'], 'consumption_type': data['consumption_type'], 'daily_consumption': data['daily_consumption'], 'unit_cost': data['unit_cost'], 'level': data['level'], 'achievement_level': data['achievement_level'], 'sort_order': _addictions.length, }, ); _addictions.add(newAddiction); notifyListeners(); return newAddiction; } Future<void> fetchAddictions() async { final List<Addiction> loadedAddictions = []; final addictionsTable = await DBHelper.getData('addictions'); if (addictionsTable.length <= 0) { _addictions = []; notifyListeners(); return; } addictionsTable.forEach( (addiction) async { var temp = Addiction( id: addiction['id'] as String, name: addiction['name'] as String, quitDate: addiction['quit_date'] as String, consumptionType: addiction['consumption_type'] as int, dailyConsumption: addiction['daily_consumption'] as double, unitCost: addiction['unit_cost'] as double, level: addiction['level'] as int?, achievementLevel: addiction['achievement_level'] as int?, sortOrder: addiction['sort_order'] as int?, personalNotes: [], gifts: [], ); loadedAddictions.add(temp); }, ); loadedAddictions.sort((a, b) { return a.sortOrder!.compareTo(b.sortOrder!); }); _addictions = loadedAddictions; notifyListeners(); } //! gifts and notes are not deleted from db but user see them in app Future<Addiction> deleteAddiction(String id) async { final addiction = _addictions.firstWhere((addiction) => addiction.id == id); _addictions.remove(addiction); notifyListeners(); final temp = _addictions.where((a) => a.sortOrder! > addiction.sortOrder!); temp.forEach((a) async { a.sortOrder = a.sortOrder! - 1; await DBHelper.update('addictions', 'sort_order', a.id, a.sortOrder); }); await DBHelper.delete('addictions', id); return addiction; // ... // add a code that reverts the delete if db fails } void reorderAddictions(int oldIndex, int newIndex) async { // if reverting a delete, skip (see insertAddiction funt.) if (oldIndex != _addictions.length) { Addiction temp = _addictions.removeAt(oldIndex); _addictions.insert(newIndex, temp); } await DBHelper.reorder( 'addictions', 'sort_order', oldIndex, newIndex, ); // ... // add a code that reverts the reorder if db fails } void createNote(Map<String, dynamic> data, String? id) async { final addiction = _addictions.firstWhere((addiction) => addiction.id == id); final newNote = PersonalNote( title: data['title'], text: data['text'], date: data['date'], ); await DBHelper.insert( 'personal_notes', { 'id': id, 'title': data['title'], 'text': data['text'], 'date': data['date'], }, ); addiction.personalNotes!.add(newNote); notifyListeners(); } Future<void> fetchNotes(String? id) async { final List<PersonalNote> loadedNotes = []; final addiction = _addictions.firstWhere((addiction) => addiction.id == id); final notes = await DBHelper.getData( 'personal_notes', 'id', id, ); notes.forEach((note) { loadedNotes.add( PersonalNote( title: note['title'] as String?, text: note['text'] as String?, date: note['date'] as String?, ), ); }); addiction.personalNotes = loadedNotes; } void createGift(Map<String, dynamic> data, String? id) async { final addiction = _addictions.firstWhere((addiction) => addiction.id == id); final giftId = Uuid().v1(); final newGift = Gift( id: giftId, addictionId: id, name: data['name'], price: data['price'], sortOrder: addiction.gifts!.length, ); await DBHelper.insert( 'gifts', { 'id': giftId, 'addiction_id': id, 'name': data['name'], 'price': data['price'], 'count': 0, 'sort_order': addiction.gifts!.length, }, ); addiction.gifts!.add(newGift); notifyListeners(); } Future<void> fetchGifts(String? id) async { final List<Gift> loadedGifts = []; final addiction = _addictions.firstWhere((addiction) => addiction.id == id); final gifts = await DBHelper.getData( 'gifts', 'addiction_id', id, ); gifts.forEach((gift) { loadedGifts.add( Gift( id: gift['id'] as String?, addictionId: gift['addiction_id'] as String?, name: gift['name'] as String?, price: gift['price'] as double?, count: gift['count'] as int?, sortOrder: gift['sort_order'] as int?, ), ); }); loadedGifts.sort((a, b) => a.sortOrder!.compareTo(b.sortOrder!)); addiction.gifts = loadedGifts; notifyListeners(); } void deleteGift(Gift gift) async { final addiction = _addictions.firstWhere((addiction) => addiction.id == gift.addictionId); addiction.gifts!.remove(gift); notifyListeners(); final temp = addiction.gifts!.where((g) => g.sortOrder! > addiction.sortOrder!); temp.forEach((g) async { g.sortOrder = g.sortOrder! - 1; await DBHelper.update('gifts', 'sort_order', g.id, g.sortOrder); }); await DBHelper.delete('gifts', gift.id); } Future<void> reorderGifts(int oldIndex, int newIndex, String? id) async { final addiction = _addictions.firstWhere((addiction) => addiction.id == id); final temp = addiction.gifts!.removeAt(oldIndex); addiction.gifts!.insert(newIndex, temp); await DBHelper.reorder( 'gifts', 'sort_order', oldIndex, newIndex, id, 'addiction_id', ); // ... // add a code that reverts the reorder if db fails } void buyGift(Gift gift) async { gift.count = gift.count! + 1; await DBHelper.update( 'gifts', 'count', gift.id, gift.count, ); notifyListeners(); } }
0
mirrored_repositories/quittle/lib
mirrored_repositories/quittle/lib/providers/settings_provider.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SettingsProvider with ChangeNotifier { SharedPreferences? _prefs; String? get currency { return _prefs!.getString('currency'); } bool? get receiveProgressNotifs { return _prefs!.getBool('allowProgressNotif'); } bool? get receiveQuoteNotifs { return _prefs!.getBool('allowQuoteNotif'); } Future<void> _initPrefs() async { if (_prefs == null) { _prefs = await SharedPreferences.getInstance(); } } Future<void> loadPrefs() async { await _initPrefs(); _prefs!.getBool('allowProgressNotif') ?? await _prefs!.setBool('allowProgressNotif', true); _prefs!.getString('allowQuoteNotif') ?? await (_prefs!.setBool('allowQuoteNotif', true) as FutureOr<String?>); _prefs!.getString('currency') ?? await (_prefs!.setString('currency', 'USD') as FutureOr<String?>); notifyListeners(); } void updateCurrency(String newCurrency) async { await _initPrefs(); await _prefs!.setString('currency', newCurrency); notifyListeners(); } void allowQuoteNotif(bool isAllowed) async { await _initPrefs(); await _prefs!.setBool('allowQuoteNotif', isAllowed); notifyListeners(); } void allowProgressNotif(bool isAllowed) async { await _initPrefs(); await _prefs!.setBool('allowProgressNotif', isAllowed); notifyListeners(); } }
0
mirrored_repositories/quittle
mirrored_repositories/quittle/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:quittle/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/xylophone
mirrored_repositories/xylophone/lib/main.dart
import 'package:flutter/material.dart'; import 'package:audioplayers/audioplayers.dart'; void main() { runApp(MaterialApp( home: Scaffold( backgroundColor: Colors.black, body: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ getView(1 , Colors.red), getView(2 , Colors.yellow), getView(3 , Colors.green), getView(4 , Colors.lime), getView(5 , Colors.brown), getView(6 , Colors.blueAccent), getView(7 , Colors.purple), ], ), ) ), )); } Widget getView(int pos , Color color){ return Expanded( child: TextButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(color) ), onPressed: (){ playSound(pos); }, child: Text("Click Me"), ), ); } void playSound(int pos) { final audioPlayer = AudioCache(); audioPlayer.play('assets_note$pos.wav'); }
0
mirrored_repositories/flim_fusion
mirrored_repositories/flim_fusion/lib/main.dart
import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/screens/favorite/fav_screen.dart'; import 'package:film_fusion/screens/home/home_screen.dart'; import 'package:film_fusion/screens/profile/profile_screen.dart'; import 'package:film_fusion/utils/route_generator.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return GetMaterialApp( theme: ThemeData( textTheme: GoogleFonts.openSansTextTheme(Theme.of(context).textTheme), useMaterial3: true, ), debugShowCheckedModeBanner: false, initialRoute: splash, getPages: RouteGenerator.getPages(), ); } } class MainPage extends StatefulWidget { const MainPage({super.key}); @override State<MainPage> createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { int currentPage = 0; List<Widget> pages = [ const HomeScreen(), FavScreen(), ProfileScreen(), ]; DateTime? currentBackPressTime; // Add this variable @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // Handle the back button press if (currentPage != 0) { setState(() { currentPage = 0; }); // Update the active tab return false; // Prevent the default back navigation } return true; }, child: SafeArea( child: Scaffold( backgroundColor: Colors.black, body: pages[currentPage], resizeToAvoidBottomInset: false, bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.black, selectedItemColor: Colors.white, unselectedItemColor: Colors.white.withOpacity(0.4), currentIndex: currentPage, onTap: (index) { setState(() { currentPage = index; }); }, items: const [ BottomNavigationBarItem( backgroundColor: Colors.black, icon: Icon(CupertinoIcons.home), label: "Home", ), BottomNavigationBarItem( backgroundColor: Colors.black, icon: Icon(Icons.favorite_border_outlined), label: "Favorites", ), BottomNavigationBarItem( backgroundColor: Colors.black, icon: Icon(CupertinoIcons.person), label: "Profile", ), ], ), ), ), ); } }
0
mirrored_repositories/flim_fusion/lib/db
mirrored_repositories/flim_fusion/lib/db/dao/user_dao.dart
import 'package:floor/floor.dart'; import '../entity/users.dart'; @dao abstract class UserProfileDao { @Query('SELECT * FROM users') Future<List<UserProfile>> findAllUserProfiles(); @Query('SELECT * FROM users WHERE email = :email') Future<UserProfile?> findUserProfileById(String email); @Query('SELECT email FROM users') Future<List<String>> getEmails(); // Modify the method name and parameter to accept UserModel @insert Future<void> insertUserProfile(UserProfile userProfile); @update Future<void> updateUserProfile(UserProfile userProfile); @delete Future<void> deleteUserProfile(UserProfile userProfile); }
0
mirrored_repositories/flim_fusion/lib/db
mirrored_repositories/flim_fusion/lib/db/database/film_fusion_database.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'film_fusion_database.dart'; // ************************************************************************** // FloorGenerator // ************************************************************************** // ignore: avoid_classes_with_only_static_members class $FloorAppDatabase { /// Creates a database builder for a persistent database. /// Once a database is built, you should keep a reference to it and re-use it. static _$AppDatabaseBuilder databaseBuilder(String name) => _$AppDatabaseBuilder(name); /// Creates a database builder for an in memory database. /// Information stored in an in memory database disappears when the process is killed. /// Once a database is built, you should keep a reference to it and re-use it. static _$AppDatabaseBuilder inMemoryDatabaseBuilder() => _$AppDatabaseBuilder(null); } class _$AppDatabaseBuilder { _$AppDatabaseBuilder(this.name); final String? name; final List<Migration> _migrations = []; Callback? _callback; /// Adds migrations to the builder. _$AppDatabaseBuilder addMigrations(List<Migration> migrations) { _migrations.addAll(migrations); return this; } /// Adds a database [Callback] to the builder. _$AppDatabaseBuilder addCallback(Callback callback) { _callback = callback; return this; } /// Creates the database and initializes it. Future<AppDatabase> build() async { final path = name != null ? await sqfliteDatabaseFactory.getDatabasePath(name!) : ':memory:'; final database = _$AppDatabase(); database.database = await database.open( path, _migrations, _callback, ); return database; } } class _$AppDatabase extends AppDatabase { _$AppDatabase([StreamController<String>? listener]) { changeListener = listener ?? StreamController<String>.broadcast(); } UserProfileDao? _userProfileDaoInstance; Future<sqflite.Database> open( String path, List<Migration> migrations, [ Callback? callback, ]) async { final databaseOptions = sqflite.OpenDatabaseOptions( version: 1, onConfigure: (database) async { await database.execute('PRAGMA foreign_keys = ON'); await callback?.onConfigure?.call(database); }, onOpen: (database) async { await callback?.onOpen?.call(database); }, onUpgrade: (database, startVersion, endVersion) async { await MigrationAdapter.runMigrations( database, startVersion, endVersion, migrations); await callback?.onUpgrade?.call(database, startVersion, endVersion); }, onCreate: (database, version) async { await database.execute( 'CREATE TABLE IF NOT EXISTS `users` (`email` TEXT NOT NULL, `name` TEXT NOT NULL, `username` TEXT NOT NULL, `phone` TEXT NOT NULL, PRIMARY KEY (`email`))'); await callback?.onCreate?.call(database, version); }, ); return sqfliteDatabaseFactory.openDatabase(path, options: databaseOptions); } @override UserProfileDao get userProfileDao { return _userProfileDaoInstance ??= _$UserProfileDao(database, changeListener); } } class _$UserProfileDao extends UserProfileDao { _$UserProfileDao( this.database, this.changeListener, ) : _queryAdapter = QueryAdapter(database), _userProfileInsertionAdapter = InsertionAdapter( database, 'users', (UserProfile item) => <String, Object?>{ 'email': item.email, 'name': item.name, 'username': item.username, 'phone': item.phone }), _userProfileUpdateAdapter = UpdateAdapter( database, 'users', ['email'], (UserProfile item) => <String, Object?>{ 'email': item.email, 'name': item.name, 'username': item.username, 'phone': item.phone }), _userProfileDeletionAdapter = DeletionAdapter( database, 'users', ['email'], (UserProfile item) => <String, Object?>{ 'email': item.email, 'name': item.name, 'username': item.username, 'phone': item.phone }); final sqflite.DatabaseExecutor database; final StreamController<String> changeListener; final QueryAdapter _queryAdapter; final InsertionAdapter<UserProfile> _userProfileInsertionAdapter; final UpdateAdapter<UserProfile> _userProfileUpdateAdapter; final DeletionAdapter<UserProfile> _userProfileDeletionAdapter; @override Future<List<UserProfile>> findAllUserProfiles() async { return _queryAdapter.queryList('SELECT * FROM users', mapper: (Map<String, Object?> row) => UserProfile( name: row['name'] as String, email: row['email'] as String, username: row['username'] as String, phone: row['phone'] as String)); } @override Future<UserProfile?> findUserProfileById(String email) async { return _queryAdapter.query('SELECT * FROM users WHERE email = ?1', mapper: (Map<String, Object?> row) => UserProfile( name: row['name'] as String, email: row['email'] as String, username: row['username'] as String, phone: row['phone'] as String), arguments: [email]); } @override Future<List<String>> getEmails() async { return _queryAdapter.queryList('SELECT email FROM users', mapper: (Map<String, Object?> row) => row.values.first as String); } @override Future<void> insertUserProfile(UserProfile userProfile) async { await _userProfileInsertionAdapter.insert( userProfile, OnConflictStrategy.abort); } @override Future<void> updateUserProfile(UserProfile userProfile) async { await _userProfileUpdateAdapter.update( userProfile, OnConflictStrategy.abort); } @override Future<void> deleteUserProfile(UserProfile userProfile) async { await _userProfileDeletionAdapter.delete(userProfile); } }
0
mirrored_repositories/flim_fusion/lib/db
mirrored_repositories/flim_fusion/lib/db/database/film_fusion_database.dart
import 'dart:async'; import 'package:film_fusion/model/user_model.dart'; import 'package:floor/floor.dart'; import 'package:sqflite/sqflite.dart' as sqflite; import '../dao/user_dao.dart'; import '../entity/users.dart'; part 'film_fusion_database.g.dart'; // the generated code will be there @Database( version: 1, entities: [UserProfile], ) abstract class AppDatabase extends FloorDatabase { static const String dbName = "flim_fusion5.db"; UserProfileDao get userProfileDao; }
0
mirrored_repositories/flim_fusion/lib/db
mirrored_repositories/flim_fusion/lib/db/entity/users.dart
import 'package:floor/floor.dart'; @Entity(tableName: 'users') class UserProfile { @primaryKey final String email; final String name; final String username; final String phone; // final String profileImageUrl; UserProfile({ required this.name, required this.email, required this.username, required this.phone, // this.profileImageUrl, }); factory UserProfile.fromFirestore(Map<String, dynamic> data) { return UserProfile( // Assuming 'uid' is a field in your Firestore document username: data['username'] ?? '', // Replace with the actual field name name: data['name'] ?? '', email: data['email'] ?? '', // Replace with the actual field name phone: data['phone'] ?? '', // profileImageUrl: data['profileImageUrl'] ?? '', // Replace with the actual field name ); } }
0
mirrored_repositories/flim_fusion/lib/db
mirrored_repositories/flim_fusion/lib/db/services/localdb_services.dart
import 'package:film_fusion/db/dao/user_dao.dart'; import '../database/film_fusion_database.dart'; abstract class LocalDbService { static Future<AppDatabase> get _db async => $FloorAppDatabase.databaseBuilder(AppDatabase.dbName).build(); static Future<UserProfileDao> get usersDao async => (await _db).userProfileDao; } // class LocalDbService2 { // static AppDatabase? _database; // static Future<AppDatabase?> get database async { // _database = await $FloorAppDatabase.databaseBuilder('app_database.db').build(); // return _database; // } // }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/model/movie_by_id_model.dart
import 'dart:convert'; MovieByIdModel movieByIdModelFromJson(String str) => MovieByIdModel.fromJson(json.decode(str)); String movieByIdModelToJson(MovieByIdModel data) => json.encode(data.toJson()); class MovieByIdModel { bool adult; String backdropPath; dynamic belongsToCollection; int budget; List<Genre> genres; String homepage; int id; String imdbId; String originalLanguage; String originalTitle; String overview; double popularity; String posterPath; List<ProductionCompany> productionCompanies; List<ProductionCountry> productionCountries; DateTime releaseDate; int revenue; int runtime; List<SpokenLanguage> spokenLanguages; String status; String tagline; String title; bool video; double voteAverage; int voteCount; MovieByIdModel({ required this.adult, required this.backdropPath, required this.belongsToCollection, required this.budget, required this.genres, required this.homepage, required this.id, required this.imdbId, required this.originalLanguage, required this.originalTitle, required this.overview, required this.popularity, required this.posterPath, required this.productionCompanies, required this.productionCountries, required this.releaseDate, required this.revenue, required this.runtime, required this.spokenLanguages, required this.status, required this.tagline, required this.title, required this.video, required this.voteAverage, required this.voteCount, }); factory MovieByIdModel.fromJson(Map<String, dynamic> json) => MovieByIdModel( adult: json["adult"], backdropPath: json["backdrop_path"], belongsToCollection: json["belongs_to_collection"], budget: json["budget"], genres: List<Genre>.from(json["genres"].map((x) => Genre.fromJson(x))), homepage: json["homepage"], id: json["id"], imdbId: json["imdb_id"], originalLanguage: json["original_language"], originalTitle: json["original_title"], overview: json["overview"], popularity: json["popularity"]?.toDouble(), posterPath: json["poster_path"], productionCompanies: List<ProductionCompany>.from(json["production_companies"].map((x) => ProductionCompany.fromJson(x))), productionCountries: List<ProductionCountry>.from(json["production_countries"].map((x) => ProductionCountry.fromJson(x))), releaseDate: DateTime.parse(json["release_date"]), revenue: json["revenue"], runtime: json["runtime"], spokenLanguages: List<SpokenLanguage>.from(json["spoken_languages"].map((x) => SpokenLanguage.fromJson(x))), status: json["status"], tagline: json["tagline"], title: json["title"], video: json["video"], voteAverage: json["vote_average"]?.toDouble(), voteCount: json["vote_count"], ); Map<String, dynamic> toJson() => { "adult": adult, "backdrop_path": backdropPath, "belongs_to_collection": belongsToCollection, "budget": budget, "genres": List<dynamic>.from(genres.map((x) => x.toJson())), "homepage": homepage, "id": id, "imdb_id": imdbId, "original_language": originalLanguage, "original_title": originalTitle, "overview": overview, "popularity": popularity, "poster_path": posterPath, "production_companies": List<dynamic>.from(productionCompanies.map((x) => x.toJson())), "production_countries": List<dynamic>.from(productionCountries.map((x) => x.toJson())), "release_date": "${releaseDate.year.toString().padLeft(4, '0')}-${releaseDate.month.toString().padLeft(2, '0')}-${releaseDate.day.toString().padLeft(2, '0')}", "revenue": revenue, "runtime": runtime, "spoken_languages": List<dynamic>.from(spokenLanguages.map((x) => x.toJson())), "status": status, "tagline": tagline, "title": title, "video": video, "vote_average": voteAverage, "vote_count": voteCount, }; } class Genre { int id; String name; Genre({ required this.id, required this.name, }); factory Genre.fromJson(Map<String, dynamic> json) => Genre( id: json["id"], name: json["name"], ); Map<String, dynamic> toJson() => { "id": id, "name": name, }; } class ProductionCompany { int id; String? logoPath; String name; String originCountry; ProductionCompany({ required this.id, required this.logoPath, required this.name, required this.originCountry, }); factory ProductionCompany.fromJson(Map<String, dynamic> json) => ProductionCompany( id: json["id"], logoPath: json["logo_path"], name: json["name"], originCountry: json["origin_country"], ); Map<String, dynamic> toJson() => { "id": id, "logo_path": logoPath, "name": name, "origin_country": originCountry, }; } class ProductionCountry { String iso31661; String name; ProductionCountry({ required this.iso31661, required this.name, }); factory ProductionCountry.fromJson(Map<String, dynamic> json) => ProductionCountry( iso31661: json["iso_3166_1"], name: json["name"], ); Map<String, dynamic> toJson() => { "iso_3166_1": iso31661, "name": name, }; } class SpokenLanguage { String englishName; String iso6391; String name; SpokenLanguage({ required this.englishName, required this.iso6391, required this.name, }); factory SpokenLanguage.fromJson(Map<String, dynamic> json) => SpokenLanguage( englishName: json["english_name"], iso6391: json["iso_639_1"], name: json["name"], ); Map<String, dynamic> toJson() => { "english_name": englishName, "iso_639_1": iso6391, "name": name, }; }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/model/trending_movies_model.dart
// // To parse this JSON data, do // // // // final trendingMovieModel = trendingMovieModelFromJson(jsonString); // import 'dart:convert'; // TrendingMovieModel trendingMovieModelFromJson(String str) => // TrendingMovieModel.fromJson(json.decode(str)); // String trendingMovieModelToJson(TrendingMovieModel data) => // json.encode(data.toJson()); // class TrendingMovieModel { // // int page; // List<Result> results; // int totalPages; // int totalResults; // TrendingMovieModel({ // // required this.page, // required this.results, // required this.totalPages, // required this.totalResults, // }); // factory TrendingMovieModel.fromJson(Map<String, dynamic> json) => // TrendingMovieModel( // // page: json["page"], // results: // List<Result>.from(json["results"].map((x) => Result.fromJson(x))), // totalPages: json["total_pages"], // totalResults: json["total_results"], // ); // Map<String, dynamic> toJson() => { // // "page": page, // "results": List<dynamic>.from(results.map((x) => x.toJson())), // "total_pages": totalPages, // "total_results": totalResults, // }; // } // class Result { // bool adult; // String? backdropPath; // int id; // String title; // // OriginalLanguage originalLanguage; // String originalTitle; // String overview; // String? posterPath; // // MediaType mediaType; // List<int> genreIds; // double popularity; // DateTime releaseDate; // bool video; // double voteAverage; // int voteCount; // Result({ // required this.adult, // required this.backdropPath, // required this.id, // required this.title, // // required this.originalLanguage, // required this.originalTitle, // required this.overview, // required this.posterPath, // // required this.mediaType, // required this.genreIds, // required this.popularity, // required this.releaseDate, // required this.video, // required this.voteAverage, // required this.voteCount, // }); // factory Result.fromJson(Map<String, dynamic> json) { // return Result( // adult: json["adult"], // backdropPath: // json["backdrop_path"] != null ? json["backdrop_path"] as String : "", // id: json["id"], // title: json["title"], // // originalLanguage: originalLanguageValues.map[json["original_language"]]!, // originalTitle: json["original_title"], // overview: json["overview"], // posterPath: // json["poster_path"] != null ? json["poster_path"] as String : "", // // mediaType: mediaTypeValues.map[json["media_type"]]!, // genreIds: List<int>.from(json["genre_ids"].map((x) => x)), // popularity: json["popularity"]?.toDouble(), // releaseDate: json["release_date"] != null // ? DateTime.tryParse(json["release_date"] as String? ?? "") ?? DateTime.now() // : DateTime.now(), // video: json["video"], // voteAverage: json["vote_average"]?.toDouble(), // voteCount: json["vote_count"], // ); // } // Map<String, dynamic> toJson() => { // "adult": adult, // "backdrop_path": backdropPath, // "id": id, // "title": title, // // "original_language": originalLanguageValues.reverse[originalLanguage], // "original_title": originalTitle, // "overview": overview, // "poster_path": posterPath, // // "media_type": mediaTypeValues.reverse[mediaType], // "genre_ids": List<dynamic>.from(genreIds.map((x) => x)), // "popularity": popularity, // "release_date": // "${releaseDate.year.toString().padLeft(4, '0')}-${releaseDate.month.toString().padLeft(2, '0')}-${releaseDate.day.toString().padLeft(2, '0')}", // "video": video, // "vote_average": voteAverage, // "vote_count": voteCount, // }; // } // enum MediaType { MOVIE } // final mediaTypeValues = EnumValues({"movie": MediaType.MOVIE}); // enum OriginalLanguage { EN, NL, SV } // final originalLanguageValues = EnumValues({ // "en": OriginalLanguage.EN, // "nl": OriginalLanguage.NL, // "sv": OriginalLanguage.SV // }); // class EnumValues<T> { // Map<String, T> map; // late Map<T, String> reverseMap; // EnumValues(this.map); // Map<T, String> get reverse { // reverseMap = map.map((k, v) => MapEntry(v, k)); // return reverseMap; // } // }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/model/new_movies_model.dart
// To parse this JSON data, do // // final latestMoviesModel = latestMoviesModelFromJson(jsonString); import 'dart:convert'; LatestMoviesModel latestMoviesModelFromJson(String str) => LatestMoviesModel.fromJson(json.decode(str)); String latestMoviesModelToJson(LatestMoviesModel data) => json.encode(data.toJson()); class LatestMoviesModel { // Dates dates; // int page; List<Movies> results; int totalPages; int totalResults; LatestMoviesModel({ // required this.dates, // required this.page, required this.results, required this.totalPages, required this.totalResults, }); factory LatestMoviesModel.fromJson(Map<String, dynamic> json) => LatestMoviesModel( // dates: Dates.fromJson(json["dates"]), // page: json["page"], results: List<Movies>.from(json["results"]!.map((x) => Movies.fromJson(x))), totalPages: json["total_pages"], totalResults: json["total_results"], ); Map<String, dynamic> toJson() => { // "dates": dates.toJson(), // "page": page, "results": List<dynamic>.from(results.map((x) => x.toJson())), "total_pages": totalPages, "total_results": totalResults, }; } class Dates { DateTime maximum; DateTime minimum; Dates({ required this.maximum, required this.minimum, }); factory Dates.fromJson(Map<String, dynamic> json) => Dates( maximum: DateTime.parse(json["maximum"]), minimum: DateTime.parse(json["minimum"]), ); Map<String, dynamic> toJson() => { "maximum": "${maximum.year.toString().padLeft(4, '0')}-${maximum.month.toString().padLeft(2, '0')}-${maximum.day.toString().padLeft(2, '0')}", "minimum": "${minimum.year.toString().padLeft(4, '0')}-${minimum.month.toString().padLeft(2, '0')}-${minimum.day.toString().padLeft(2, '0')}", }; } class Movies { bool isFavorite; List<int> genreIds; int id; String overview; String? posterPath; DateTime releaseDate; String title; double voteAverage; Movies({ required this.isFavorite, required this.genreIds, required this.id, required this.overview, required this.posterPath, required this.releaseDate, required this.title, required this.voteAverage, }); factory Movies.fromJson(Map<String, dynamic> json, {bool isFavorite = false}) => Movies( isFavorite: isFavorite, genreIds: List<int>.from(json["genre_ids"].map((x) => x)), id: json["id"], overview: json["overview"], posterPath: json["poster_path"] != null ? json["poster_path"] as String : "", releaseDate: json["release_date"] != null ? DateTime.tryParse(json["release_date"] as String? ?? "") ?? DateTime.now() : DateTime.now(), title: json["title"], voteAverage: json["vote_average"]?.toDouble() ?? 0.0, ); Map<String, dynamic> toJson() => { "genre_ids": List<dynamic>.from(genreIds.map((x) => x)), "id": id, "overview": overview, "poster_path": posterPath, "release_date": "${releaseDate.year.toString().padLeft(4, '0')}-${releaseDate.month.toString().padLeft(2, '0')}-${releaseDate.day.toString().padLeft(2, '0')}", "title": title, "vote_average": voteAverage, }; } enum OriginalLanguage { EN, ES } final originalLanguageValues = EnumValues({"en": OriginalLanguage.EN, "es": OriginalLanguage.ES}); class EnumValues<T> { Map<String, T> map; late Map<T, String> reverseMap; EnumValues(this.map); Map<T, String> get reverse { reverseMap = map.map((k, v) => MapEntry(v, k)); return reverseMap; } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/model/user_model.dart
// import 'package:floor/floor.dart'; // @Entity(tableName: 'user_models') // class UserModel { // @primaryKey // final String email; // final String name; // Firebase User ID // final String username; // final String phone; // UserModel({ // required this.name, // required this.username, // required this.email, // required this.phone, // }); // factory UserModel.fromFirestore(Map<String, dynamic> data) { // return UserModel( // // Assuming 'uid' is a field in your Firestore document // username: data['username'] ?? '', // Replace with the actual field name // name: data['name'] ?? '', // email: data['email'] ?? '', // Replace with the actual field name // phone: data['phone'] ?? '', // Replace with the actual field name // ); // } // }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/controller/login_screen_controller.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/utils/toast_message.dart'; import 'package:firebase_auth/firebase_auth.dart'; class LoginController extends GetxController { final isLoading = false.obs; final obscureText = true.obs; final useremailController = TextEditingController(); final passwordController = TextEditingController(); final FirebaseFirestore firestore = FirebaseFirestore.instance; final formKey = GlobalKey<FormState>(); String? validateUsername(String? value) { if (value == null || value.isEmpty) { return 'Username is required'; } return null; } String? validatePassword(String? value) { if (value == null || value.isEmpty) { return 'Password is required'; } return null; } final auth = FirebaseAuth.instance; void login() { if (formKey.currentState!.validate()) { isLoading.value = true; auth .signInWithEmailAndPassword( email: useremailController.text.toString(), password: passwordController.text.toString(), ) .then((value) async { isLoading.value = false; Get.snackbar( "LOGIN", "Successfully", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.greenAccent.withOpacity(0.5), ); Get.offAllNamed(mainScreen); }).onError((error, stackTrace) { ToastMessage.toastMessage(error.toString()); debugPrint(error.toString()); isLoading.value = false; }); } } void sendPasswordResetEmail(String email) async { try { await auth.sendPasswordResetEmail(email: email); Get.snackbar( "Password Reset Email Sent", "Check your email for password reset instructions.", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.greenAccent.withOpacity(0.7), ); } catch (error) { Get.snackbar( "Error", error.toString(), snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.redAccent.withOpacity(0.7), ); } } // void changepasswordDialog(context) { // RxBool isLoading = false.obs; // showDialog( // context: context, // barrierDismissible: false, // builder: (BuildContext context) { // return AlertDialog( // title: const Text('Change Password'), // content: Form( // key: formKey, // child: TextFormField( // controller: useremailController, // decoration: const InputDecoration( // labelText: 'Enter You Email', // ), // validator: validateUsername // ), // ) // ); // } ); // actions: [ // TextButton( // onPressed: () { // Navigator.of(context).pop(); // }, // child: const Text('Cancel'), // ), // Obx( // () => ElevatedButton( // onPressed: () async { // isLoading.value = true; // debugPrint("object"); // String oldPassword = oldPasswordController.text; // String newPassword = newPasswordController.text; // if (formKey.currentState!.validate()) { // if (oldPassword.isNotEmpty && newPassword.isNotEmpty) { // // Verify the old password before changing // try { // AuthCredential credential = // EmailAuthProvider.credential( // email: _auth.currentUser!.email!, // password: oldPassword, // ); // await _auth.currentUser! // .reauthenticateWithCredential(credential); // // Old password is correct, change the password // await changePassword(newPassword); // Navigator.of(context).pop(); // isLoading.value = false; // } catch (e) { // // Handle the case where the old password is incorrect // debugPrint('Error reauthenticating: $e'); // Get.snackbar( // "Unsuccessfull", "Enter You Correct Old Password.", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.red.withOpacity(0.7)); // isLoading.value = false; // } // } // } // }, // child: isLoading.value // ? const CircularProgressIndicator( // color: Colors.black, // ) // : const Text('Save'), // ), // ), // ], // ); // }, // ); // } void forgotPasswordDialog(context) { showDialog( context: context, barrierDismissible: false, builder: (context) { return AlertDialog( title: Text("Forget Password"), content: TextFormField( controller: useremailController, validator: validateUsername, decoration: const InputDecoration(labelText: "Enter your email"), ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Cancel'), ), ElevatedButton( onPressed: () { String email = useremailController.text.trim(); if (email.isNotEmpty) { sendPasswordResetEmail(email); Get.back(); } }, child: const Text("Reset Password"), ), ], ); }, ); // barrierDismissible: false, } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/controller/profile_screen_controller.dart
// import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:connectivity_plus/connectivity_plus.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'package:flutter/material.dart'; // import 'package:get/get.dart'; // import 'package:get/get_connect/http/src/utils/utils.dart'; // import '../db/entity/users.dart'; // import '../db/services/localdb_services.dart'; // class ProfileController extends GetxController { // final TextEditingController nameController = TextEditingController(); // final TextEditingController emailController = TextEditingController(); // final TextEditingController usernameController = TextEditingController(); // final TextEditingController phoneController = TextEditingController(); // final TextEditingController updatePassword = TextEditingController(); // final GlobalKey<FormState> formKey = GlobalKey<FormState>(); // User? user; // final Connectivity connectivity = Connectivity(); // final List<UserProfile> updateQueue = []; // final FirebaseAuth _auth = FirebaseAuth.instance; // final FirebaseFirestore _firestore = FirebaseFirestore.instance; // UserProfile? userData; // @override // void onInit() { // super.onInit(); // _loadUserData(); // _checkConnectivity(); // } // void addToUpdateQueue(UserProfile request) { // updateQueue.add(request); // } // Future<void> processPendingUpdates() async { // final ConnectivityResult result = await connectivity.checkConnectivity(); // if (result != ConnectivityResult.none) { // for (var request in updateQueue) { // await updateProfileInFirestore(request); // await updateProfileInLocalDb(request); // } // updateQueue.clear(); // } // } // Future<void> updateProfileInFirestore(UserProfile request) async { // try { // await _firestore.collection('users').doc(user!.email).update({ // 'name': request.name, // 'email': request.email, // 'username': request.username, // 'phone': request.phone, // }); // Get.snackbar("Updated", "'Profile updated successfully in Firestore'", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.green.withOpacity(0.6)); // } catch (error) { // debugPrint('Error updating profile in Firestore: $error'); // addToUpdateQueue(request); // } // } // Future<void> updateProfileInLocalDb(UserProfile request) async { // try { // final userDao = await LocalDbService.usersDao; // await userDao.insertUserProfile(UserProfile( // email: request.email, // name: request.name, // username: request.username, // phone: request.phone, // )); // Get.snackbar("Updated", "'Profile updated successfully in Local DB'", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.green.withOpacity(0.6)); // } catch (error) { // debugPrint('Error updating profile in local database: $error'); // addToUpdateQueue(request); // } // } // Future<void> _checkConnectivity() async { // final ConnectivityResult result = await connectivity.checkConnectivity(); // if (result == ConnectivityResult.none) { // _loadDataFromLocalDb(); // debugPrint("Data From Local DB"); // } else { // _loadUserData(); // debugPrint("Data From Firestore DB"); // } // } // Future<void> _loadDataFromLocalDb() async { // try { // final localUserData = await (await LocalDbService.usersDao) // .findUserProfileById(user!.email!); // if (localUserData != null) { // nameController.text = localUserData.name; // emailController.text = localUserData.email; // usernameController.text = localUserData.username; // phoneController.text = localUserData.phone; // } else { // debugPrint('User data not found in the local database.'); // } // } catch (error) { // debugPrint('Error loading data from local database: $error'); // } // } // Future<void> _loadUserData() async { // try { // user = _auth.currentUser; // if (user != null) { // final userDoc = // await _firestore.collection('users').doc(user!.email).get(); // final _userData = userDoc.data(); // if (userData != null) { // userData = UserProfile.fromFirestore(_userData!); // nameController.text = userData!.name; // emailController.text = userData!.email; // usernameController.text = userData!.username; // phoneController.text = userData!.phone; // } else { // debugPrint('User data is null.'); // } // } // } catch (error) { // debugPrint('Error loading data from Firebase: $error'); // } // } // void changepasswordDialog( // {required bool obscureOldpPass, // required bool obscureNewPass, // required bool isLoadingChngePassword, // required var context}) { // showDialog( // context: context, // builder: (BuildContext context) { // final TextEditingController oldPasswordController = // TextEditingController(); // final TextEditingController newPasswordController = // TextEditingController(); // return AlertDialog( // title: const Text('Change Password'), // content: Form( // key: formKey, // child: SingleChildScrollView( // child: Column( // children: [ // TextFormField( // controller: oldPasswordController, // obscureText: obscureOldpPass, // decoration: InputDecoration( // labelText: 'Old Password', // suffixIcon: IconButton( // icon: Icon( // obscureOldpPass // ? Icons.visibility // : Icons.visibility_off, // color: Colors.white, // ), // onPressed: () { // obscureOldpPass = !obscureOldpPass; // }, // ), // ), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter old password'; // } // return null; // }, // ), // TextFormField( // controller: newPasswordController, // obscureText: obscureNewPass, // decoration: InputDecoration( // labelText: 'New Password', // suffixIcon: IconButton( // icon: Icon( // obscureNewPass // ? Icons.visibility // : Icons.visibility_off, // color: Colors.white, // ), // onPressed: () { // obscureNewPass = !obscureNewPass; // }, // ), // ), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter new password'; // } else if (value.length < 6) { // return 'Password must be at least 6 characters'; // } // return null; // }, // ), // ], // ), // ), // ), // actions: [ // TextButton( // onPressed: () { // Navigator.of(context).pop(); // }, // child: const Text('Cancel'), // ), // ElevatedButton( // onPressed: isLoadingChngePassword // ? null // : () async { // isLoadingChngePassword = true; // debugPrint("object"); // String oldPassword = oldPasswordController.text; // String newPassword = newPasswordController.text; // if (oldPassword.isNotEmpty && newPassword.isNotEmpty) { // // Verify the old password before changing // try { // AuthCredential credential = // EmailAuthProvider.credential( // email: _auth.currentUser!.email!, // password: oldPassword, // ); // await _auth.currentUser! // .reauthenticateWithCredential(credential); // // Old password is correct, change the password // await changePassword(newPassword); // Navigator.of(context).pop(); // isLoadingChngePassword = false; // } catch (e) { // // Handle the case where the old password is incorrect // debugPrint('Error reauthenticating: $e'); // Get.snackbar("Unsuccessfull", // "Your password has Not updated Unsuccessfull.", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.red.withOpacity(0.7)); // isLoadingChngePassword = false; // } // } // }, // child: isLoadingChngePassword // ? const CircularProgressIndicator( // color: Colors.black, // ) // : const Text('Save'), // ), // ], // ); // }, // ); // } // Future<void> changePassword(String newPassword) async { // try { // User? user = FirebaseAuth.instance.currentUser; // await user?.updatePassword(newPassword); // Get.snackbar( // "Password Changed", "Your password has been updated successfully.", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.greenAccent.withOpacity(0.7)); // } catch (error) { // Get.snackbar("Error", error.toString(), // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.redAccent.withOpacity(0.7)); // } // } // void showEditProfileDialog(context) { // showDialog( // context: context, // builder: (BuildContext context) { // return AlertDialog( // title: const Text('Edit Profile'), // content: Form( // key: formKey, // child: SingleChildScrollView( // child: Column( // children: [ // TextFormField( // controller: nameController, // decoration: const InputDecoration(labelText: 'Name'), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter your name'; // } // return null; // }, // ), // TextFormField( // controller: emailController, // decoration: const InputDecoration( // labelText: 'Email', // // Set the enabled property to false to make it read-only // enabled: false, // ), // ), // TextFormField( // controller: usernameController, // decoration: const InputDecoration(labelText: 'Username'), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter your username'; // } // return null; // }, // ), // TextFormField( // controller: phoneController, // decoration: // const InputDecoration(labelText: 'Phone Number'), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter your phone number'; // } // return null; // }, // ), // ], // ), // ), // ), // actions: [ // TextButton( // onPressed: () { // Navigator.of(context).pop(); // }, // child: const Text('Cancel'), // ), // ElevatedButton( // onPressed: () { // if (formKey.currentState!.validate()) { // // Update user data in Firestore // _updateUserData( // name: nameController.text, // email: emailController.text, // username: usernameController.text, // phone: phoneController.text, // ); // Navigator.of(context).pop(); // } // }, // child: const Text('Save'), // ), // ], // ); // }, // ); // } // Future<void> _updateUserData({ // required String name, // required String email, // required String username, // required String phone, // }) async { // try { // // Check if the new email is already registered // // Update user data in Firestore // await _firestore // .collection('users') // .doc(_auth.currentUser!.email) // .update({ // 'name': name, // 'username': username, // 'phone': phone, // }); // // await (await LocalDbService.usersDao).updateUserProfile(UserProfile( // // name: name, email: email, username: username, phone: phone)); // final currentEmail = _auth.currentUser!.email; // await (await LocalDbService.usersDao).updateUserProfile(UserProfile( // name: name, email: currentEmail!, username: username, phone: phone)); // // Update user email in Firebase Authentication // await user!.updateEmail(email); // // Reload user data // _loadUserData(); // // Show a success message // Get.snackbar("Updated", "'Profile updated successfully'", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.green.withOpacity(0.6)); // } catch (error) { // // Handle error, e.g., show an error message // Get.snackbar("Error", 'Error updating profile: $error'); // debugPrint(error.toString()); // } // } // } import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:film_fusion/db/entity/users.dart'; import 'package:film_fusion/db/services/localdb_services.dart'; import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:get/get.dart'; class ProfileController extends GetxController { final TextEditingController nameController = TextEditingController(); final TextEditingController emailController = TextEditingController(); final TextEditingController usernameController = TextEditingController(); final TextEditingController phoneController = TextEditingController(); final TextEditingController oldpaswordCon = TextEditingController(); final TextEditingController newPassCon = TextEditingController(); final GlobalKey<FormState> formKey = GlobalKey<FormState>(); final FirebaseAuth _auth = FirebaseAuth.instance; final FirebaseFirestore _firestore = FirebaseFirestore.instance; User? user; Rx<UserProfile?> userData = Rx<UserProfile?>(null); final Connectivity _connectivity = Connectivity(); List<UserProfile> updateQueue = []; RxBool obscureOldPass = true.obs; RxBool obscureNewPass = true.obs; RxBool isLoadingChangePassword = false.obs; @override void onInit() { super.onInit(); _loadUserData(); _checkConnectivity(); saveTolcaldbWhenEmailNotExists(); } void saveTolcaldbWhenEmailNotExists() async { final emailList = await (await LocalDbService.usersDao).getEmails(); final currentUserEmail = _auth.currentUser?.email; final userDoc = await _firestore .collection('users') .doc(_auth.currentUser!.email) .get(); final userData = userDoc.data(); if (!emailList.contains(currentUserEmail.toString())) { debugPrint("Data added to local db"); UserProfile _userData = UserProfile.fromFirestore(userData!); await (await LocalDbService.usersDao).insertUserProfile(UserProfile( name: _userData.name, email: _userData.email, username: _userData.username, phone: _userData.phone, )); } } void addToUpdateQueue(UserProfile request) { updateQueue.add(request); } Future<void> processPendingUpdates() async { final ConnectivityResult result = await Connectivity().checkConnectivity(); if (result != ConnectivityResult.none) { for (var request in updateQueue) { await updateProfileInFirestore(request); await updateProfileInLocalDb(request); } updateQueue.clear(); } } Future<void> updateProfileInFirestore(UserProfile request) async { try { await _firestore .collection('users') .doc(_auth.currentUser!.email) .update({ 'name': request.name, 'email': request.email, 'username': request.username, 'phone': request.phone, }); Get.snackbar("Updated", "Profile updated successfully in Firestore", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.green.withOpacity(0.6)); } catch (error) { debugPrint('Error updating profile in Firestore: $error'); addToUpdateQueue(request); } } Future<void> updateProfileInLocalDb(UserProfile request) async { try { final userDao = await LocalDbService.usersDao; await userDao.insertUserProfile(UserProfile( email: request.email, name: request.name, username: request.username, phone: request.phone, )); Get.snackbar("Updated", "Profile updated successfully in Local DB", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.green.withOpacity(0.6)); } catch (error) { debugPrint('Error updating profile in local database: $error'); addToUpdateQueue(request); } } Future<void> _checkConnectivity() async { final ConnectivityResult result = await _connectivity.checkConnectivity(); if (result == ConnectivityResult.none) { _loadDataFromLocalDb(); debugPrint("Data from Local DB"); } else { _loadUserData(); debugPrint("Data from Firestore DB"); } } Future<void> _loadDataFromLocalDb() async { try { final localUserData = await (await LocalDbService.usersDao) .findUserProfileById(user!.email.toString()); if (localUserData != null) { nameController.text = userData.value!.name; emailController.text = userData.value!.email; usernameController.text = userData.value!.username; phoneController.text = userData.value!.phone; } else { debugPrint('User data not found in the local database.'); } } catch (error) { debugPrint('Error loading data from local database: $error'); } } Future<void> _loadUserData() async { try { user = _auth.currentUser; if (user != null) { final userDoc = await _firestore .collection('users') .doc(_auth.currentUser!.email) .get(); final _userData = userDoc.data(); if (_userData != null) { userData.value = UserProfile.fromFirestore(_userData); nameController.text = userData.value!.name; emailController.text = userData.value!.email; usernameController.text = userData.value!.username; phoneController.text = userData.value!.phone; } else { debugPrint('User data is null.'); } } } catch (error) { debugPrint('Error loading data from Firebase: $error'); } } void changepasswordDialog(context) { RxBool isLoading = false.obs; showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { final TextEditingController oldPasswordController = TextEditingController(); final TextEditingController newPasswordController = TextEditingController(); return AlertDialog( title: const Text('Change Password'), content: Form( key: formKey, child: SingleChildScrollView( child: Column( children: [ Obx( () => TextFormField( controller: oldPasswordController, obscureText: obscureOldPass.value, decoration: InputDecoration( labelText: 'Old Password', suffixIcon: IconButton( icon: Icon( obscureOldPass.value ? Icons.visibility : Icons.visibility_off, color: Colors.black, ), onPressed: () { obscureOldPass.value = !obscureOldPass.value; }, ), ), validator: (value) { if (value == null || value.isEmpty) { isLoading.value = false; return 'Please enter old password'; } return null; }, ), ), Obx( () => TextFormField( controller: newPasswordController, obscureText: obscureNewPass.value, decoration: InputDecoration( labelText: 'New Password', suffixIcon: IconButton( icon: Icon( obscureNewPass.value ? Icons.visibility : Icons.visibility_off, color: Colors.black, ), onPressed: () { obscureNewPass.value = !obscureNewPass.value; }, ), ), validator: (value) { if (value == null || value.isEmpty) { isLoading.value = false; return 'Please enter new password'; } else if (value.length < 6) { isLoading.value = false; return 'Password must be at least 6 characters'; } return null; }, ), ) ], ), ), ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Cancel'), ), Obx( () => ElevatedButton( onPressed: () async { isLoading.value = true; debugPrint("object"); String oldPassword = oldPasswordController.text; String newPassword = newPasswordController.text; if (formKey.currentState!.validate()) { if (oldPassword.isNotEmpty && newPassword.isNotEmpty) { // Verify the old password before changing try { AuthCredential credential = EmailAuthProvider.credential( email: _auth.currentUser!.email!, password: oldPassword, ); await _auth.currentUser! .reauthenticateWithCredential(credential); // Old password is correct, change the password await changePassword(newPassword); Navigator.of(context).pop(); isLoading.value = false; } catch (e) { // Handle the case where the old password is incorrect debugPrint('Error reauthenticating: $e'); Get.snackbar( "Unsuccessfull", "Enter You Correct Old Password.", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.red.withOpacity(0.7)); isLoading.value = false; } } } }, child: isLoading.value ? const CircularProgressIndicator( color: Colors.black, ) : const Text('Save'), ), ), ], ); }, ); } Future<void> changePassword(String newPassword) async { try { User? user = FirebaseAuth.instance.currentUser; await user?.updatePassword(newPassword); Get.snackbar( "Password Changed", "Your password has been updated successfully.", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.greenAccent.withOpacity(0.7), ); } catch (error) { Get.snackbar( "Error", error.toString(), snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.redAccent.withOpacity(0.7), ); } } void showEditProfileDialog(context) { RxBool isLoading = false.obs; // Add a boolean to track loading state showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return StatefulBuilder( builder: (context, setState) { // Wrap the AlertDialog in a StatefulBuilder to access the local state return AlertDialog( title: const Text('Edit Profile'), content: Form( key: formKey, child: SingleChildScrollView( child: Column( children: [ TextFormField( controller: nameController, decoration: const InputDecoration(labelText: 'Name'), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your name'; } return null; }, ), TextFormField( controller: emailController, decoration: const InputDecoration( labelText: 'Email', enabled: false, ), ), TextFormField( controller: usernameController, decoration: const InputDecoration(labelText: 'Username'), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your username'; } return null; }, ), TextFormField( controller: phoneController, decoration: const InputDecoration(labelText: 'Phone Number'), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your phone number'; } return null; }, ), ], ), ), ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('Cancel'), ), Obx( () => ElevatedButton( onPressed: isLoading.value // Check loading state ? null : () async { if (formKey.currentState!.validate()) { isLoading.value = true; // Set loading state to true // Update user data in Firestore await _updateUserData( name: nameController.text, email: emailController.text, username: usernameController.text, phone: phoneController.text, ); Navigator.of(context).pop(); isLoading.value = false; // Set loading state to false } }, child: isLoading.value ? const CircularProgressIndicator() // Show loader when loading : const Text('Save'), ), ), ], ); }, ); }, ); } Future<void> _updateUserData({ required String name, required String email, required String username, required String phone, }) async { try { await _firestore .collection('users') .doc(_auth.currentUser!.email) .update({ 'name': name, 'username': username, 'phone': phone, }); final currentEmail = _auth.currentUser!.email; await (await LocalDbService.usersDao).updateUserProfile(UserProfile( name: name, email: currentEmail!, username: username, phone: phone, )); await user!.updateEmail(email); _loadUserData(); Get.snackbar("Updated", "Profile updated successfully", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.green.withOpacity(0.6)); } catch (error) { Get.snackbar("Error", 'Error updating profile: $error'); debugPrint(error.toString()); } } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/controller/favorite_screen_controller.dart
// import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'package:flutter/material.dart'; // import 'package:get/get.dart'; // import '../model/movie_by_id_model.dart'; // import '../model/new_movies_model.dart'; // import '../services/movies_data.dart'; // import 'package:shared_preferences/shared_preferences.dart'; // class FavorieScreenController extends GetxController { // // RxList<MovieByIdModel> favoriteMovies = <MovieByIdModel>[].obs; // RxBool isLoading = true.obs; // // RxBool isFav = false.obs;// // final RxSet<int> favoriteMovieIds = <int>{}.obs; // final RxBool isFavarit = false.obs; // SharedPreferences? prefs; // List<Latest> movies = []; // @override // void onInit() { // // _loadUserData(); // _loadSharedPreferences(); // fetchFavoriteMovies(); // super.onInit(); // } // void toggleFavoriteStatus(int movieId) { // for (final movie in movies) { // if (movie.id == movieId) { // movie.isFavorite = !movie.isFavorite; // return; // Exit the loop once the movie is found and toggled. // } // } // } // List<Latest> get favoriteMoviesNew { // return movies.where((movie) => movie.isFavorite).toList(); // } // Future<void> _loadSharedPreferences() async { // prefs = await SharedPreferences.getInstance(); // final List<int> storedIds = prefs // ?.getStringList('favoriteMovieIds') // ?.map((id) => int.parse(id)) // .toList() ?? // []; // favoriteMovieIds.addAll(storedIds); // } // Stream<List<MovieByIdModel>> fetchFavoriteMovies() async* { // final user = FirebaseAuth.instance.currentUser; // final List<MovieByIdModel> favoriteMovies = []; // if (user != null) { // final userDoc = await FirebaseFirestore.instance // .collection('users') // .doc(user.uid) // .get(); // final favoriteMovieIds = // List<int>.from(userDoc.get('favoriteMovies') ?? []); // // Fetch details for each favorite movie using your API // for (final movieId in favoriteMovieIds) { // final movie = await MovieService.fetchMovieById(movieId); // favoriteMovies.add(movie); // debugPrint("assedd"); // } // } // isLoading.value = false; // yield favoriteMovies; // } // Future<void> addToFav(int movieId) async { // final user = FirebaseAuth.instance.currentUser; // if (user != null) { // final userRef = // FirebaseFirestore.instance.collection('users').doc(user.uid); // if (favoriteMovieIds.contains(movieId)) { // print(movieId); // await userRef.update({ // 'favoriteMovies': FieldValue.arrayRemove([movieId]), // }); // favoriteMovieIds.remove(movieId); // isFavarit(false); // } else { // await userRef.update({ // 'favoriteMovies': FieldValue.arrayUnion([movieId]), // }); // favoriteMovieIds.add(movieId); // isFavarit(true); // } // await prefs?.setStringList('favoriteMovieIds', // favoriteMovieIds.map((id) => id.toString()).toList()); // } // } // Future<void> removeFromFavorites(int movieId) async { // final user = FirebaseAuth.instance.currentUser; // if (user != null) { // // Remove the movie ID from the local list // favoriteMovieIds.remove(movieId); // // Remove the movie ID from Firestore // await FirebaseFirestore.instance // .collection('users') // .doc(user.uid) // .update({ // 'favoriteMovies': FieldValue.arrayRemove([movieId]) // }); // fetchFavoriteMovies(); // } // } // // Future<bool> checkIfFavorite(String movieIdFromApi) async { // // final user = FirebaseAuth.instance.currentUser; // // try { // // final userDoc = // // FirebaseFirestore.instance.collection('users').doc(user!.uid); // // final favoritesSnapshot = await userDoc.collection('favorites').get(); // // // Check if the movie ID from the API exists in the user's favorites // // if (favoritesSnapshot.docs // // .any((doc) => doc.id.toString() == movieIdFromApi)) { // // isFav.value = true; // // } // // } catch (e) { // // print('Error checking favorite: $e'); // // } // // return isFav.value; // // } // // Stream<List<MovieByIdModel>> fetchFavoriteMovies() async*{ // // final user = FirebaseAuth.instance.currentUser; // // if (user != null) { // // final userDoc = await FirebaseFirestore.instance // // .collection('users') // // .doc(user.uid) // // .get(); // // final favoriteMovieIds = // // List<int>.from(userDoc.get('favoriteMovies') ?? []); // // // Fetch details for each favorite movie using your API // // for (final movieId in favoriteMovieIds) { // // final movie = await MovieService.fetchMovieById(movieId); // // favoriteMovies.add(movie); // // } // // } else { // // yield* Stream.value(<int>[].cast<MovieByIdModel>()); // Return an empty stream if user is not logged in // // } // // } // } import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:film_fusion/model/new_movies_model.dart'; import 'package:get/get.dart'; class FavoriteMoviesController extends GetxController { final RxList<Movies> favoriteMovies = <Movies>[].obs; final RxBool isLoading = false.obs; // Add isLoading variable final FirebaseFirestore _firestore = FirebaseFirestore.instance; // Method to toggle a movie's favorite status in Firestore Future<void> toggleFavorite( {required Movies movie, required String userId}) async { final userDoc = _firestore.collection('users').doc(userId); final movieDoc = userDoc.collection('favorites').doc(movie.id.toString()); final isFavorite = favoriteMovies.any((favoriteMovie) => favoriteMovie.id == movie.id); if (isFavorite) { // Remove from favorites await movieDoc.delete(); favoriteMovies.removeWhere((favoriteMovie) => favoriteMovie.id == movie.id); // Get.snackbar('Removed from Favorites', movie.title, // snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.red); } else { // Add to favorites await movieDoc.set({ 'id': movie.id, 'title': movie.title, 'poster_path': movie.posterPath, 'voteAverage': movie.voteAverage }); favoriteMovies.add(movie); // Get.snackbar('Added to Favorites', movie.title, // snackPosition: SnackPosition.BOTTOM,backgroundColor: Colors.green); } // Toggle the isFavorite property } bool isMovieFavorite(Movies movie) { return favoriteMovies.any((favoriteMovie) => favoriteMovie.id == movie.id); } //Method to fetch user's favorite movies from Firestore Future<void> fetchFavoriteMovies(String userId) async { isLoading.value = true; final userDoc = _firestore.collection('users').doc(userId); final querySnapshot = await userDoc.collection('favorites').get(); final movies = querySnapshot.docs.map((doc) { final data = doc.data(); DateTime parseDate(dynamic date) { if (date is Timestamp) { return date.toDate(); } return DateTime .now(); // Provide a default value if the date is missing or in an unexpected format. } return Movies( id: data['id'] ?? 0, // Provide a default value if 'id' is missing. title: data['title'] ?? 'Unknown', // Provide a default value if 'title' is missing. posterPath: data['poster_path'] != null ? data['poster_path'] as String : '', genreIds: List<int>.from(data['genreIds'] ?? []), overview: data['overview'] ?? '', releaseDate: parseDate(data['release_date']), voteAverage: data['voteAverage']?.toDouble() ?? 0.0, isFavorite: true, ); }).toList(); favoriteMovies.assignAll(movies); isLoading.value = false; } // Future<void> fetchFavoriteMovies(String userId) async { // final userDoc = _firestore.collection('users').doc(userId); // // Get the user's favorite movies data // final userFavoritesDoc = // await userDoc.collection('favorites').doc('user_favorites').get(); // if (userFavoritesDoc.exists) { // final userFavoritesData = userFavoritesDoc.data() as Map<String, dynamic>; // DateTime parseDate(dynamic date) { // if (date is Timestamp) { // return date.toDate(); // } // return DateTime // .now(); // Provide a default value if the date is missing or in an unexpected format. // } // final movies = userFavoritesData.values.map((data) { // return Movies( // id: data['id'] ?? 0, // Provide a default value if 'id' is missing. // title: data['title'] ?? // 'Unknown', // Provide a default value if 'title' is missing. // posterPath: // data['poster_path'] != null ? data['poster_path'] as String : '', // genreIds: List<int>.from(data['genreIds'] ?? []), // overview: data['overview'] ?? '', // releaseDate: parseDate(data['release_date']), // voteAverage: data['voteAverage']?.toDouble() ?? 0.0, // isFavorite: true, // ); // }).toList(); // favoriteMovies.assignAll(movies); // } else { // favoriteMovies.clear(); // } // } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/controller/sign_up_controller.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:firebase_auth/firebase_auth.dart'; import '../../services/firebase_service.dart'; import '../screens/auth/sms_code_screen.dart'; class SignUpController extends GetxController { final isLoading = false.obs; final obscurePass = true.obs; final obscureConf = true.obs; final formKey = GlobalKey<FormState>(); final nameController = TextEditingController(); final usernameController = TextEditingController(); final emailController = TextEditingController(); final phoneController = TextEditingController(); final passwordController = TextEditingController(); final confirmPasswordController = TextEditingController(); final smsCodeController = TextEditingController(); String verificationId = ''; final FirebaseAuth auth = FirebaseAuth.instance; final FirebaseService firebaseService = FirebaseService(); String? validateName(String? value) { if (value == null || value.isEmpty) { return 'Name is required'; } return null; } String? validateUsername(String? value) { if (value == null || value.isEmpty) { return 'Username is required'; } return null; } String? validateEmail(String? value) { if (value == null || value.isEmpty) { return 'Email is required'; } else if (!value.contains('@')) { return 'Invalid email format'; } return null; } String? validatePhone(String? value) { if (value == null || value.isEmpty) { return 'Phone number is required'; } else if (value.length != 11) { return 'Phone number should be 10 digits'; } return null; } String? validatePassword(String? value) { if (value == null || value.isEmpty) { return 'Password is required'; } return null; } String? validateConfirmPassword(String? value) { if (value == null || value.isEmpty) { return 'Confirm Password is required'; } else if (value != passwordController.text) { return 'Passwords do not match'; } return null; } String? validatePhoneNumber(String? value) { if (value == null || value.isEmpty) { return 'Please enter a valid 10-digit phone number'; } return null; } void signUp() async { if (formKey.currentState!.validate()) { try { isLoading.value = true; await auth.verifyPhoneNumber( phoneNumber: "+92${phoneController.text}", verificationCompleted: (AuthCredential credential) { _signInWithCredential(credential); }, verificationFailed: (FirebaseAuthException e) { print("Verification Failed: ${e.message}"); isLoading.value = false; }, codeSent: (String verificationId, int? resendToken) { this.verificationId = verificationId; Get.to( SmsCodeScreen( verificationId: verificationId, name: nameController.text, phone: "+92${phoneController.text}", username: usernameController.text, email: emailController.text, password: passwordController.text, ), ); isLoading.value = false; }, codeAutoRetrievalTimeout: (String verificationId) {}, ); } catch (e) { isLoading.value = false; print("Error sending SMS code: $e"); } } } Future<void> _signInWithCredential(AuthCredential credential) async { try { await auth.signInWithCredential(credential); await firebaseService.signUpUser( email: emailController.text, password: passwordController.text, name: nameController.text, phone: "+92${phoneController.text}", username: usernameController.text, ); Get.offNamed(login); } catch (e) { print("Error signing in: $e"); } } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/controller/sms_code_controller.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/db/entity/users.dart'; import 'package:film_fusion/db/services/localdb_services.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class SmsCodeController extends GetxController { final FirebaseAuth _auth = FirebaseAuth.instance; final FirebaseFirestore _firestore = FirebaseFirestore.instance; final TextEditingController smsCodeController = TextEditingController(); final isLoading = false.obs; Future<void> verifySmsCode({ required String verificationId, required String name, required String phone, required String username, required String email, required String password, }) async { AuthCredential credential = PhoneAuthProvider.credential( verificationId: verificationId, smsCode: smsCodeController.text, ); isLoading.value = true; try { // Verify the SMS code await _auth.signInWithCredential(credential); // If verification is successful, register the user await (await LocalDbService.usersDao).insertUserProfile(UserProfile( name: name, username: username, email: email, phone: phone, )); // Attempt to save user data in Firestore await _firestore.collection('users').doc(email).set({ 'name': name, 'email': email, 'phone': phone, 'username': username, }); await _auth.createUserWithEmailAndPassword( email: email, password: password, ); // Navigate to the login screen Get.offAllNamed(mainScreen); isLoading.value = false; } catch (e) { // Handle verification errors // Display an error message to the user final snackBar = SnackBar(content: Text('Verification failed: $e')); debugPrint(e.toString()); isLoading.value = false; ScaffoldMessenger.of(Get.context!).showSnackBar(snackBar); // If any exceptions occur, avoid saving data to Firestore } } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/controller/home_screen_controller.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../model/new_movies_model.dart'; import '../model/trending_movies_model.dart'; import '../services/movies_data.dart'; class HomeScreenController extends GetxController { RxBool isLoading = true.obs; RxList<Movies> latsetmoviesList = <Movies>[].obs; RxList<Movies> trendingmoviesList = <Movies>[].obs; RxList<Movies> topRatedmoviesList = <Movies>[].obs; // RxList<Movies> moviesList = <Movies>[].obs; RxInt latestPage = 1.obs; // Page for latest movies RxInt trendingPage = 1.obs; RxInt topRtaedPage = 1.obs; // Page for trending movies RxBool latestHasMoreData = true.obs; RxBool trendingHasMoreData = true.obs; RxBool topRatedHasMoreData = true.obs; var scrollControllerLatest = ScrollController(); var scrollControllerTrending = ScrollController(); var scrollControllerTopRated = ScrollController(); final searchResults = <Movies>[].obs; // final suggestions = <String>[].obs; // Suggestions list @override void onInit() { fetchLatestMovies(); fetchTrendingMovies(); configureScrollControllers(); fetchTopRatedMovies(); super.onInit(); } Future<void> fetchLatestMovies() async { try { isLoading.value = true; // Fetch latest movies data final newLatestMovies = await MovieService.getNewMovies(latestPage.value); latsetmoviesList.addAll(newLatestMovies); latestHasMoreData.value = true; // Set to true if there's more data to load } finally { isLoading.value = false; } } Future<void> fetchTrendingMovies() async { try { isLoading.value = true; // Fetch trending movies data final newTrendingMovies = await MovieService.fetchTrendingMovies(trendingPage.value); trendingmoviesList.addAll(newTrendingMovies); trendingHasMoreData.value = true; // Set to true if there's more data to load } finally { isLoading.value = false; } } Future<void> fetchTopRatedMovies() async { try { isLoading.value = true; // Fetch trending movies data final topRated = await MovieService.fetchToRatedMovies(topRtaedPage.value); topRatedmoviesList.addAll(topRated); topRatedHasMoreData.value = true; // Set to true if there's more data to load } finally { isLoading.value = false; } } Future<void> searchMovies(String query) async { try { isLoading.value = true; final movies = await MovieService.searchMovies(query); debugPrint(movies.length.toString()); searchResults.assignAll(movies); } finally { isLoading.value = false; } } void clearSuggestions() { searchResults.clear(); } void configureScrollControllers() { // Configure scroll controller for latest movies list scrollControllerLatest.addListener(() { if (scrollControllerLatest.position.pixels == scrollControllerLatest.position.maxScrollExtent) { // Reached the end of the list, load more data if (latestHasMoreData.value) { loadMoreLatestMovies(); } } }); // Configure scroll controller for trending movies list scrollControllerTrending.addListener(() { if (scrollControllerTrending.position.pixels == scrollControllerTrending.position.maxScrollExtent) { // Reached the end of the list, load more data if (trendingHasMoreData.value) { loadMoreTrendingMovies(); } } }); scrollControllerTopRated.addListener(() { if (scrollControllerTopRated.position.pixels == scrollControllerTopRated.position.maxScrollExtent) { // Reached the end of the list, load more data if (topRatedHasMoreData.value) { loadMoreTopRatedMovies(); } } }); } void loadMoreLatestMovies() async { latestPage++; debugPrint(latestPage.toString()); final moreLatestMovies = await MovieService.getNewMovies(latestPage.value); latsetmoviesList.addAll(moreLatestMovies); } void loadMoreTrendingMovies() async { trendingPage++; debugPrint(trendingPage.toString()); final moreTrendingMovies = await MovieService.fetchTrendingMovies(trendingPage.value); trendingmoviesList.addAll(moreTrendingMovies); } void loadMoreTopRatedMovies() async { topRtaedPage++; debugPrint(topRtaedPage.toString()); final moreToRatedMovies = await MovieService.fetchTrendingMovies(topRtaedPage.value); topRatedmoviesList.addAll(moreToRatedMovies); } void resetPageParameter() { trendingPage = 1.obs; // Reset the page parameter for trending movies latestPage = 1.obs; topRtaedPage = 1.obs; // Reset the page parameter for latest movies } @override void onClose() { scrollControllerLatest .dispose(); // Dispose of the latest movies scroll controller scrollControllerTrending.dispose(); scrollControllerTopRated .dispose(); // Dispose of the trending movies scroll controller super.onClose(); } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/utils/genre_data.dart
class GenreData { final Map<String, List<Map<String, Object>>> genreData = { "genres": [ {"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 16, "name": "Animation"}, {"id": 35, "name": "Comedy"}, {"id": 80, "name": "Crime"}, {"id": 99, "name": "Documentary"}, {"id": 18, "name": "Drama"}, {"id": 10751, "name": "Family"}, {"id": 14, "name": "Fantasy"}, {"id": 36, "name": "History"}, {"id": 27, "name": "Horror"}, {"id": 10402, "name": "Music"}, {"id": 9648, "name": "Mystery"}, {"id": 10749, "name": "Romance"}, {"id": 878, "name": "Science Fiction"}, {"id": 10770, "name": "TV Movie"}, {"id": 53, "name": "Thriller"}, {"id": 10752, "name": "War"}, {"id": 37, "name": "Western"} ] }; String mapGenreIdsToNames(List<int> genreIds, int count) { if (genreIds.isEmpty) { return 'Unknown'; } final genreNames = genreIds .map((genreId) { final genre = genreData['genres']?.firstWhere( (genre) => genre['id'] == genreId, orElse: () => {'name': 'Unknown'}, ); return genre?['name'] ?? 'Unknown'; }) .take(count) .toList(); return genreNames.join('-'); } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/utils/toast_message.dart
import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; class ToastMessage { static void toastMessage(String message) { Fluttertoast.showToast( msg: message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 3, backgroundColor: Colors.red, textColor: Colors.white, fontSize: 16.0); } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/utils/screen_bidings.dart
import 'package:film_fusion/controller/favorite_screen_controller.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:get/get.dart'; class ScreenBidings extends Bindings { @override void dependencies() { Get.lazyPut(() => HomeScreenController()); Get.lazyPut(() => FavoriteMoviesController()); // Get.lazyPut(() => SearchResyltController()); } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/utils/route_generator.dart
import 'package:film_fusion/main.dart'; import 'package:film_fusion/screens/auth/sign_up_screen.dart'; import 'package:film_fusion/screens/favorite/fav_screen.dart'; import 'package:film_fusion/screens/home/detailScreen/detail_screen.dart'; import 'package:film_fusion/screens/home/home_screen.dart'; import 'package:film_fusion/screens/home/splash/splash_screen.dart'; import 'package:get/get.dart'; import '../screens/auth/login_screen.dart'; class RouteGenerator { static List<GetPage> getPages() { return [ GetPage( name: '/splash', page: () => const SplashScreen(), ), GetPage( name: '/login', page: () => LoginScreen(), ), GetPage( name: '/signup', page: () => SignUpScreen(), ), GetPage( name: '/main', page: () => const MainPage(), ), GetPage( name: '/home', page: () => const HomeScreen(), ), GetPage( name: '/detail', page: () => const MovieDetailScreen(), ), GetPage( name: '/fav', page: () => FavScreen(), ) ]; } }
0
mirrored_repositories/flim_fusion/lib/utils
mirrored_repositories/flim_fusion/lib/utils/constants/routes.dart
String splash = "/splash"; String login = "/login"; String signup = "/signup"; String homeScreen = "/home"; String detailScreen = "/detail"; String mainScreen = "/main"; String favScreen = "/fav"; // String latestdetailScreen = "/detail"; // String trendingCategoryScreen = "/trending"; // String latestCategoryScreen = "/latest";
0
mirrored_repositories/flim_fusion/lib/utils
mirrored_repositories/flim_fusion/lib/utils/constants/api_key.dart
String apiKey = "47ffa47d8792fe1a414a82a3db71ea2e";
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/services/movies_data.dart
import 'dart:convert'; import 'package:film_fusion/utils/constants/api_key.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '../model/new_movies_model.dart'; class MovieService { static Future<List<Movies>> fetchTrendingMovies(int page) async { final response = await http.get( Uri.parse( 'https://api.themoviedb.org/3/trending/movie/day?api_key=$apiKey&page=$page'), ); debugPrint("Trending Movies responce"); debugPrint(response.body); if (response.statusCode == 200) { final trendingMovieModel = LatestMoviesModel.fromJson(json.decode(response.body)); return trendingMovieModel.results; } else { throw Exception('Failed to load trending movies'); } } /// New Movies// static Future<List<Movies>> getNewMovies(int page) async { final response = await http.get( Uri.parse( 'https://api.themoviedb.org/3/movie/now_playing?api_key=$apiKey&page=$page'), ); debugPrint("Latest Movies responce"); debugPrint(response.body); if (response.statusCode == 200) { final lstestMovieModel = LatestMoviesModel.fromJson(json.decode(response.body)); return lstestMovieModel.results; } else { throw Exception('Failed to load new movies'); } } static Future<List<Movies>> searchMovies(String query) async { final response = await http.get(Uri.parse( 'https://api.themoviedb.org/3/search/movie?api_key=$apiKey&query=$query')); if (response.statusCode == 200) { final trendingMovie = LatestMoviesModel.fromJson(json.decode(response.body)); return trendingMovie.results; } else { throw Exception('Failed to load trending movies'); } } static Future<List<Movies>> fetchToRatedMovies(int page) async { final response = await http.get( Uri.parse( 'https://api.themoviedb.org/3/movie/top_rated?api_key=$apiKey&page=$page'), ); debugPrint("To Rtaed Movies responce"); debugPrint(response.body); if (response.statusCode == 200) { final toRatedMovie = LatestMoviesModel.fromJson(json.decode(response.body)); return toRatedMovie.results; } else { throw Exception('Failed to load trending movies'); } } // https://api.themoviedb.org/3/movie/top_rated?api_key=47ffa47d8792fe1a414a82a3db71ea2e // static Future<MovieByIdModel> fetchMovieById(int movieId) async { // // Replace with your actual API endpoint // final apiUrl = // 'https://api.themoviedb.org/3/movie/$movieId?api_key=$apiKey'; // final response = await http.get(Uri.parse(apiUrl)); // if (response.statusCode == 200) { // final jsonData = json.decode(response.body); // final movie = MovieByIdModel.fromJson(jsonData); // return movie; // } else { // throw Exception('Failed to fetch movie details'); // } // } }
0
mirrored_repositories/flim_fusion/lib
mirrored_repositories/flim_fusion/lib/services/firebase_service.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class FirebaseService { final FirebaseAuth _auth = FirebaseAuth.instance; final FirebaseFirestore _firestore = FirebaseFirestore.instance; // Getter for isSaved Future<void> signUpUser({ required String email, required String password, required String name, required String phone, required String username, //required Null Function(String verificationId) onVerificationCompleted, required Null Function(String error) onVerificationFailed, }) async { try { // Create a user account with email and password // await _auth.createUserWithEmailAndPassword( // email: email, password: password); // await _auth.signInWithCredential(credential) // Get the current user's UID final currentUser = _auth.currentUser; final uid = currentUser?.uid; if (uid != null) { // Store user data in Firestore await _firestore.collection('users').doc(uid).set({ 'name': name, 'phone': phone, 'email': email, 'username': username, }); } } catch (e) { // Handle signup errors debugPrint('Signup Error: $e'); } } // Future<void> saveMovieToFirestore(int movieId) async { // final user = FirebaseAuth.instance.currentUser; // if (user != null) { // final userDoc = // FirebaseFirestore.instance.collection('users').doc(user.uid); // final currentFavorites = await userDoc.get().then((doc) { // if (doc.exists) { // return List<int>.from(doc['favoriteMovies'] ?? []); // } else { // return []; // } // }); // currentFavorites.add(movieId); // await userDoc.set({'favoriteMovies': currentFavorites}); // } // } }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/stream/stream_screen.dart
import 'package:flutter/material.dart'; class StreamScreen extends StatelessWidget { const StreamScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Fav Screen")), ); } }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/profile/profile_screen.dart
// import 'package:connectivity_plus/connectivity_plus.dart'; // import 'package:film_fusion/constants/routes.dart'; // import 'package:film_fusion/db/entity/users.dart'; // import 'package:film_fusion/db/services/localdb_services.dart'; // import 'package:film_fusion/utils/toast_message.dart'; // import 'package:flutter/material.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:get/get.dart'; // class ProfileScreen extends StatefulWidget { // @override // _ProfileScreenState createState() => _ProfileScreenState(); // } // class _ProfileScreenState extends State<ProfileScreen> { // final TextEditingController nameController = TextEditingController(); // final TextEditingController emailController = TextEditingController(); // final TextEditingController usernameController = TextEditingController(); // final TextEditingController phoneController = TextEditingController(); // final TextEditingController updatePassword = TextEditingController(); // final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); // final FirebaseAuth _auth = FirebaseAuth.instance; // final FirebaseFirestore _firestore = FirebaseFirestore.instance; // User? _user; // UserProfile? _userData; // final Connectivity _connectivity = Connectivity(); // List<UserProfile> updateQueue = []; // @override // void initState() { // super.initState(); // _loadUserData(); // _checkConnectivity(); // } // void addToUpdateQueue(UserProfile request) { // updateQueue.add(request); // } // // Function to process pending update requests when internet is available // Future<void> processPendingUpdates() async { // final ConnectivityResult result = await Connectivity().checkConnectivity(); // if (result != ConnectivityResult.none) { // for (var request in updateQueue) { // // Update data in Firestore // await updateProfileInFirestore(request); // // Update data in local database (Floor) // await updateProfileInLocalDb(request); // } // // Clear the update queue // updateQueue.clear(); // } // } // // Function to update profile data in Firestore // Future<void> updateProfileInFirestore(UserProfile request) async { // try { // // Update user data in Firestore // await _firestore // .collection('users') // .doc(_auth.currentUser!.email) // .update({ // 'name': request.name, // 'email': request.email, // 'username': request.username, // 'phone': request.phone, // }); // Get.snackbar("Updated", "'Profile updated successfully in FireStore'", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.green.withOpacity(0.6)); // // Success, you can handle success here // } catch (error) { // debugPrint('Error updating profile in Firestore: $error'); // // Handle error, e.g., add the request back to the queue // addToUpdateQueue(request); // } // } // // Function to update profile data in local database (Floor) // Future<void> updateProfileInLocalDb(UserProfile request) async { // try { // final userDao = await LocalDbService.usersDao; // // Update or insert the user data into the local database // await userDao.insertUserProfile(UserProfile( // email: request.email, // name: request.name, // username: request.username, // phone: request.phone, // )); // Get.snackbar( // "Updated", "'Profile updated successfully in Floor Local db'", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.green.withOpacity(0.6)); // // Success, you can handle success here // } catch (error) { // debugPrint('Error updating profile in local database: $error'); // // Handle error, e.g., add the request back to the queue // addToUpdateQueue(request); // } // } // // Data structure for profile update request // Future<void> _checkConnectivity() async { // final ConnectivityResult result = await _connectivity.checkConnectivity(); // if (result == ConnectivityResult.none) { // // No internet connection, load data from local database // _loadDataFromLocalDb(); // debugPrint("Data Froom Local db"); // } else { // // Internet connection is available, load data from Firebase // _loadUserData(); // debugPrint("Data Froom Firestore db"); // } // } // Future<void> _loadDataFromLocalDb() async { // try { // // Use your Floor database to retrieve user data from the local database // final localUserData = await (await LocalDbService.usersDao) // .findUserProfileById(_user!.email.toString()); // if (localUserData != null) { // setState(() { // nameController.text = _userData!.name; // emailController.text = _userData!.email; // usernameController.text = _userData!.username; // phoneController.text = _userData!.phone; // }); // } else { // debugPrint('User data not found in the local database.'); // } // } catch (error) { // debugPrint('Error loading data from local database: $error'); // } // } // Future<void> _loadUserData() async { // try { // _user = _auth.currentUser; // if (_user != null) { // final userDoc = await _firestore // .collection('users') // .doc(_auth.currentUser!.email) // .get(); // final userData = userDoc.data(); // if (userData != null) { // setState(() { // _userData = UserProfile.fromFirestore(userData); // nameController.text = _userData!.name; // emailController.text = _userData!.email; // usernameController.text = _userData!.username; // phoneController.text = _userData!.phone; // }); // } else { // debugPrint('User data is null.'); // } // } // } catch (error) { // debugPrint('Error loading data from Firebase: $error'); // } // } // // Future<void> _loadUserData() async { // // _user = _auth.currentUser; // // if (_user != null) { // // final userDoc = await _firestore // // .collection('users') // // .doc(_auth.currentUser!.email) // // .get(); // // final userData = userDoc.data(); // // if (userData != null) { // // setState(() { // // _userData = UserModel.fromFirestore(userData); // // nameController.text = _userData!.name; // // emailController.text = _userData!.email; // // usernameController.text = _userData!.username; // // phoneController.text = _userData!.phone; // // }); // // } else { // // // Handle the case where user data is null, e.g., show an error message // // print('User data is null.'); // // } // // } // // } // void _changepasswordDialog( // {required bool obscureOldpPass, // required bool obscureNewPass, // required bool isLoadingChngePassword}) { // showDialog( // context: context, // builder: (BuildContext context) { // final TextEditingController oldPasswordController = // TextEditingController(); // final TextEditingController newPasswordController = // TextEditingController(); // return AlertDialog( // title: const Text('Change Password'), // content: Form( // key: _formKey, // child: SingleChildScrollView( // child: Column( // children: [ // TextFormField( // controller: oldPasswordController, // obscureText: obscureOldpPass, // decoration: InputDecoration( // labelText: 'Old Password', // suffixIcon: IconButton( // icon: Icon( // obscureOldpPass // ? Icons.visibility // : Icons.visibility_off, // color: Colors.white, // ), // onPressed: () { // setState(() { // obscureOldpPass = !obscureOldpPass; // }); // }, // ), // ), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter old password'; // } // return null; // }, // ), // TextFormField( // controller: newPasswordController, // obscureText: obscureNewPass, // decoration: InputDecoration( // labelText: 'New Password', // suffixIcon: IconButton( // icon: Icon( // obscureNewPass // ? Icons.visibility // : Icons.visibility_off, // color: Colors.white, // ), // onPressed: () { // setState(() { // obscureNewPass = !obscureNewPass; // }); // }, // ), // ), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter new password'; // } else if (value.length < 6) { // return 'Password must be at least 6 characters'; // } // return null; // }, // ), // ], // ), // ), // ), // actions: [ // TextButton( // onPressed: () { // Navigator.of(context).pop(); // }, // child: const Text('Cancel'), // ), // ElevatedButton( // onPressed: isLoadingChngePassword // ? null // : () async { // setState(() { // isLoadingChngePassword = true; // }); // debugPrint("object"); // String oldPassword = oldPasswordController.text; // String newPassword = newPasswordController.text; // if (oldPassword.isNotEmpty && newPassword.isNotEmpty) { // // Verify the old password before changing // try { // AuthCredential credential = // EmailAuthProvider.credential( // email: _auth.currentUser!.email!, // password: oldPassword, // ); // await _auth.currentUser! // .reauthenticateWithCredential(credential); // // Old password is correct, change the password // await changePassword(newPassword); // Navigator.of(context).pop(); // setState(() { // isLoadingChngePassword = false; // }); // } catch (e) { // // Handle the case where the old password is incorrect // debugPrint('Error reauthenticating: $e'); // Get.snackbar("Unsuccessfull", // "Your password has Not updated Unsuccessfull.", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.red.withOpacity(0.7)); // setState(() { // isLoadingChngePassword = false; // }); // } // } // }, // child: isLoadingChngePassword // ? const CircularProgressIndicator( // color: Colors.black, // ) // : const Text('Save'), // ), // ], // ); // }, // ); // } // Future<void> changePassword(String newPassword) async { // try { // User? user = FirebaseAuth.instance.currentUser; // await user?.updatePassword(newPassword); // Get.snackbar( // "Password Changed", "Your password has been updated successfully.", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.greenAccent.withOpacity(0.7)); // } catch (error) { // Get.snackbar("Error", error.toString(), // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.redAccent.withOpacity(0.7)); // } // } // void _showEditProfileDialog() { // showDialog( // context: context, // builder: (BuildContext context) { // return AlertDialog( // title: const Text('Edit Profile'), // content: Form( // key: _formKey, // child: SingleChildScrollView( // child: Column( // children: [ // TextFormField( // controller: nameController, // decoration: const InputDecoration(labelText: 'Name'), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter your name'; // } // return null; // }, // ), // TextFormField( // controller: emailController, // decoration: const InputDecoration( // labelText: 'Email', // // Set the enabled property to false to make it read-only // enabled: false, // ), // ), // TextFormField( // controller: usernameController, // decoration: const InputDecoration(labelText: 'Username'), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter your username'; // } // return null; // }, // ), // TextFormField( // controller: phoneController, // decoration: // const InputDecoration(labelText: 'Phone Number'), // validator: (value) { // if (value == null || value.isEmpty) { // return 'Please enter your phone number'; // } // return null; // }, // ), // ], // ), // ), // ), // actions: [ // TextButton( // onPressed: () { // Navigator.of(context).pop(); // }, // child: const Text('Cancel'), // ), // ElevatedButton( // onPressed: () { // if (_formKey.currentState!.validate()) { // // Update user data in Firestore // _updateUserData( // name: nameController.text, // email: emailController.text, // username: usernameController.text, // phone: phoneController.text, // ); // Navigator.of(context).pop(); // } // }, // child: const Text('Save'), // ), // ], // ); // }, // ); // } // Future<void> _updateUserData({ // required String name, // required String email, // required String username, // required String phone, // }) async { // try { // // Check if the new email is already registered // // Update user data in Firestore // await _firestore // .collection('users') // .doc(_auth.currentUser!.email) // .update({ // 'name': name, // 'username': username, // 'phone': phone, // }); // // await (await LocalDbService.usersDao).updateUserProfile(UserProfile( // // name: name, email: email, username: username, phone: phone)); // final currentEmail = _auth.currentUser!.email; // await (await LocalDbService.usersDao).updateUserProfile(UserProfile( // name: name, email: currentEmail!, username: username, phone: phone)); // // Update user email in Firebase Authentication // await _user!.updateEmail(email); // // Reload user data // _loadUserData(); // // Show a success message // Get.snackbar("Updated", "'Profile updated successfully'", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.green.withOpacity(0.6)); // } catch (error) { // // Handle error, e.g., show an error message // Get.snackbar("Error", 'Error updating profile: $error'); // debugPrint(error.toString()); // } // } // @override // Widget build(BuildContext context) { // bool obscureOldPass = false; // bool obscureNewPass = false; // bool isLoadingChngePassword = false; // return Scaffold( // resizeToAvoidBottomInset: false, // appBar: AppBar( // title: const Text( // 'Profile', // style: TextStyle(fontSize: 30), // ), // centerTitle: true, // actions: [ // IconButton( // onPressed: () { // _auth.signOut().then((value) { // Get.offNamed(login); // Get.snackbar("LOGOUT", "successfully", // snackPosition: SnackPosition.BOTTOM, // backgroundColor: Colors.greenAccent.withOpacity(0.7)); // }).onError((error, stackTrace) { // ToastMessage.toastMessage(error.toString()); // }); // }, // icon: const Icon(Icons.logout)) // ], // ), // body: _userData != null // ? Padding( // padding: const EdgeInsets.all(16), // child: Column( // crossAxisAlignment: CrossAxisAlignment.center, // children: [ // const Center( // child: CircleAvatar( // backgroundImage: AssetImage("assets/images/logo.png"), // radius: 60, // ), // ), // const SizedBox( // height: 30, // ), // Card( // child: ListTile( // leading: const Text( // "Name", // style: TextStyle( // fontSize: 18.0, // ), // ), // title: Text( // _userData! // .name, // Access the user's name from UserModel // style: const TextStyle( // fontSize: 18.0, // ), // ), // ), // ), // Card( // child: ListTile( // leading: const Text( // "Email:", // style: TextStyle( // fontSize: 18.0, // ), // ), // title: Text( // _userData! // .email, // Access the user's email from UserModel // style: const TextStyle( // fontSize: 18.0, // ), // ), // ), // ), // Card( // child: ListTile( // leading: const Text( // "User Name:", // style: TextStyle( // fontSize: 18.0, // ), // ), // title: Text( // _userData! // .username, // Access the user's username from UserModel // style: const TextStyle( // fontSize: 18.0, // ), // ), // ), // ), // Card( // child: ListTile( // leading: const Text( // "Phone No:", // style: TextStyle( // fontSize: 18.0, // ), // ), // title: Text( // _userData! // .phone, // Access the user's phone from UserModel // style: const TextStyle( // fontSize: 18.0, // ), // ), // ), // ), // const SizedBox( // height: 20, // ), // InkWell( // onTap: () { // _showEditProfileDialog(); // }, // child: Container( // height: 50, // width: double.infinity, // decoration: BoxDecoration( // color: const Color.fromARGB(255, 236, 225, 238), // borderRadius: BorderRadius.circular(10)), // child: const Center( // child: Text( // "UPDATE", // style: TextStyle( // fontSize: 18, fontWeight: FontWeight.bold), // ), // ), // ), // ), // SizedBox( // height: Get.height * .025, // ), // TextButton( // onPressed: () => _changepasswordDialog( // isLoadingChngePassword: isLoadingChngePassword, // obscureNewPass: obscureNewPass, // obscureOldpPass: obscureOldPass), // child: const Text("Chnage Password")), // const SizedBox( // height: 20, // ), // // InkWell( // // onTap: () { // // _auth.signOut().then((value) { // // Get.offNamed(login); // // Get.snackbar("LOGOUT", "successfully", // // snackPosition: SnackPosition.BOTTOM, // // backgroundColor: // // Colors.greenAccent.withOpacity(0.7)); // // }).onError((error, stackTrace) { // // ToastMessage.toastMessage(error.toString()); // // }); // // }, // // child: Container( // // height: 30, // // width: 100, // // decoration: BoxDecoration( // // color: const Color.fromARGB(255, 236, 225, 238), // // borderRadius: BorderRadius.circular(10)), // // child: const Center( // // child: Text( // // "LOGOUT", // // style: TextStyle( // // fontSize: 16, fontWeight: FontWeight.bold), // // ), // // ), // // ), // // ), // ], // ), // ) // : const Center( // child: CircularProgressIndicator(), // ), // ); // } // } import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/controller/profile_screen_controller.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../utils/toast_message.dart'; class ProfileScreen extends StatelessWidget { @override Widget build(BuildContext context) { ProfileController controller = Get.put(ProfileController()); final FirebaseAuth _auth = FirebaseAuth.instance; return Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar( title: const Text( 'Profile', style: TextStyle(fontSize: 30), ), centerTitle: true, actions: [ IconButton( onPressed: () { _auth.signOut().then((value) { Get.offAllNamed(login); Get.snackbar("LOGOUT", "Successfully", snackPosition: SnackPosition.BOTTOM, backgroundColor: Colors.greenAccent.withOpacity(0.7)); }).onError((error, stackTrace) { ToastMessage.toastMessage(error.toString()); }); }, icon: const Icon(Icons.logout), ) ], ), body: Obx( () => controller.userData.value != null ? Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ const Center( child: CircleAvatar( backgroundImage: AssetImage("assets/images/logo.png"), radius: 60, ), ), const SizedBox(height: 30), Card( child: ListTile( leading: const Text( "Name", style: TextStyle( fontSize: 18.0, ), ), title: Obx( () => Text( controller.userData.value!.name, style: const TextStyle( fontSize: 18.0, ), ), ), ), ), Card( child: ListTile( leading: const Text( "Email:", style: TextStyle( fontSize: 18.0, ), ), title: Obx( () => Text( controller.userData.value!.email, style: const TextStyle( fontSize: 18.0, ), ), ), ), ), Card( child: ListTile( leading: const Text( "User Name:", style: TextStyle( fontSize: 18.0, ), ), title: Obx( () => Text( controller.userData.value!.username, style: const TextStyle( fontSize: 18.0, ), ), )), ), Card( child: ListTile( leading: const Text( "Phone No:", style: TextStyle( fontSize: 18.0, ), ), title: Obx( () => Text( controller.userData.value!.phone, style: const TextStyle( fontSize: 18.0, ), ), )), ), const SizedBox(height: 20), InkWell( onTap: () { controller.showEditProfileDialog(context); }, child: Container( height: 50, width: double.infinity, decoration: BoxDecoration( color: const Color.fromARGB(255, 236, 225, 238), borderRadius: BorderRadius.circular(10), ), child: const Center( child: Text( "UPDATE", style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), ), ), SizedBox(height: Get.height * 0.025), TextButton( onPressed: () => controller.changepasswordDialog(context), child: const Text("Change Password"), ), const SizedBox(height: 20), ], ), ) : const Center( child: CircularProgressIndicator(), ), )); } }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/favorite/fav_screen.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/controller/favorite_screen_controller.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:get/get.dart'; // // Replace with your controller class FavScreen extends StatelessWidget { FavScreen({super.key}); FavoriteMoviesController controller = Get.put(FavoriteMoviesController()); final user = FirebaseAuth.instance.currentUser; @override Widget build(BuildContext context) { controller.fetchFavoriteMovies(user!.uid); // controller.fetchFavoriteMovies(); return Scaffold( appBar: AppBar( title: const Text( 'Favorites', style: TextStyle(fontSize: 30), ), centerTitle: true, ), body: Obx(() { final favoriteMovies = controller.favoriteMovies; if (controller.isLoading.value) { return const Center( child: CircularProgressIndicator(), ); } else if (favoriteMovies.isEmpty) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.favorite, color: Colors.red, size: 80, ), SizedBox( height: Get.height * .05, ), const Center( child: Text( "NO FAVORITE ITEM AVAILBLE", style: TextStyle(fontSize: 24, fontWeight: FontWeight.w700), ), ) ], ), ); } else { return ListView.builder( itemCount: favoriteMovies.length, itemBuilder: (context, index) { final movie = favoriteMovies[index]; print(favoriteMovies.length); return ListTile( leading: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const CircularProgressIndicator(), errorWidget: (context, url, error) => const Icon(Icons.error), fit: BoxFit.fill, width: 80, ), title: Text(movie.title), subtitle: RatingBar.builder( initialRating: movie.voteAverage / 2, // Divide by 2 to convert to a 5-star rating minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemSize: 15, unratedColor: Colors.grey, itemBuilder: (context, _) => const Icon(Icons.star, color: Color.fromRGBO(242, 163, 58, 1)), onRatingUpdate: (newRating) { // Handle rating updates if needed }, ), trailing: // final isFavorite = controller.movies[index].isFavorite; IconButton( icon: const Icon( Icons.favorite, color: Colors.red, ), onPressed: () { controller.toggleFavorite( movie: movie, userId: user!.uid); }, )); }, ); } })); } } // StreamBuilder<List<MovieByIdModel>>( // stream: controller.fetchFavoriteMovies(), // builder: (context, snapshot) { // if (snapshot.hasError) { // return const Text('Error'); // } else if (snapshot.hasData) { // return ListView.builder( // itemCount: snapshot.data!.length, // itemBuilder: (BuildContext context, int index) { // final movie = snapshot.data![index]; // return ListTile( // leading: CachedNetworkImage( // imageUrl: // 'https://image.tmdb.org/t/p/w200${movie.posterPath}', // placeholder: (context, url) => // const CircularProgressIndicator(), // errorWidget: (context, url, error) => // const Icon(Icons.error), // fit: BoxFit.fill, // width: 80, // ), // title: Text(movie.title), // subtitle: RatingBar.builder( // initialRating: movie.voteAverage / // 2, // Divide by 2 to convert to a 5-star rating // minRating: 1, // direction: Axis.horizontal, // allowHalfRating: true, // itemCount: 5, // itemSize: 15, // unratedColor: Colors.grey, // itemBuilder: (context, _) => const Icon(Icons.star, // color: Color.fromRGBO(242, 163, 58, 1)), // onRatingUpdate: (newRating) { // // Handle rating updates if needed // }, // ), // trailing: IconButton( // icon: const Icon(Icons.delete), // onPressed: () { // // Remove the movie from favorites // controller.removeFromFavorites(movie.id); // }, // ), // ); // }, // ); // } else { // return const Center( // child: CircularProgressIndicator(), // ); // } // }, // ) // class FavScreen extends GetView<FavorieScreenController> { // @override // Widget build(BuildContext context) { // return Scaffold( // appBar: AppBar( // title: Text('Favorites'), // ), // body: Obx(() { // if (controller.favoriteMovies.isEmpty) { // return const Center( // child: Text('You have no favorite movies yet.'), // ); // } else { // return NotificationListener<ScrollNotification>( // onNotification: (ScrollNotification scrollInfo) { // if (scrollInfo is ScrollEndNotification && // scrollInfo.metrics.pixels == // scrollInfo.metrics.maxScrollExtent) { // // User reached the end of the list, load more data here // controller.fetchFavoriteMovies(); // } // return false; // }, // child: ListView.builder( // itemCount: controller.favoriteMovies.length, // itemBuilder: (BuildContext context, int index) { // final movie = controller.favoriteMovies[index]; // return ListTile( // leading: CachedNetworkImage( // imageUrl: // 'https://image.tmdb.org/t/p/w200${movie.posterPath}', // placeholder: (context, url) => // const CircularProgressIndicator(), // errorWidget: (context, url, error) => // const Icon(Icons.error), // fit: BoxFit.fill, // width: 80, // ), // title: Text(movie.title), // subtitle: RatingBar.builder( // initialRating: movie.voteAverage / // 2, // Divide by 2 to convert to a 5-star rating // minRating: 1, // direction: Axis.horizontal, // allowHalfRating: true, // itemCount: 5, // itemSize: 15, // unratedColor: Colors.white.withOpacity(0.8), // itemBuilder: (context, _) => const Icon(Icons.star, // color: Color.fromRGBO(242, 163, 58, 1)), // onRatingUpdate: (newRating) { // // Handle rating updates if needed // }, // ), // trailing: IconButton( // icon: Icon(Icons.delete), // onPressed: () { // // Remove the movie from favorites // controller.removeFromFavorites(movie.id); // }, // ), // ); // }, // ), // ); // } // }), // ); // } // }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/auth/sms_code_screen.dart
// import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:film_fusion/constants/routes.dart'; // import 'package:film_fusion/db/entity/users.dart'; // import 'package:film_fusion/db/services/localdb_services.dart'; // import 'package:film_fusion/model/user_model.dart'; // import 'package:film_fusion/services/firebase_service.dart'; // import 'package:flutter/material.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'package:flutter_otp_text_field/flutter_otp_text_field.dart'; // import 'package:get/get.dart'; // import 'package:get/get_core/src/get_main.dart'; // class SmsCodeScreen extends StatefulWidget { // SmsCodeScreen({ // super.key, // required this.verificationId, // required this.name, // required this.phone, // required this.username, // required this.email, // required this.password, // }); // final String verificationId; // final String name; // final String phone; // final String username; // final String email; // final String password; // @override // _SmsCodeScreenState createState() => _SmsCodeScreenState(); // } // class _SmsCodeScreenState extends State<SmsCodeScreen> { // final FirebaseAuth _auth = FirebaseAuth.instance; // final FirebaseFirestore _firestore = FirebaseFirestore.instance; // final TextEditingController _smsCodeController = TextEditingController(); // bool isLoading = false; // Future<void> _verifySmsCode() async { // AuthCredential credential = PhoneAuthProvider.credential( // verificationId: widget.verificationId, // smsCode: _smsCodeController.text, // ); // setState(() { // isLoading = true; // }); // try { // // Verify the SMS code // await _auth.signInWithCredential(credential); // // If verification is successful, register the user // await (await LocalDbService.usersDao).insertUserProfile(UserProfile( // name: widget.name, // username: widget.username, // email: widget.email, // phone: widget.phone)); // await _firestore.collection('users').doc(widget.email).set({ // 'name': widget.name, // 'email': widget.email, // 'phone': widget.phone, // 'username': widget.username, // }); // await _auth.createUserWithEmailAndPassword( // email: widget.email, password: widget.password); // // Navigate to the login screen // Get.offAllNamed(login); // setState(() { // isLoading = true; // }); // } catch (e) { // // Handle verification errors // // Display an error message to the user // final snackBar = SnackBar(content: Text('Verification failed: $e')); // print(e.toString()); // setState(() { // isLoading = false; // }); // ScaffoldMessenger.of(context).showSnackBar(snackBar); // } // } // @override // Widget build(BuildContext context) { // return Scaffold( // resizeToAvoidBottomInset: false, // body: Padding( // padding: EdgeInsets.symmetric(horizontal: Get.height * .04), // child: Column( // // mainAxisAlignment: MainAxisAlignment.center, // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // SizedBox( // height: Get.height * .15, // ), // const Text( // "Verification Code", // style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), // ), // const Text( // "We Texted You a code \nPlease enter it below", // style: TextStyle( // fontSize: 16, // ), // ), // SizedBox( // height: Get.height * .2, // ), // OtpTextField( // numberOfFields: 6, // borderColor: Color(0xFF512DA8), // //set to true to show as box or false to show as dash // showFieldAsBox: true, // //runs when a code is typed in // onCodeChanged: (String code) { // //handle validation or checks here // _smsCodeController.text = code; // print(_smsCodeController.text); // }, // //runs when every textfield is filled // onSubmit: (String verificationCode) { // _smsCodeController.text = verificationCode; // print(_smsCodeController.text); // showDialog( // context: context, // builder: (context) { // return AlertDialog( // title: Text("Verification Code"), // content: Text('Code entered is $verificationCode'), // ); // }); // }, // end onSubmit // ), // SizedBox( // height: Get.height * .1, // ), // Center( // child: InkWell( // onTap: () => _verifySmsCode(), // child: Container( // height: 50, // width: double.infinity, // decoration: BoxDecoration( // borderRadius: BorderRadius.circular(10), // color: Colors.black), // child: Center( // child: isLoading // ? const CircularProgressIndicator( // color: Colors.white, // ) // : const Text( // "Verify Code", // style: TextStyle( // color: Colors.white, // fontSize: 16, // fontWeight: FontWeight.w400), // )), // ), // ), // ), // ], // ), // ), // ); // } // } import 'package:film_fusion/controller/sms_code_controller.dart'; import 'package:flutter/material.dart'; import 'package:flutter_otp_text_field/flutter_otp_text_field.dart'; import 'package:get/get.dart'; class SmsCodeScreen extends StatelessWidget { SmsCodeScreen({ Key? key, required this.verificationId, required this.name, required this.phone, required this.username, required this.email, required this.password, }) : super(key: key); final String verificationId; final String name; final String phone; final String username; final String email; final String password; @override Widget build(BuildContext context) { SmsCodeController controller = Get.put(SmsCodeController()); return Scaffold( resizeToAvoidBottomInset: false, body: Padding( padding: EdgeInsets.symmetric(horizontal: Get.height * .04), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: Get.height * .15, ), const Text( "Verification Code", style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), ), const Text( "We Texted You a code \nPlease enter it below", style: TextStyle( fontSize: 16, ), ), SizedBox( height: Get.height * .2, ), OtpTextField( numberOfFields: 6, borderColor: const Color(0xFF512DA8), showFieldAsBox: true, onCodeChanged: (String code) { controller.smsCodeController.text = code; }, onSubmit: (String verificationCode) { controller.smsCodeController.text = verificationCode; }, ), SizedBox( height: Get.height * .1, ), Center( child: InkWell( onTap: () => controller.verifySmsCode( verificationId: verificationId, name: name, phone: phone, username: username, email: email, password: password, ), child: Container( height: 50, width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.black, ), child: Center( child: Obx( () => controller.isLoading.value ? const CircularProgressIndicator( color: Colors.white, ) : const Text( "Verify Code", style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w400, ), ), ), ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/auth/login_sms_code_screen.dart
// import 'package:film_fusion/constants/routes.dart'; // import 'package:flutter/material.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'package:get/get.dart'; // class SMSCodeScreen extends StatelessWidget { // final String verificationId; // final TextEditingController _smsCodeController = TextEditingController(); // SMSCodeScreen(this.verificationId); // Future<void> _signInWithPhoneNumber(BuildContext context) async { // final FirebaseAuth _auth = FirebaseAuth.instance; // final AuthCredential credential = PhoneAuthProvider.credential( // verificationId: verificationId, // smsCode: _smsCodeController.text, // ); // try { // await _auth.signInWithCredential(credential); // // Authentication successful, navigate to next screen. // // Example: Navigator.push(context, MaterialPageRoute(builder: (context) => HomeScreen())); // Get.offNamed(mainScreen); // } catch (e) { // print('Sign in failed: $e'); // // Handle sign-in failure here. // } // } // @override // Widget build(BuildContext context) { // return Scaffold( // appBar: AppBar( // title: Text('Enter SMS Code'), // ), // body: Padding( // padding: const EdgeInsets.all(16.0), // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // TextField( // controller: _smsCodeController, // keyboardType: TextInputType.number, // decoration: InputDecoration(labelText: 'SMS Code'), // ), // SizedBox(height: 16.0), // ElevatedButton( // onPressed: () => _signInWithPhoneNumber(context), // child: Text('Verify'), // ), // ], // ), // ), // ); // } // }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/auth/login_with_phone.dart
// import 'package:flutter/material.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'login_sms_code_screen.dart'; // class PhoneNumberScreen extends StatelessWidget { // final TextEditingController _phoneNumberController = TextEditingController(); // Future<void> _verifyPhoneNumber(BuildContext context) async { // final FirebaseAuth _auth = FirebaseAuth.instance; // final String phoneNumber = '+92${_phoneNumberController.text}'; // await _auth.verifyPhoneNumber( // phoneNumber: phoneNumber, // verificationCompleted: (PhoneAuthCredential credential) {}, // verificationFailed: (FirebaseAuthException e) { // print('Verification failed: $e'); // }, // codeSent: (String verificationId, int? resendToken) { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => SMSCodeScreen(verificationId), // ), // ); // }, // codeAutoRetrievalTimeout: (String verificationId) {}, // ); // } // @override // Widget build(BuildContext context) { // return Scaffold( // appBar: AppBar( // title: Text('Phone Number Authentication'), // ), // body: Padding( // padding: const EdgeInsets.all(16.0), // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // TextField( // controller: _phoneNumberController, // keyboardType: TextInputType.phone, // decoration: InputDecoration(labelText: 'Phone Number'), // ), // SizedBox(height: 16.0), // ElevatedButton( // onPressed: () => _verifyPhoneNumber(context), // child: Text('Send OTP'), // ), // ], // ), // ), // ); // } // }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/auth/sign_up_screen.dart
// import 'package:film_fusion/constants/routes.dart'; // import 'package:film_fusion/screens/auth/sms_code_screen.dart'; // import 'package:firebase_auth/firebase_auth.dart'; // import 'package:flutter/cupertino.dart'; // import 'package:flutter/material.dart'; // import 'package:get/get.dart'; // import '../../services/firebase_service.dart'; // import '../../utils/toast_message.dart'; // class SignUpScreen extends StatefulWidget { // const SignUpScreen({super.key}); // @override // _SignUpScreenState createState() => _SignUpScreenState(); // } // class _SignUpScreenState extends State<SignUpScreen> { // final FirebaseService _firebaseService = FirebaseService(); // final _formKey = GlobalKey<FormState>(); // final _nameController = TextEditingController(); // // final _fatherNameController = TextEditingController(); // // final _cnicController = TextEditingController(); // final _phoneController = TextEditingController(); // final _emailController = TextEditingController(); // final _usernameController = TextEditingController(); // final _passwordController = TextEditingController(); // final _confirmPasswordController = TextEditingController(); // bool isLoading = false; // bool _obscurePass = true; // bool _obscureConf = true; // String phoneNumber = ''; // String? _validateName(String? value) { // if (value == null || value.isEmpty) { // return 'Name is required'; // } // return null; // } // // String? _validateFatherName(String? value) { // // if (value == null || value.isEmpty) { // // return "Father's Name is required"; // // } // // return null; // // } // // String? _validateCNIC(String? value) { // // if (value == null || value.isEmpty) { // // return 'CNIC is required'; // // } else if (value.length != 13) { // // return 'CNIC should be 13 digits'; // // } // // return null; // // } // String? _validatePhone(String? value) { // if (value == null || value.isEmpty) { // return 'Phone number is required'; // } else if (value.length != 11) { // return 'Phone number should be 10 digits'; // } // return null; // } // String? _validateEmail(String? value) { // if (value == null || value.isEmpty) { // return 'Email is required'; // } else if (!value.contains('@')) { // return 'Invalid email format'; // } // return null; // } // String? _validateUsername(String? value) { // if (value == null || value.isEmpty) { // return 'Username is required'; // } // return null; // } // String? _validatePassword(String? value) { // if (value == null || value.isEmpty) { // return 'Password is required'; // } // return null; // } // String? _validatePhoneNumber(String? value) { // if (value == null || value.isEmpty) { // return 'Please enter a valid 10-digit phone number'; // } // return null; // } // String? _validateConfirmPassword(String? value) { // if (value == null || value.isEmpty) { // return 'Confirm Password is required'; // } else if (value != _passwordController.text) { // return 'Passwords do not match'; // } // return null; // } // TextEditingController _smsCodeController = TextEditingController(); // String _verificationId = ''; // final FirebaseAuth _auth = FirebaseAuth.instance; // void _signUp() async { // if (_formKey.currentState!.validate()) { // try { // setState(() { // isLoading = true; // Set loading to true // }); // await _auth.verifyPhoneNumber( // phoneNumber: "+92${_phoneController.text}", // verificationCompleted: (AuthCredential credential) { // // Auto verification if on the same device // _signInWithCredential(credential); // }, // verificationFailed: (FirebaseAuthException e) { // // Handle verification failure // print("Verification Failed: ${e.message}"); // setState(() { // isLoading = false; // }); // }, // codeSent: (String verificationId, int? resendToken) { // // Save verification ID for later use // _verificationId = verificationId; // // Navigate to SMS code verification screen // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => SmsCodeScreen( // verificationId: verificationId, // name: _nameController.text, // phone: "+92${_phoneController.text}", // username: _usernameController.text, // email: _emailController.text, // password: _passwordController.text, // ), // ), // ).then((_) { // setState(() { // isLoading = // false; // Set isLoading back to false when the SMS code screen is dismissed // }); // }).catchError((error) { // setState(() { // isLoading = false; // Set isLoading back to false on error // }); // print("Error navigating to SMS code screen: $error"); // }); // // .then((value) => setState(() { // // isLoading = false; // Set loading back to false // // })) // // .onError((error, stackTrace) => setState(() { // // isLoading = false; // Set loading back to false // // })); // }, // codeAutoRetrievalTimeout: (String verificationId) { // // Timeout handling // }, // ); // } catch (e) { // setState(() { // isLoading = false; // Set loading back to false in case of error // }); // print("Error sending SMS code: $e"); // } // } // } // Future<void> _signInWithCredential(AuthCredential credential) async { // try { // // Sign in with the provided credential // await _auth.signInWithCredential(credential); // // If sign-in is successful, register the user // await _firebaseService.signUpUser( // email: _emailController.text, // password: _passwordController.text, // name: _nameController.text, // phone: "+92${_phoneController.text}", // username: _usernameController.text, // ); // // Navigate to the login screen // Get.offNamed(login); // } catch (e) { // // Handle sign-in errors // print("Error signing in: $e"); // } // } // @override // Widget build(BuildContext context) { // return SafeArea( // child: Scaffold( // resizeToAvoidBottomInset: false, // body: Stack( // children: [ // Container( // height: double.infinity, // width: double.infinity, // decoration: const BoxDecoration( // gradient: LinearGradient(colors: [ // Color.fromRGBO(38, 116, 9, 1), // Color.fromRGBO(0, 0, 0, 1), // ], begin: Alignment.topCenter, end: Alignment.bottomCenter), // ), // child: Form( // key: _formKey, // child: Padding( // padding: EdgeInsets.symmetric( // horizontal: Get.width * .16, // ), // child: Column(mainAxisSize: MainAxisSize.min, children: [ // Image.asset( // "assets/images/logo.png", // height: Get.height * .2, // ), // const Text( // "Create Your Account", // style: TextStyle( // color: Colors.white, // fontSize: 20, // fontWeight: FontWeight.w700), // ), // SizedBox( // height: Get.height * .015, // ), // TextFormField( // controller: _nameController, // validator: _validateName, // style: const TextStyle(color: Colors.white), // decoration: const InputDecoration( // hintText: 'Name', // hintStyle: TextStyle(color: Colors.white), // prefixIcon: Icon( // CupertinoIcons.person_alt, // color: Colors.white, // ), // alignLabelWithHint: true, // focusedBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors // .white, // Color of the bottom line when focused // width: // 2.0, // Thickness of the bottom line when focused // ), // ), // enabledBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors.white, // width: // 2 // Color of the bottom line when unfocused // ), // ), // ), // ), // SizedBox( // height: Get.height * .015, // ), // TextFormField( // controller: _usernameController, // validator: _validateUsername, // style: const TextStyle(color: Colors.white), // decoration: const InputDecoration( // hintText: 'Username', // hintStyle: TextStyle(color: Colors.white), // prefixIcon: Icon( // Icons.person, // color: Colors.white, // ), // alignLabelWithHint: true, // focusedBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors // .white, // Color of the bottom line when focused // width: // 2.0, // Thickness of the bottom line when focused // ), // ), // enabledBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors.white, // width: // 2 // Color of the bottom line when unfocused // ), // ), // ), // ), // SizedBox( // height: Get.height * .015, // ), // TextFormField( // controller: _emailController, // validator: _validateEmail, // style: const TextStyle(color: Colors.white), // decoration: const InputDecoration( // hintText: 'E-Mail', // hintStyle: TextStyle(color: Colors.white), // prefixIcon: Icon( // Icons.email, // color: Colors.white, // ), // alignLabelWithHint: true, // focusedBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors // .white, // Color of the bottom line when focused // width: // 2.0, // Thickness of the bottom line when focused // ), // ), // enabledBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors.white, // width: // 2 // Color of the bottom line when unfocused // ), // ), // ), // ), // SizedBox( // height: Get.height * .015, // ), // TextFormField( // controller: _phoneController, // validator: _validatePhone, // onChanged: _validatePhoneNumber, // maxLength: 11, // style: const TextStyle(color: Colors.white), // decoration: const InputDecoration( // hintText: 'Phone No', // Use a standard hint text // hintStyle: TextStyle(color: Colors.white), // prefixIcon: Icon( // Icons.phone, // color: Colors.white, // ), // alignLabelWithHint: true, // focusedBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors // .white, // Color of the bottom line when focused // width: // 2.0, // Thickness of the bottom line when focused // ), // ), // enabledBorder: UnderlineInputBorder( // borderSide: BorderSide( // color: Colors.white, // width: 2, // Color of the bottom line when unfocused // ), // ), // counterText: '', // ), // ), // SizedBox( // height: Get.height * .015, // ), // TextFormField( // controller: _passwordController, // validator: _validatePassword, // obscureText: _obscurePass, // style: const TextStyle(color: Colors.white), // decoration: InputDecoration( // hintText: 'Password', // hintStyle: const TextStyle(color: Colors.white), // prefixIcon: const Icon( // Icons.lock, // color: Colors.white, // ), // alignLabelWithHint: true, // focusedBorder: const UnderlineInputBorder( // borderSide: BorderSide( // color: Colors // .white, // Color of the bottom line when focused // width: // 2.0, // Thickness of the bottom line when focused // ), // ), // enabledBorder: const UnderlineInputBorder( // borderSide: BorderSide( // color: Colors.white, // width: // 2 // Color of the bottom line when unfocused // ), // ), // suffixIcon: IconButton( // icon: Icon( // _obscurePass // ? Icons.visibility // : Icons.visibility_off, // color: Colors.white, // ), // onPressed: () { // setState(() { // _obscurePass = !_obscurePass; // }); // }, // ), // ), // ), // SizedBox( // height: Get.height * .015, // ), // TextFormField( // controller: _confirmPasswordController, // validator: _validateConfirmPassword, // obscureText: _obscureConf, // For password fields // style: const TextStyle(color: Colors.white), // decoration: InputDecoration( // hintText: 'Confirm Password', // hintStyle: const TextStyle(color: Colors.white), // prefixIcon: const Icon( // Icons.lock, // color: Colors.white, // ), // alignLabelWithHint: true, // focusedBorder: const UnderlineInputBorder( // borderSide: BorderSide( // color: Colors // .white, // Color of the bottom line when focused // width: // 2.0, // Thickness of the bottom line when focused // ), // ), // enabledBorder: const UnderlineInputBorder( // borderSide: BorderSide( // color: Colors.white, // width: // 2 // Color of the bottom line when unfocused // ), // ), // suffixIcon: IconButton( // icon: Icon( // _obscureConf // ? Icons.visibility // : Icons.visibility_off, // color: Colors.white, // ), // onPressed: () { // setState(() { // _obscureConf = !_obscureConf; // }); // }, // ), // ), // ), // SizedBox( // height: Get.height * .03, // ), // GestureDetector( // onTap: () => _signUp(), // child: Container( // height: Get.height * .07, // width: double.infinity, // decoration: BoxDecoration( // borderRadius: BorderRadius.circular(10), // color: Colors.white, // ), // child: const Center( // child: Text( // "SIGN UP", // style: TextStyle(color: Colors.black, fontSize: 20), // ), // ), // ), // ), // SizedBox( // height: Get.height * .015, // ), // TextButton( // onPressed: () => Get.offNamed(login), // // onPressed: () => Get.toNamed(signup), // child: Text( // "LOGIN", // style: TextStyle( // color: Colors.white.withOpacity(0.8), // fontSize: 30), // )) // ]), // ), // ), // ), // if (isLoading) // Container( // color: Colors.black // .withOpacity(0.5), // Dark semi-transparent background // child: const Center( // child: CircularProgressIndicator( // color: Colors.white, // ), // ), // ), // ], // ), // ), // ); // } // } import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/controller/sign_up_controller.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class SignUpScreen extends StatelessWidget { const SignUpScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { SignUpController controller = Get.put(SignUpController()); return SafeArea( child: Scaffold( resizeToAvoidBottomInset: false, body: Stack( children: [ Container( height: double.infinity, width: double.infinity, decoration: const BoxDecoration( gradient: LinearGradient( colors: [ Color.fromRGBO(38, 116, 9, 1), Color.fromRGBO(0, 0, 0, 1), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: Form( key: controller.formKey, child: Padding( padding: EdgeInsets.symmetric( horizontal: Get.width * .16, ), child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, children: [ Image.asset( "assets/images/logo.png", height: Get.height * .2, ), const Text( "Create Your Account", style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.w700), ), SizedBox( height: Get.height * .015, ), TextFormField( controller: controller.nameController, validator: controller.validateName, style: const TextStyle(color: Colors.white), decoration: const InputDecoration( hintText: 'Name', hintStyle: TextStyle(color: Colors.white), prefixIcon: Icon( Icons.person, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2.0, ), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2, ), ), ), ), SizedBox( height: Get.height * .015, ), TextFormField( controller: controller.usernameController, validator: controller.validateUsername, style: const TextStyle(color: Colors.white), decoration: const InputDecoration( hintText: 'Username', hintStyle: TextStyle(color: Colors.white), prefixIcon: Icon( Icons.person, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2.0, ), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2, ), ), ), ), SizedBox( height: Get.height * .015, ), TextFormField( controller: controller.emailController, validator: controller.validateEmail, style: const TextStyle(color: Colors.white), decoration: const InputDecoration( hintText: 'E-Mail', hintStyle: TextStyle(color: Colors.white), prefixIcon: Icon( Icons.email, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2.0, ), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2, ), ), ), ), SizedBox( height: Get.height * .015, ), TextFormField( controller: controller.phoneController, validator: controller.validatePhone, onChanged: controller.validatePhoneNumber, maxLength: 11, style: const TextStyle(color: Colors.white), decoration: const InputDecoration( hintText: 'Phone No', hintStyle: TextStyle(color: Colors.white), prefixIcon: Icon( Icons.phone, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2.0, ), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2, ), ), counterText: '', ), ), SizedBox( height: Get.height * .015, ), Obx( () => TextFormField( controller: controller.passwordController, validator: controller.validatePassword, obscureText: controller.obscurePass.value, style: const TextStyle(color: Colors.white), decoration: InputDecoration( hintText: 'Password', hintStyle: const TextStyle(color: Colors.white), prefixIcon: const Icon( Icons.lock, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2.0, ), ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Colors.white, width: 2), ), suffixIcon: IconButton( icon: Icon( controller.obscurePass.value ? Icons.visibility : Icons.visibility_off, color: Colors.white, ), onPressed: () { controller.obscurePass.toggle(); }, ), ), ), ), SizedBox( height: Get.height * .015, ), Obx( () => TextFormField( controller: controller.confirmPasswordController, validator: controller.validateConfirmPassword, obscureText: controller.obscureConf.value, style: const TextStyle(color: Colors.white), decoration: InputDecoration( hintText: 'Confirm Password', hintStyle: const TextStyle(color: Colors.white), prefixIcon: const Icon( Icons.lock, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2.0, ), ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Colors.white, width: 2), ), suffixIcon: IconButton( icon: Icon( controller.obscureConf.value ? Icons.visibility : Icons.visibility_off, color: Colors.white, ), onPressed: () { controller.obscureConf.toggle(); }, ), ), ), ), SizedBox( height: Get.height * .03, ), GestureDetector( onTap: () => controller.signUp(), child: Container( height: Get.height * .07, width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, ), child: const Center( child: Text( "SIGN UP", style: TextStyle( color: Colors.black, fontSize: 20), ), ), ), ), SizedBox( height: Get.height * .015, ), TextButton( onPressed: () => Get.offNamed(login), child: Text( "LOGIN", style: TextStyle( color: Colors.white.withOpacity(0.8), fontSize: 30), ), ), ], ), ), ), ), ), Obx( () => controller.isLoading.value ? Container( color: Colors.black.withOpacity(0.5), child: const Center( child: CircularProgressIndicator( color: Colors.white, ), ), ) : const SizedBox.shrink(), ), ], ), ), ); } }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/auth/login_screen.dart
import 'package:film_fusion/utils/constants/routes.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../controller/login_screen_controller.dart'; class LoginScreen extends StatelessWidget { const LoginScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { LoginController controller = Get.put(LoginController()); return Scaffold( resizeToAvoidBottomInset: false, body: Container( height: double.infinity, width: double.infinity, decoration: const BoxDecoration( gradient: LinearGradient( colors: [ Color.fromRGBO(38, 116, 9, 1), Color.fromRGBO(0, 0, 0, 1), ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: Form( key: controller.formKey, // Access _formKey from controller child: Padding( padding: EdgeInsets.symmetric( horizontal: Get.width * .1, vertical: Get.height * .06), child: Column( children: [ Image.asset( "assets/images/logo.png", height: Get.height * .3, ), TextFormField( controller: controller.useremailController, validator: (value) => controller.validateUsername(value), style: const TextStyle(color: Colors.white), decoration: const InputDecoration( hintText: 'Email', hintStyle: TextStyle(color: Colors.white), prefixIcon: Icon( Icons.person, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors .white, // Color of the bottom line when focused width: 2.0, // Thickness of the bottom line when focused ), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2 // Color of the bottom line when unfocused ), ), ), ), const SizedBox(height: 20.0), Obx( () => TextFormField( controller: controller.passwordController, validator: (value) => controller.validatePassword(value), obscureText: controller.obscureText.value, // For password fields style: const TextStyle(color: Colors.white), decoration: InputDecoration( hintText: 'Password', hintStyle: const TextStyle( color: Colors.white, ), prefixIcon: const Icon( Icons.lock, color: Colors.white, ), alignLabelWithHint: true, focusedBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors .white, // Color of the bottom line when focused width: 2.0, // Thickness of the bottom line when focused ), ), enabledBorder: const UnderlineInputBorder( borderSide: BorderSide( color: Colors.white, width: 2 // Color of the bottom line when unfocused ), ), suffixIcon: IconButton( icon: Icon( controller.obscureText.value ? Icons.visibility : Icons.visibility_off, color: Colors.white, ), onPressed: () { controller.obscureText.value = !controller.obscureText.value; }, ), ), ), ), SizedBox( height: Get.height * .08, ), // Your existing UI code here GestureDetector( onTap: () { print("object"); controller .login(); // Call the login method from the controller }, child: Container( height: 60, width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white), child: Obx( () => Center( child: controller.isLoading.value ? const Center( child: CircularProgressIndicator( color: Colors.black, ), ) : const Text( "LOGIN", style: TextStyle( color: Colors.black, fontSize: 20), )), ), ), ), SizedBox( height: Get.height * .005, ), TextButton( onPressed: () => controller.forgotPasswordDialog(context), child: Text( "Forgot Your Password?", style: TextStyle( color: Colors.white.withOpacity(0.8), ), ), ), SizedBox( height: Get.height * .04, ), TextButton( onPressed: () => Get.toNamed(signup), child: Text( "SIGN UP", style: TextStyle( color: Colors.white.withOpacity(0.8), fontSize: 20), )) ], ), ), ), ), ); } }
0
mirrored_repositories/flim_fusion/lib/screens
mirrored_repositories/flim_fusion/lib/screens/home/home_screen.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/screens/home/widgets/header.dart'; import 'package:film_fusion/screens/home/widgets/latest_movie_poster.dart'; import 'package:film_fusion/screens/home/widgets/search_movies_textfield.dart'; import 'package:film_fusion/screens/home/widgets/section_title.dart'; import 'package:film_fusion/screens/home/widgets/top_rated_movies_posters.dart'; import 'package:film_fusion/screens/home/widgets/trending_movie_poster.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../controller/home_screen_controller.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); return SafeArea( child: Scaffold( resizeToAvoidBottomInset: false, body: Container( padding: const EdgeInsets.symmetric(horizontal: 25), height: double.infinity, width: double.infinity, decoration: const BoxDecoration( gradient: LinearGradient(colors: [ Color.fromRGBO(38, 116, 9, 1), Color.fromRGBO(0, 0, 0, 1), ], begin: Alignment.topCenter, end: Alignment.bottomCenter), ), child: GestureDetector( onTap: () { FocusScope.of(context).requestFocus(FocusNode()); controller.clearSuggestions(); }, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: Get.height * .07, ), const HomePageHeader(), SizedBox( height: Get.height * .035, ), SearchMoviesTextField(), const SizedBox( height: 20, ), Obx(() { final suggestions = controller.searchResults; if (suggestions.isEmpty) { return const SizedBox.shrink(); } return Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.white.withOpacity(0.12), borderRadius: BorderRadius.circular(10), ), height: Get.height * .5, child: ListView.builder( shrinkWrap: true, itemCount: suggestions.length, itemBuilder: (context, index) { final suggestion = suggestions[index]; return SizedBox( height: Get.height * .09, child: ListTile( leading: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${suggestion.posterPath}', placeholder: (context, url) => const CircularProgressIndicator(), errorWidget: (context, url, error) => const Icon(Icons.error), fit: BoxFit.fill, ), title: Text( suggestion.title, style: const TextStyle(color: Colors.white), ), onTap: () { // Handle suggestion selection Get.toNamed(detailScreen, arguments: suggestion); controller.searchResults.clear(); // Clear the search field }, ), ); }, ), ); }), SizedBox( height: Get.height * .035, ), // const SearchResultsWidget(), Expanded( child: SingleChildScrollView( child: Obx( () => controller.isLoading.value ? const Center( child: CircularProgressIndicator( color: Colors.white, )) : Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ const SectionTitle( title: "New Movies", ), SizedBox( height: Get.height * .02, ), LatestMoviePoster(), const SectionTitle( title: "Trending Movies", ), SizedBox( height: Get.height * .02, ), TrendingMoviePosters(), const SectionTitle( title: "Top Rated Movies", ), SizedBox( height: Get.height * .02, ), TopRtaedMoviesPoster(), SizedBox( height: Get.height * .035, ), ], ), ))), ], ), ), ))); } } // class CustomContainerClipper extends CustomClipper<Path> { // @override // Path getClip(Size size) { // final path = Path(); // // Define the width at the top and bottom // final double topWidth = 200.0; // final double bottomWidth = 50.0; // // Start from the top-left corner // path.moveTo(0, 0); // // Line to the top-right corner with variable width // path.lineTo(size.width - (topWidth - bottomWidth) / 2, 0); // // Line to the bottom-right corner with a horizontal line // path.lineTo(size.width - bottomWidth / 2, size.height); // path.lineTo((topWidth - bottomWidth) / 2, size.height); // // Line to the bottom-left corner with variable width // path.lineTo(bottomWidth / 2, size.height - 1); // path.lineTo(0, 1); // path.close(); // return path; // } // @override // bool shouldReclip(covariant CustomClipper<Path> oldClipper) { // return false; // } // } //latest Movies Display// // Obx( // () { // if (controller.isLoading.value) { // return Center(child: CircularProgressIndicator()); // } else { // return ListView.builder( // itemCount: controller.latestMovies.length, // itemBuilder: (context, index) { // final movie = controller.latestMovies[index]; // debugPrint(controller.latestMovies.length.toString()); // return ListTile( // leading: CachedNetworkImage( // imageUrl: // 'https://image.tmdb.org/t/p/w200${movie.posterPath}', // placeholder: (context, url) => CircularProgressIndicator(), // errorWidget: (context, url, error) => Icon(Icons.error), // ), // title: Text(movie.title), // // subtitle: Text(movie.releaseDate.timeZoneName), // onTap: () { // // Handle movie item tap here // }, // ); // }, // ); // } // }, // ), // // lib/screens/home_screen.dart // import 'package:flutter/material.dart'; // import 'package:get/get.dart'; // import '../../controller/home_screen_controller.dart'; // import '../../model/trending_movies_model.dart'; // import '../../model/new_movies_model.dart'; // class HomeScreen extends GetView<HomeScreenController> { // const HomeScreen({super.key}); // @override // Widget build(BuildContext context) { // return Scaffold( // appBar: AppBar( // title: Text('Movie App'), // ), // body: Obx(() { // if (controller.isLoading.value) { // return Center( // child: CircularProgressIndicator(), // ); // } else { // return ListView( // children: [ // SectionTitle('Trending Movies'), // MovieList(controller.trendingMovies), // SectionTitle('New Movies'), // NewMovieList(controller.newMovies), // ], // ); // } // }), // ); // } // } // class SectionTitle extends StatelessWidget { // final String title; // SectionTitle(this.title); // @override // Widget build(BuildContext context) { // return Padding( // padding: const EdgeInsets.all(16.0), // child: Text( // title, // style: TextStyle( // fontSize: 18, // fontWeight: FontWeight.bold, // ), // ), // ); // } // } // class MovieList extends StatelessWidget { // final RxList<Result> movies; // MovieList(this.movies); // @override // Widget build(BuildContext context) { // return SizedBox( // height: 200, // child: ListView.builder( // scrollDirection: Axis.horizontal, // itemCount: movies.length, // itemBuilder: (context, index) { // final movie = movies[index]; // return MovieCard(movie); // }, // ), // ); // } // } // class NewMovieList extends StatelessWidget { // final RxList<NewMovie> newMovies; // NewMovieList(this.newMovies); // @override // Widget build(BuildContext context) { // return Column( // children: newMovies.map((newMovie) => NewMovieCard(newMovie)).toList(), // ); // } // } // class MovieCard extends StatelessWidget { // final Result movie; // MovieCard(this.movie); // @override // Widget build(BuildContext context) { // return Container( // width: 150, // margin: EdgeInsets.all(8.0), // child: Column( // children: [ // Image.network( // 'https://image.tmdb.org/t/p/w200${movie.posterPath}', // height: 120, // ), // SizedBox(height: 8), // Text( // movie.title, // style: TextStyle( // fontSize: 16, // fontWeight: FontWeight.bold, // ), // textAlign: TextAlign.center, // ), // ], // ), // ); // } // } // class NewMovieCard extends StatelessWidget { // final NewMovie newMovie; // NewMovieCard(this.newMovie); // @override // Widget build(BuildContext context) { // return ListTile( // title: Text(newMovie.title), // subtitle: Text(newMovie.overview), // leading: Image.network( // 'https://image.tmdb.org/t/p/w200${newMovie.poster_path}', // height: 100, // width: 80, // fit: BoxFit.cover, // ), // ); // } // }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/search_movies_textfield.dart
import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class SearchMoviesTextField extends StatelessWidget{ SearchMoviesTextField({ super.key, }); final TextEditingController searchController = TextEditingController(); final FocusNode _searchFocusNode = FocusNode(); @override Widget build(BuildContext context) { HomeScreenController controller= Get.put(HomeScreenController()); return TextFormField( controller: searchController, onChanged: (query) { if (query.isEmpty) { controller.clearSuggestions(); _searchFocusNode.unfocus(); } else { controller.searchMovies(query); _searchFocusNode.requestFocus(); } }, // Clear the suggestions list when the text field is empty onEditingComplete: () { if (searchController.text.isEmpty) { controller.clearSuggestions(); } }, // controller: searchController, style: const TextStyle(color: Colors.white), focusNode: _searchFocusNode, decoration: InputDecoration( contentPadding: const EdgeInsets.symmetric(vertical: 8), prefixIcon: Icon( Icons.search, color: Colors.white.withOpacity(0.6), ), suffixIcon: GestureDetector( onTap: () => Get.to(()), child: Icon( Icons.mic, color: Colors.white.withOpacity(0.6), ), ), hintText: "Search", hintStyle: TextStyle( fontSize: 16, color: Colors.white.withOpacity(0.6), ), labelStyle: const TextStyle(color: Colors.white), filled: true, fillColor: Colors.white.withOpacity(0.12), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none, ), )); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/top_rated_movies_posters.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/utils/genre_data.dart'; import 'package:flutter/material.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:get/get.dart'; class TopRtaedMoviesPoster extends StatelessWidget { TopRtaedMoviesPoster({ Key? key, }) : super(key: key); Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); return Flexible( flex: 1, fit: FlexFit.loose, child: SizedBox( height: 300, child: Obx( () => ListView.builder( scrollDirection: Axis.horizontal, itemCount: controller.topRatedmoviesList.length, itemBuilder: (context, index) { final movie = controller.topRatedmoviesList[index]; final genreNames = GenreData().mapGenreIdsToNames(movie.genreIds, 2); return GestureDetector( onTap: () => Get.toNamed(detailScreen, arguments: movie), child: Container( width: 150, margin: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(50), ), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const Center( child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), width: 150, height: 217, fit: BoxFit.fill, ), ), const SizedBox( height: 10, ), Text( movie.title, maxLines: 1, // Limit to one line overflow: TextOverflow.ellipsis, // Add ellipsis (...) for overflow style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Colors.white), ), const SizedBox( height: 5, ), Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), color: Colors.red, ), child: Text( genreNames, style: TextStyle(color: Colors.white), ), ), ], ), ), ); }, ), )), ); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/search_screen_result.dart
// import 'package:film_fusion/controller/home_screen_controller.dart'; // import 'package:flutter/material.dart'; // import 'package:get/get.dart'; // class SearchResultsScreen extends GetView<HomeScreenController> { // @override // Widget build(BuildContext context) { // final TextEditingController searchController = TextEditingController(); // return Scaffold( // appBar: AppBar( // title: TextFormField( // controller: searchController, // decoration: InputDecoration( // hintText: "Search", // ), // onFieldSubmitted: (query) { // controller.searchMovies(query); // // Perform the search and display results // // You can call your searchMovies function here // // Don't forget to show a loading indicator while searching // }, // ), // ), // body: Obx(() { // if (controller.isLoading.value) { // return const Center( // child: CircularProgressIndicator(), // ); // } else { // // Display search results here in a ListView // return ListView.builder( // itemCount: controller.searchResults.length, // itemBuilder: (context, index) { // final result = controller.searchResults[index]; // // Create widgets to display search results // // You can customize this part as needed // return ListTile( // title: Text(result.title), // // Add more details or customize the result display // ); // }, // ); // } // }), // ); // } // }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/section_title.dart
import 'package:film_fusion/screens/home/catagories/latest_categories_.dart'; import 'package:film_fusion/screens/home/catagories/trending_category.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../catagories/top_rated_category.dart'; class SectionTitle extends StatelessWidget { final String title; const SectionTitle({ super.key, required this.title, }); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { if (title == "New Movies") { Get.to(() => LatestCategoriesList( title, )); } else if (title == "Trending Movies") { Get.to(() => TrendingCategoriesList( title, )); } else { Get.to(() => TopRatedCategoriesList(title)); } }, child: Text( title, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white.withOpacity(0.6), ), ), ); } } // class TrendingSectionTitle extends StatelessWidget { // final String title; // final dynamic trendingCatageryData; // const TrendingSectionTitle({ // super.key, // required this.title, // required this.trendingCatageryData, // }); // @override // Widget build(BuildContext context) { // return GestureDetector( // onTap: () => Get.to(TrendingCategoriesList(title, trendingCatageryData)), // child: Text( // title, // style: TextStyle( // fontSize: 18, // fontWeight: FontWeight.bold, // color: Colors.white.withOpacity(0.6), // ), // ), // ); // } // }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/latest_movie_poster.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/utils/genre_data.dart'; import 'package:flutter/material.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:get/get.dart'; class LatestMoviePoster extends StatelessWidget { LatestMoviePoster({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); return Flexible( flex: 1, fit: FlexFit.loose, child: SizedBox( height: 300, child: Obx( () => ListView.builder( scrollDirection: Axis.horizontal, itemCount: controller.latsetmoviesList.length, itemBuilder: (context, index) { final movie = controller.latsetmoviesList[index]; final genreNames = GenreData().mapGenreIdsToNames(movie.genreIds, 2); return GestureDetector( onTap: () => Get.toNamed(detailScreen, arguments: movie), child: Container( width: 150, margin: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(50), ), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const Center( child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), fit: BoxFit.fill, width: 147, height: 217, ), ), const SizedBox( height: 10, ), Text( movie.title, maxLines: 1, // Limit to one line overflow: TextOverflow .ellipsis, // Add ellipsis (...) for overflow style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Colors.white), ), const SizedBox( height: 5, ), Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), color: Colors.red, ), child: Text( genreNames, style: TextStyle(color: Colors.white), ), ), ], ), ), ); }, ), )), ); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/trending_movie_poster.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/utils/genre_data.dart'; import 'package:flutter/material.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:get/get.dart'; class TrendingMoviePosters extends StatelessWidget { TrendingMoviePosters({ Key? key, }) : super(key: key); Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); return Flexible( flex: 1, fit: FlexFit.loose, child: SizedBox( height: 300, child: Obx( () => ListView.builder( scrollDirection: Axis.horizontal, itemCount: controller.trendingmoviesList.length, itemBuilder: (context, index) { final movie = controller.trendingmoviesList[index]; final genreNames = GenreData().mapGenreIdsToNames(movie.genreIds, 2); return GestureDetector( onTap: () => Get.toNamed(detailScreen, arguments: movie), child: Container( width: 150, margin: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(50), ), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const Center( child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), width: 150, height: 217, fit: BoxFit.fill, ), ), const SizedBox( height: 10, ), Text( movie.title, maxLines: 1, // Limit to one line overflow: TextOverflow.ellipsis, // Add ellipsis (...) for overflow style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Colors.white), ), const SizedBox( height: 5, ), Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), color: Colors.red, ), child: Text( genreNames, style: TextStyle(color: Colors.white), ), ), ], ), ), ); }, ), )), ); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/widgets/header.dart
import 'package:flutter/material.dart'; class HomePageHeader extends StatelessWidget { const HomePageHeader({super.key}); @override Widget build(BuildContext context) { return Text("What would you like to watch?", textScaleFactor: 1, textAlign: TextAlign.center, style: TextStyle( fontSize: 28, fontWeight: FontWeight.bold, color: Colors.white.withOpacity(0.8), )); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/catagories/latest_categories_.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:get/get.dart'; import '../../../controller/favorite_screen_controller.dart'; import '../../../utils/genre_data.dart'; class LatestCategoriesList extends StatelessWidget { final String title; LatestCategoriesList(this.title, {super.key}); final user = FirebaseAuth.instance.currentUser; // Get the instance of HomeScreenController @override Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); FavoriteMoviesController favoriteMoviesController = Get.put(FavoriteMoviesController()); favoriteMoviesController.fetchFavoriteMovies(user!.uid); return Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, elevation: 0, title: Text( title, style: TextStyle(fontSize: 30, color: Colors.white.withOpacity(0.8)), ), centerTitle: true, leading: IconButton( icon: const Icon( Icons.arrow_back_ios, size: 30, ), onPressed: () { controller.resetPageParameter(); }), ), body: Padding( padding: const EdgeInsets.only(top: 20, left: 20, right: 20), child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 29.0, // Add spacing between rows crossAxisSpacing: 20.0, childAspectRatio: 0.5 // Add spacing between co ), itemCount: controller.latsetmoviesList.length + 1, // Add 1 for the loading indicator controller: controller.scrollControllerLatest, itemBuilder: (context, index) { if (index < controller.latsetmoviesList.length) { final movie = controller.latsetmoviesList[index]; final genreNames = GenreData().mapGenreIdsToNames(movie.genreIds, 2); return GestureDetector( onTap: () => Get.toNamed(detailScreen, arguments: movie), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack( children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(50), ), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const Center( child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), fit: BoxFit.fill, width: 147, height: 217, ), ), Padding( padding: EdgeInsets.only( left: Get.width * .27, top: 10), child: Obx( () { final isFavorite = favoriteMoviesController .isMovieFavorite(movie); return IconButton( icon: Icon( isFavorite ? Icons.favorite : Icons.favorite_border, color: isFavorite ? Colors.red : Colors.grey, ), onPressed: () { favoriteMoviesController.toggleFavorite( movie: movie, userId: user!.uid); }, ); }, )) ], ), const SizedBox( height: 10, ), Text( movie.title, maxLines: 1, // Limit to one line overflow: TextOverflow .ellipsis, // Add ellipsis (...) for overflow style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Colors.white), ), Container( padding: EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), color: Colors.red, ), child: Text( maxLines: 1, // Limit to one line overflow: TextOverflow.ellipsis, genreNames, style: TextStyle(color: Colors.white), ), ), RatingBar.builder( initialRating: movie.voteAverage / 2, // Divide by 2 to convert to a 5-star rating minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemSize: 15, unratedColor: Colors.white.withOpacity(0.8), itemBuilder: (context, _) => const Icon(Icons.star, color: Color.fromRGBO(242, 163, 58, 1)), onRatingUpdate: (newRating) { // Handle rating updates if needed }, ), ], ), ); } else { // Display loading indicator when reaching the end return controller.latestHasMoreData.value ? const Center( child: CircularProgressIndicator( color: Colors.white, )) : const SizedBox(); } }, ))); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/catagories/top_rated_category.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:get/get.dart'; import '../../../utils/constants/routes.dart'; import '../../../controller/favorite_screen_controller.dart'; import '../../../utils/genre_data.dart'; class TopRatedCategoriesList extends StatelessWidget { final String title; TopRatedCategoriesList(this.title, {super.key}); // Get the instance of HomeScreenController final user = FirebaseAuth.instance.currentUser; @override Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); FavoriteMoviesController favoriteMoviesController = Get.put(FavoriteMoviesController()); favoriteMoviesController.fetchFavoriteMovies(user!.uid); return Obx(() { return WillPopScope( onWillPop: () async { controller.resetPageParameter(); return true; // Allow the back navigation }, child: Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, elevation: 0, title: Text( title, style: TextStyle( fontSize: 30, color: Colors.white.withOpacity(0.8)), ), centerTitle: true, leading: IconButton( icon: const Icon( Icons.arrow_back_ios, size: 30, ), onPressed: () { controller.resetPageParameter(); }), ), body: Padding( padding: const EdgeInsets.only(top: 20, left: 20, right: 20), child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 29.0, // Add spacing between rows crossAxisSpacing: 20.0, childAspectRatio: 0.5 // Add spacing between co ), itemCount: controller.topRatedmoviesList.length + 1, // Add 1 for the loading indicator controller: controller.scrollControllerTopRated, itemBuilder: (context, index) { if (index < controller.topRatedmoviesList.length) { final movie = controller.topRatedmoviesList[index]; final genreNames = GenreData().mapGenreIdsToNames(movie.genreIds, 2); return GestureDetector( onTap: () => Get.toNamed(detailScreen, arguments: movie), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack( children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(50), ), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const Center( child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), fit: BoxFit.fill, width: 147, height: 217, ), ), Padding( padding: EdgeInsets.only( left: Get.width * .27, top: 10), child: Obx( () { final isFavorite = favoriteMoviesController .isMovieFavorite(movie); return IconButton( icon: Icon( isFavorite ? Icons.favorite : Icons.favorite_border, color: isFavorite ? Colors.red : Colors.grey, ), onPressed: () { favoriteMoviesController.toggleFavorite( movie: movie, userId: user!.uid); }, ); }, )), ], ), const SizedBox( height: 10, ), Text( movie.title, maxLines: 1, // Limit to one line overflow: TextOverflow .ellipsis, // Add ellipsis (...) for overflow style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Colors.white), ), Container( padding: const EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), color: Colors.red, ), child: Text( maxLines: 1, // Limit to one line overflow: TextOverflow.ellipsis, genreNames, style: const TextStyle(color: Colors.white), ), ), RatingBar.builder( initialRating: movie.voteAverage / 2, // Divide by 2 to convert to a 5-star rating minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemSize: 15, unratedColor: Colors.white.withOpacity(0.8), itemBuilder: (context, _) => const Icon( Icons.star, color: Color.fromRGBO(242, 163, 58, 1)), onRatingUpdate: (newRating) { // Handle rating updates if needed }, ), ], ), ); } else { // Display loading indicator when reaching the end return controller.topRatedHasMoreData.value ? const Center( child: CircularProgressIndicator( color: Colors.white, )) : const SizedBox(); } }, ), ))); }); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/catagories/trending_category.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/controller/home_screen_controller.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:get/get.dart'; import '../../../controller/favorite_screen_controller.dart'; import '../../../utils/genre_data.dart'; class TrendingCategoriesList extends StatelessWidget { final String title; TrendingCategoriesList(this.title, {super.key}); // Get the instance of HomeScreenController final user = FirebaseAuth.instance.currentUser; @override Widget build(BuildContext context) { HomeScreenController controller = Get.put(HomeScreenController()); FavoriteMoviesController favoriteMoviesController = Get.put(FavoriteMoviesController()); favoriteMoviesController.fetchFavoriteMovies(user!.uid); return Obx(() { return WillPopScope( onWillPop: () async { controller.resetPageParameter(); return true; // Allow the back navigation }, child: Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, elevation: 0, title: Text( title, style: TextStyle( fontSize: 30, color: Colors.white.withOpacity(0.8)), ), centerTitle: true, leading: IconButton( icon: const Icon( Icons.arrow_back_ios, size: 30, ), onPressed: () { controller.resetPageParameter(); }), ), body: Padding( padding: const EdgeInsets.only(top: 20, left: 20, right: 20), child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 29.0, // Add spacing between rows crossAxisSpacing: 20.0, childAspectRatio: 0.5 // Add spacing between co ), itemCount: controller.trendingmoviesList.length + 1, // Add 1 for the loading indicator controller: controller.scrollControllerTrending, itemBuilder: (context, index) { if (index < controller.trendingmoviesList.length) { final movie = controller.trendingmoviesList[index]; final genreNames = GenreData().mapGenreIdsToNames(movie.genreIds, 2); return GestureDetector( onTap: () => Get.toNamed(detailScreen, arguments: movie), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack( children: [ ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.circular(50), topRight: Radius.circular(20), bottomLeft: Radius.circular(20), bottomRight: Radius.circular(50), ), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${movie.posterPath}', placeholder: (context, url) => const Center( child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), fit: BoxFit.fill, width: 147, height: 217, ), ), Padding( padding: EdgeInsets.only( left: Get.width * .27, top: 10), child: Obx( () { final isFavorite = favoriteMoviesController .isMovieFavorite(movie); return IconButton( icon: Icon( isFavorite ? Icons.favorite : Icons.favorite_border, color: isFavorite ? Colors.red : Colors.grey, ), onPressed: () { favoriteMoviesController.toggleFavorite( movie: movie, userId: user!.uid); }, ); }, )), ], ), const SizedBox( height: 10, ), Text( movie.title, maxLines: 1, // Limit to one line overflow: TextOverflow .ellipsis, // Add ellipsis (...) for overflow style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, color: Colors.white), ), Container( padding: const EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(7), color: Colors.red, ), child: Text( maxLines: 1, // Limit to one line overflow: TextOverflow.ellipsis, genreNames, style: const TextStyle(color: Colors.white), ), ), RatingBar.builder( initialRating: movie.voteAverage / 2, // Divide by 2 to convert to a 5-star rating minRating: 1, direction: Axis.horizontal, allowHalfRating: true, itemCount: 5, itemSize: 15, unratedColor: Colors.white.withOpacity(0.8), itemBuilder: (context, _) => const Icon( Icons.star, color: Color.fromRGBO(242, 163, 58, 1)), onRatingUpdate: (newRating) { // Handle rating updates if needed }, ), ], ), ); } else { // Display loading indicator when reaching the end return controller.trendingHasMoreData.value ? const Center( child: CircularProgressIndicator( color: Colors.white, )) : const SizedBox(); } }, ), ))); }); } }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/detailScreen/detail_screen.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:film_fusion/controller/favorite_screen_controller.dart'; import 'package:film_fusion/screens/profile/profile_screen.dart'; import 'package:film_fusion/utils/genre_data.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:get/get.dart'; import 'package:readmore/readmore.dart'; class MovieDetailScreen extends StatelessWidget { const MovieDetailScreen({ super.key, }); @override Widget build(BuildContext context) { FavoriteMoviesController controller = Get.put(FavoriteMoviesController()); FirebaseAuth _user = FirebaseAuth.instance; final detailData = Get.arguments; final genreModel = GenreData().mapGenreIdsToNames(detailData.genreIds, 4); return SafeArea( child: Scaffold( backgroundColor: Colors.black, body: SingleChildScrollView( child: Stack( children: [ ClipRRect( borderRadius: const BorderRadius.only( bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)), child: CachedNetworkImage( imageUrl: 'https://image.tmdb.org/t/p/w200${detailData.posterPath}', placeholder: (context, url) => const Center(child: CircularProgressIndicator()), errorWidget: (context, url, error) => const Icon(Icons.error), filterQuality: FilterQuality.high, height: Get.height * .5, width: double.infinity, fit: BoxFit.fill, ), ), // Padding( // padding: const EdgeInsets.all(16), // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, // children: [ // InkWell( // onTap: () => Get.back(), // child: Container( // padding: const EdgeInsets.all(10), // decoration: BoxDecoration( // color: Colors.black.withOpacity(0.4), // borderRadius: BorderRadius.circular(50), // border: Border.all( // color: Colors.white, // width: 2, // ), // ), // child: const Icon( // Icons.arrow_back, // color: Colors.white, // )), // ), // GestureDetector( // onTap: () { // showPopupMenu(context); // debugPrint("tab"); // }, // child: Container( // padding: const EdgeInsets.all(10), // decoration: BoxDecoration( // color: Colors.black.withOpacity(0.4), // borderRadius: BorderRadius.circular(50), // border: Border.all( // color: Colors.white, // width: 2, // ), // ), // child: const Icon( // Icons.menu, // color: Colors.white, // )), // ), // ], // ), // ), Padding( padding: EdgeInsets.only(top: Get.height * .5), child: Container( decoration: const BoxDecoration( color: Colors.black, borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20))), child: Padding( padding: EdgeInsets.symmetric(horizontal: Get.width * .08), child: Column(mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: Get.height * .017, ), Text( detailData.title.toUpperCase(), textAlign: TextAlign.center, style: TextStyle( color: Colors.white.withOpacity(0.8), fontSize: 30, // fontWeight: FontWeight.w700 ), ), SizedBox( height: Get.height * .017, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( extractYearFromDate( detailData.releaseDate.toString(), ), style: TextStyle(color: Colors.white.withOpacity(0.8)), ), const SizedBox( width: 5, ), Container( height: 4, width: 4, color: Colors.white, ), const SizedBox( width: 5, ), Text( genreModel, style: TextStyle(color: Colors.white.withOpacity(0.8)), ), ], ), SizedBox( height: Get.height * .017, ), RatingBar.builder( initialRating: detailData.voteAverage / 2, // Divide by 2 to convert to a 5-star rating minRating: 1, direction: Axis.horizontal, allowHalfRating: true, // Set to false to prevent half-star ratings updateOnDrag: false, ignoreGestures: true, // Set to false to prevent rating change on drag itemCount: 5, itemSize: 20, unratedColor: Colors.white.withOpacity(0.8), itemBuilder: (context, _) => const Icon(Icons.star, color: Color.fromRGBO(242, 163, 58, 1)), onRatingUpdate: (newRating) { // Handle rating updates if needed }, ), SizedBox( height: Get.height * .017, ), ReadMoreText( detailData.overview, trimLines: 4, style: TextStyle( color: Colors.white.withOpacity(0.8), fontSize: 18), colorClickableText: Colors.white, trimMode: TrimMode.Line, trimCollapsedText: '...Show more', trimExpandedText: ' show less', ), SizedBox( height: Get.height * .025, ), InkWell( onTap: () => controller.toggleFavorite( movie: detailData, userId: _user.currentUser!.uid), child: Obx(() { final isFavorite = controller.isMovieFavorite(detailData); return Container( height: 50, width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white), child: Center( child: isFavorite ? const Text( "Added", style: TextStyle( color: Colors.black, fontSize: 16, fontWeight: FontWeight.w700), ) : const Text( "Add To Fav", style: TextStyle( color: Colors.black, fontSize: 16, fontWeight: FontWeight.w700), )), ); }), ), SizedBox( height: Get.height * .08, ) ]), ), ), ) ], ), ), ), ); // Build the detail screen for trending movies } String extractYearFromDate(String? releaseDate) { if (releaseDate != null && releaseDate.isNotEmpty) { try { final date = DateTime.parse(releaseDate); return date.year.toString(); } catch (e) { print('Error parsing release date: $e'); } } return ''; } void showPopupMenu(BuildContext context) { showMenu<int>( context: context, position: RelativeRect.fromLTRB(100, 30, 10, 10), color: Colors.grey, items: [ const PopupMenuItem<int>( value: 1, child: Text('Home Screen'), ), const PopupMenuItem<int>( value: 2, child: Text('Favorite Screen'), ), const PopupMenuItem<int>( value: 3, child: Text('Profile Screen'), ), const PopupMenuItem<int>( value: 4, child: Text('Screen 4'), ), ], ).then((value) { if (value == null) return; // Handle menu item selection if (value == 1) { Get.toNamed(homeScreen); } else if (value == 2) { Get.toNamed(favScreen); } else if (value == 3) { Get.to(ProfileScreen()); } else if (value == 4) { Get.toNamed(homeScreen); } }); } } // class LatestMovieDetailScreen extends StatelessWidget { // final Latest latestMovie; // Replace with your latest movie model // final String genreModel; // const LatestMovieDetailScreen( // {super.key, required this.latestMovie, required this.genreModel}); // @override // Widget build(BuildContext context) { // return SafeArea( // child: Scaffold( // backgroundColor: Colors.black, // body: Stack( // children: [ // ClipRRect( // borderRadius: const BorderRadius.only( // bottomLeft: Radius.circular(30), // bottomRight: Radius.circular(30)), // child: CachedNetworkImage( // imageUrl: // 'https://image.tmdb.org/t/p/w200${latestMovie.posterPath}', // placeholder: (context, url) => // const Center(child: CircularProgressIndicator()), // errorWidget: (context, url, error) => const Icon(Icons.error), // filterQuality: FilterQuality.high, // height: Get.height * .5, // width: double.infinity, // fit: BoxFit.fill, // ), // ), // Padding( // padding: const EdgeInsets.all(16), // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceBetween, // children: [ // InkWell( // onTap: () => Get.back(), // child: Container( // padding: EdgeInsets.all(10), // decoration: BoxDecoration( // color: Colors.black.withOpacity(0.4), // borderRadius: BorderRadius.circular(50), // border: Border.all( // color: Colors.white, // width: 2, // ), // ), // child: const Icon( // Icons.arrow_back, // color: Colors.white, // )), // ), // Container( // padding: EdgeInsets.all(10), // decoration: BoxDecoration( // color: Colors.black.withOpacity(0.4), // borderRadius: BorderRadius.circular(50), // border: Border.all( // color: Colors.white, // width: 2, // ), // ), // child: const Icon( // Icons.menu, // color: Colors.white, // )), // ], // ), // ), // Padding( // padding: EdgeInsets.only(top: Get.height * .5), // child: Container( // decoration: const BoxDecoration( // color: Colors.black, // borderRadius: BorderRadius.only( // topLeft: Radius.circular(20), // topRight: Radius.circular(20))), // child: Padding( // padding: EdgeInsets.symmetric(horizontal: Get.width * .08), // child: SingleChildScrollView( // child: Column(mainAxisSize: MainAxisSize.min, children: [ // const SizedBox( // height: 10, // ), // Text( // textAlign: TextAlign.center, // latestMovie.title.toUpperCase(), // style: TextStyle( // color: Colors.white.withOpacity(0.8), // fontSize: 30, // // fontWeight: FontWeight.w700 // ), // ), // const SizedBox( // height: 10, // ), // Padding( // padding: const EdgeInsets.all(8.0), // child: Row( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // Text( // extractYearFromDate( // latestMovie.releaseDate.toString(), // ), // style: TextStyle( // color: Colors.white.withOpacity(0.8)), // ), // const SizedBox( // width: 5, // ), // Container( // height: 4, // width: 4, // color: Colors.white, // ), // const SizedBox( // width: 5, // ), // Text( // genreModel, // style: TextStyle( // color: Colors.white.withOpacity(0.8)), // ), // ], // ), // ), // const SizedBox( // height: 10, // ), // RatingBar.builder( // initialRating: latestMovie.voteAverage / // 2, // Divide by 2 to convert to a 5-star rating // minRating: 1, // direction: Axis.horizontal, // allowHalfRating: true, // itemCount: 5, // itemSize: 20, // unratedColor: Colors.white.withOpacity(0.8), // itemBuilder: (context, _) => const Icon(Icons.star, // color: Color.fromRGBO(242, 163, 58, 1)), // onRatingUpdate: (newRating) { // // Handle rating updates if needed // }, // ), // const SizedBox( // height: 10, // ), // ReadMoreText( // latestMovie.overview, // trimLines: 7, // style: TextStyle( // color: Colors.white.withOpacity(0.8), fontSize: 18), // colorClickableText: Colors.white, // trimMode: TrimMode.Line, // trimCollapsedText: '...Show more', // trimExpandedText: ' show less', // ), // const SizedBox( // height: 10, // ), // ]), // ), // ), // ), // ) // ], // ), // ), // ); // // Build the detail screen for latest movies // } // String extractYearFromDate(String? releaseDate) { // if (releaseDate != null && releaseDate.isNotEmpty) { // try { // final date = DateTime.parse(releaseDate); // return date.year.toString(); // } catch (e) { // print('Error parsing release date: $e'); // } // } // return ''; // } // }
0
mirrored_repositories/flim_fusion/lib/screens/home
mirrored_repositories/flim_fusion/lib/screens/home/splash/splash_screen.dart
import 'dart:async'; import 'package:film_fusion/utils/constants/routes.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class SplashScreen extends StatefulWidget { const SplashScreen({super.key}); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { @override void initState() { isUserLogin(); super.initState(); } void isUserLogin() { final auth = FirebaseAuth.instance; final user = auth.currentUser; if (user != null) { Timer(const Duration(seconds: 3), () => Get.offNamed(mainScreen)); } else { Timer(const Duration(seconds: 3), () => Get.offNamed(login)); } } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Container( height: double.infinity, width: double.infinity, decoration: const BoxDecoration( gradient: LinearGradient(colors: [ Color.fromRGBO(38, 116, 9, 1), Color.fromRGBO(37, 35, 35, 1) ], begin: Alignment.topCenter, end: Alignment.bottomCenter), ), child: Column( // mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: Get.height * .2, ), Image.asset( "assets/images/logo.png", height: Get.height * .5, // color: Colors.red, ), ], ), ), ), ); } }
0