repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/forgot_pw.dart
import 'package:flutter/material.dart'; class SecondRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xFF0A0E21), appBar: AppBar( backgroundColor: Color(0xFF0A0E21), ), body: Container( child: ListView( children: <Widget>[ SizedBox( height: 250, ), Center( child: Text( 'Forgot Password', style: TextStyle( fontSize: 20, color: Colors.white, ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextFormField( style: TextStyle( color: Colors.white, ), decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), ), icon: Icon(Icons.email, color: Colors.white), //labelText: 'Password', hintText: 'Email', hintStyle: new TextStyle(color: Colors.grey), ), ), ), SizedBox( height: 40, ), Container( height: 50, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), //side: BorderSide(color: Colors.red) ), textColor: Colors.white, color: Color(0xFF4440D9), child: Text('Generate OTP'), onPressed: () { //Add forgot pw stuff here }, )), ], ) ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/pending_requests.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/appointment_tile.dart'; import 'package:qifyadmin/schedule_tile.dart'; import 'package:qifyadmin/view_profile.dart'; import 'current_user.dart'; class PendingRequests extends StatefulWidget { final String title; final String windowID; PendingRequests({this.title, this.windowID}); @override _PendingRequestsState createState() => _PendingRequestsState(); } class _PendingRequestsState extends State<PendingRequests> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('${widget.title}'), backgroundColor: Color(0xFF0A0E21), ), body: Padding( padding: EdgeInsets.only(top: 10, left: 8, right: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('appointments') // .orderBy('date') .where('doctorWindowID', isEqualTo: widget.windowID) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( "We're getting your pending appointment requests ready!", style: TextStyle(fontSize: 16), ), ); } final windows = snapshot.data.documents; List<AppointmentTile> tiles = []; for (var window in windows) { final name = window.data['name']; final content = window.data['description']; final windowID = window.data['doctorWindowID']; final status = window.data['appointmentStatus']; final image = window.data['image']; final uid = window.data['uid']; final docID = window.documentID; print(window.data); bool changeStatus; try { changeStatus = (status=="Approval Pending" || status.substring(0, 9)=="Forwarded")?true:false; } catch (e) { changeStatus=false; } tiles.add( AppointmentTile( userName: name, content: content, postImage: image, status: status, docId: docID, changeStatus: changeStatus, cancelAp: false, onPress: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return ViewProfile(uid: uid, name: name,); })); } ), ); } return Expanded( child: tiles.length != 0 ? ListView( children: tiles, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No appointment windows found'), ), ); }, ), ], ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/admin_screen.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/user_tile.dart'; import 'current_user.dart'; import 'login_screen.dart'; class AdminScreen extends StatefulWidget { @override _AdminScreenState createState() => _AdminScreenState(); } class _AdminScreenState extends State<AdminScreen> { bool loading; @override void didChangeDependencies() { super.didChangeDependencies(); loading = true; WidgetsBinding.instance.addPostFrameCallback((_) async { await Provider.of<CurrentUser>(context, listen: false).getRequests(); setState(() { loading = false; }); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Admin Panel'), backgroundColor: Color(0xFF0A0E21), actions: <Widget>[ IconButton( icon: Icon(Icons.exit_to_app), onPressed: () async { await FirebaseAuth.instance.signOut().then((value) { Navigator.of(context).popUntil((route) => route.isFirst); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) { return LoginPage(); })); }); }, ), // overflow menu ], ), body: ModalProgressHUD( inAsyncCall: loading, child: SafeArea( child: Consumer<CurrentUser>( builder: (context, userData, child) { return Padding( padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Doctor Verification Requests', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, fontFamily: 'Helvetica Neue', letterSpacing: 0.2, ), ), SizedBox( height: 10, ), userData.requests.length == 0 ? Text( 'No new requests', style: TextStyle(fontSize: 16.5), ) : ListView.builder( shrinkWrap: true, //reverse: true, itemCount: userData.requests.length, itemBuilder: (context, index) { return UserTile( userName: userData.requests[index].name, photoUrl: userData.requests[index].photoUrl, request: true, accept: () async { await userData.acceptRequest( userData.requests[index].uid, index); }, decline: () async { await userData.declineRequest( userData.requests[index].uid, index); }, ); }), SizedBox( height: 30, ), ], ), ); }, ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/search_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/user_tile.dart'; import 'package:qifyadmin/view_windows.dart'; import 'current_user.dart'; String currentText = ""; class SearchScreen extends StatefulWidget { @override _SearchScreenState createState() => _SearchScreenState(); } class _SearchScreenState extends State<SearchScreen> { String placeholderText = 'Start connecting with doctors now!'; bool searchState = false; Color c1 = Colors.grey; Color c2 = Colors.grey; Color activeC = Colors.pink; Color inactiveC = Colors.grey; String speciality = ''; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: Scaffold( backgroundColor: Colors.white, body: Consumer<CurrentUser>( builder: (context, userData, child) { return SafeArea( child: Column( children: <Widget>[ Padding( padding: EdgeInsets.only(top: 4, left: 4, right: 4), child: TextField( textCapitalization: TextCapitalization.sentences, decoration: InputDecoration( hintStyle: TextStyle(color: Colors.grey), hintText: 'Search', prefixIcon: Icon( Icons.search, color: Colors.black54, ), prefixStyle: TextStyle(color: Color(0xFF0A0E21)), contentPadding: EdgeInsets.only( top: 14.0, ), border: OutlineInputBorder( //borderRadius: BorderRadius.all(Radius.circular(32.0)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Color(0xFF0A0E21), width: 1.0), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Color(0xFF0A0E21), width: 2.0), ), ), // decoration: kTextFieldDecoration.copyWith( // ), onChanged: (value) { placeholderText = 'No doctor found!'; setState(() { currentText = value.toLowerCase(); if (!searchState) { searchState = true; } else if (value == "") { searchState = false; } }); }, ), ), Padding( padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10), child: Row( children: <Widget>[ Expanded( child: GestureDetector( onTap: () { setState(() { if (c1 == activeC) { c1 = inactiveC; speciality = ''; } else { c1 = activeC; c2 = inactiveC; speciality = 'false'; } }); }, child: Container( height: 40, child: Center( child: Text( 'Doctor', ), ), decoration: BoxDecoration( border: Border.all(color: c1), borderRadius: BorderRadius.all(Radius.circular(10)), ), ), ), ), SizedBox( width: 10, ), Expanded( child: GestureDetector( onTap: () { setState(() { if (c2 == activeC) { c2 = inactiveC; speciality = ''; } else { c1 = inactiveC; c2 = activeC; speciality = 'true'; } }); }, child: Container( height: 40, child: Center( child: Text( 'Speciality', ), ), decoration: BoxDecoration( border: Border.all(color: c2), borderRadius: BorderRadius.all(Radius.circular(10)), ), ), ), ), SizedBox( width: 10, ), ], ), ), StreamBuilder<QuerySnapshot>( stream: speciality == 'false' ? Firestore.instance .collection('users') .where('indexList', arrayContains: currentText) .snapshots() : Firestore.instance .collection('users') .where('specialityIndex', arrayContains: currentText) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( '$placeholderText', style: TextStyle(fontSize: 16), ), ); } final users = snapshot.data.documents; List<UserTile> userList = []; for (var user in users) { final userName = user.data['displayName']; final photoUrl = user.data['profile']; final uid = user.documentID.toString(); userList.add( UserTile( photoUrl: photoUrl, userName: userName, onPress: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return ViewWindows( name: userName, uid: uid, ); })); }, ), ); } return Expanded( child: userList.length != 0 ? ListView( children: userList, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No results found for $speciality'), ), ); }, ), ], ), ); }, ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/login_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/admin_screen.dart'; import 'package:qifyadmin/home_screen.dart'; import 'package:qifyadmin/verification_screen.dart'; import 'current_user.dart'; import 'register.dart'; import 'forgot_pw.dart'; class LoginPage extends StatefulWidget { @override State<StatefulWidget> createState() => new _State(); } class _State extends State<LoginPage> { final FirebaseAuth _auth = FirebaseAuth.instance; final Firestore _db = Firestore.instance; FirebaseUser _user; // String mail; // String password; String errorText; String mailErrorText; bool validateMail = false; bool validatePassword = false; bool _loading = false; var _mailController = TextEditingController(); var _passwordController = TextEditingController(); final FocusNode _mailFocus = FocusNode(); final FocusNode _passwordFocus = FocusNode(); _fieldFocusChange( BuildContext context, FocusNode currentFocus, FocusNode nextFocus) { currentFocus.unfocus(); FocusScope.of(context).requestFocus(nextFocus); } Future logIn() async { setState(() { _loading = true; }); try { if (_mailController.text == null || _mailController.text.length < 1) { setState(() { validateMail = true; mailErrorText = 'Enter a valid e-mail!'; _loading = false; }); } else if (_passwordController.text == null || _passwordController.text.length < 8) { setState(() { validatePassword = true; validateMail = false; errorText = 'Enter a valid password!'; _loading = false; }); } else { setState(() { validatePassword = false; validateMail = false; }); var user = await _auth.signInWithEmailAndPassword( email: _mailController.text, password: _passwordController.text); setState(() { _loading = false; }); if (user != null) { _user=await _auth.currentUser(); bool isDoc = false; bool admin = false; bool isVerified = false; await Firestore.instance .collection('users') .document(_user.uid) .get() .then((document) { print(document.data['photoUrl']); isDoc = document.data['isDoctor']; admin = document.data['admin']; isVerified = document.data['isVerified']; }); Navigator.of(context).popUntil((route) => route.isFirst); await Provider.of<CurrentUser>(context, listen: false) .getCurrentUser(); if (isDoc) { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return VerificationScreen(isVerified); })); } else if (admin!=null || admin == true){ Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return AdminScreen(); })); } else { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return HomePage(); })); } } } } catch (PlatformException) { setState(() { _loading = false; errorText = 'Check your email/password combination!'; mailErrorText = null; }); print(PlatformException.code); switch (PlatformException.code) { case "ERROR_INVALID_EMAIL": setState(() { mailErrorText = "Your email address appears to be malformed."; errorText = null; validateMail = true; validatePassword = false; }); break; case "ERROR_WRONG_PASSWORD": setState(() { errorText = "Wrong password!"; mailErrorText = null; validateMail = false; validatePassword = true; }); break; case "ERROR_USER_NOT_FOUND": setState(() { mailErrorText = "User with this email doesn't exist."; errorText = null; validateMail = true; validatePassword = false; }); break; case "ERROR_USER_DISABLED": setState(() { mailErrorText = "User with this email has been disabled."; errorText = null; validateMail = true; validatePassword = false; }); break; case "ERROR_TOO_MANY_REQUESTS": setState(() { errorText = "Too many requests. Try again later."; mailErrorText = null; validateMail = false; validatePassword = true; }); break; case "ERROR_NETWORK_REQUEST_FAILED": setState(() { errorText = 'The internet connection appears to be offline'; mailErrorText = null; validateMail = false; validatePassword = true; }); break; } } } @override Widget build(BuildContext context) { return ModalProgressHUD( inAsyncCall: _loading, child: Scaffold( backgroundColor: Color(0xFF0A0E21), body: ListView( shrinkWrap: true, padding: const EdgeInsets.all(20.0), children: <Widget>[ SizedBox( height: 270, ), Column( children: <Widget>[ Text( 'Qify', textAlign: TextAlign.right, style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white, fontSize: 40, fontFamily: 'Notable', ), ), IconButton( icon: Icon( Icons.supervised_user_circle, color: Colors.white, size: 40, ), ), ], ), SizedBox( //width: , height: 20, ), Container( padding: EdgeInsets.all(10), child: TextField( textInputAction: TextInputAction.next, style: TextStyle( color: Colors.white, ), focusNode: _mailFocus, controller: _mailController, keyboardType: TextInputType.emailAddress, onSubmitted: (value) { _fieldFocusChange(context, _mailFocus, _passwordFocus); }, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white12), ), prefixIcon: Icon( Icons.person, color: Colors.white, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), ), fillColor: Colors.white, hintText: 'Email', errorText: validateMail ? mailErrorText : null, hintStyle: new TextStyle(color: Colors.grey), //labelText: 'User Name', ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: new TextField( style: TextStyle( color: Colors.white, ), focusNode: _passwordFocus, controller: _passwordController, obscureText: true, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), ), errorText: validatePassword ? errorText : null, //labelText: 'Password', hintText: 'Password', prefixIcon: Icon(Icons.lock, color: Colors.white), hintStyle: new TextStyle(color: Colors.grey), ), onSubmitted: (value) => logIn(), ), ), FlatButton( onPressed: (){ Navigator.push( context, MaterialPageRoute(builder: (context) => SecondRoute()), ); }, textColor: Colors.blue, child: Text( 'Forgot Password', style: TextStyle(color: Colors.white), ), ), Container( height: 50, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), //side: BorderSide(color: Colors.red) ), textColor: Colors.white, color: Color(0xFF4440D9), child: Text('Login'), onPressed: () async => await logIn(), )), Container( child: Row( children: <Widget>[ Text( "Don't have an account?", style: TextStyle(color: Colors.white, fontSize: 16), ), FlatButton( textColor: Colors.white, child: Text( 'Register here', style: TextStyle( color: Colors.white, fontSize: 16 ), ), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => Register()), ); } ) ], mainAxisAlignment: MainAxisAlignment.center, ), ), ], ), ), ); } } class FirstRoute extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('First Route'), ), body: Center( child: RaisedButton( child: Text('Open route'), onPressed: () { // Navigate to second route when tapped. }, ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/main.dart
import 'package:bot_toast/bot_toast.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'current_user.dart'; import 'login_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => CurrentUser(), child: BotToastInit( child: MaterialApp( navigatorObservers: [BotToastNavigatorObserver()], //0xFFFE871E theme: ThemeData( primarySwatch: Colors.red, ), home: LoginPage(), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/user.dart
class User { final String name; final String photoUrl; final String uid; final bool isDoctor; User({this.name, this.photoUrl, this.uid, this.isDoctor}); }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/schedule_tile.dart
import 'package:flutter/material.dart'; class ScheduleTile extends StatelessWidget { final String title; final String startTime; final String endTime; final String date; final String docId; Function onLongPress; Function onPress; ScheduleTile({this.title, this.startTime, this.endTime, this.date, this.docId, this.onLongPress, this.onPress}); @override Widget build(BuildContext context) { return GestureDetector( onLongPress: onLongPress, onTap: onPress, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( '$title', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold ), ), SizedBox(height: 4,), Row( children: <Widget>[ Text( 'From ', style: TextStyle( fontSize: 17, ), ), Text( '$startTime', style: TextStyle( fontSize: 17, color: Colors.pink, ), ), Text( ' to ', style: TextStyle( fontSize: 17, ), ), Text( '$endTime', style: TextStyle( fontSize: 17, color: Colors.pink, ), ), ], ), SizedBox(height: 4,), Text( 'On $date', style: TextStyle( fontSize: 16, color: Colors.pink, ), ), SizedBox(height: 5,), Container( height: 0.5, color: Colors.black26, ), SizedBox(height: 12,), ], ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/appointment_tile.dart
import 'package:bot_toast/bot_toast.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/forward_screen.dart'; class AppointmentTile extends StatefulWidget { final String userName; final String content; final String postImage; final String docId; final String uid; final int index; final String status; final bool changeStatus; final bool cancelAp; Function onPress; AppointmentTile({ this.userName, this.content, //this.location, this.postImage, this.docId, this.uid, this.index, this.status, this.changeStatus, this.cancelAp, this.onPress, }); @override _AppointmentTileState createState() => _AppointmentTileState(); } class _AppointmentTileState extends State<AppointmentTile> { @override Widget build(BuildContext context) { return GestureDetector( onTap: widget.onPress, child: Padding( padding: EdgeInsets.only(top: 10, bottom: 10), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Patient Name: ${widget.userName}', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, letterSpacing: 0.1), ), Text( widget.status!="Done"?'Status: ${widget.status}':"", style: TextStyle( fontSize: 16, letterSpacing: 0.1, color: Colors.pink, ), ), ], ), SizedBox( height: 20, ), Visibility( visible: widget.content != null ? true : false, child: Text( '${widget.content}', style: TextStyle( fontSize: 17, letterSpacing: 0.15, height: 1.3, ), ), ), Visibility( visible: (widget.postImage != null) ? true : false, child: SizedBox( height: 10, ), ), Visibility( visible: (widget.postImage != null) ? true : false, child: Container( height: 256, width: 512, child: ClipRRect( borderRadius: BorderRadius.all(Radius.circular(10)), child: Image.network( '${widget.postImage}', fit: BoxFit.cover, ), ), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10)), ), ), ), SizedBox(height: 4,), Visibility( visible: widget.changeStatus, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ RaisedButton( color: Colors.green, child: Row( children: <Widget>[ Icon(Icons.check, color: Colors.white,), Text('Approve', style: TextStyle(color: Colors.white),), ], ), onPressed: () async { DocumentReference doctorRef = Firestore.instance.document('appointments/' + widget.docId); await Firestore.instance.runTransaction((transaction) async { DocumentSnapshot freshSnap1 = await transaction.get(doctorRef); await transaction.update(freshSnap1.reference, { 'appointmentStatus': 'Approved', }); }); }, ), RaisedButton( color: Colors.red, child: Row( children: <Widget>[ Icon(Icons.close, color: Colors.white,), Text('Reject', style: TextStyle(color: Colors.white),), ], ), onPressed: () async { DocumentReference doctorRef = Firestore.instance.document('appointments/' + widget.docId); await Firestore.instance.runTransaction((transaction) async { DocumentSnapshot freshSnap1 = await transaction.get(doctorRef); await transaction.update(freshSnap1.reference, { 'appointmentStatus': 'Rejected', }); }); }, ), RaisedButton( color: Colors.orange, child: Row( children: <Widget>[ Icon(Icons.send, color: Colors.white,), Text('Forward', style: TextStyle(color: Colors.white),), ], ), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return ForwardScreen(docID: widget.docId,); } )); }, ), ], ), ), Visibility( visible: widget.cancelAp, child: RaisedButton( color: Colors.red, child: Row( children: <Widget>[ Icon(Icons.close, color: Colors.white,), Text('Cancel', style: TextStyle(color: Colors.white),), ], ), onPressed: () async { try { DocumentReference ref = Firestore.instance.document('appointments/' + widget.docId); await Firestore.instance.runTransaction((Transaction myTransaction) async { await myTransaction.delete(ref); }); } catch (e) { BotToast.showSimpleNotification(title: 'Something went wrong :('); } }, ), ), SizedBox( height: 10, ), Container( height: 0.5, color: Colors.black26, ), SizedBox(height: 12,), ], ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/add_window.dart
import 'package:bot_toast/bot_toast.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:time_range_picker/time_range_picker.dart'; import 'current_user.dart'; class AddWindow extends StatefulWidget { final String title; final String startTime; final String endTime; final String date; final String docId; bool editState; AddWindow( {this.title, this.startTime, this.endTime, this.date, this.docId, this.editState}); @override _AddWindowState createState() => _AddWindowState(); } class _AddWindowState extends State<AddWindow> { bool inProgress = false; String text; String imgUrl; String startTime = "9"; String endTime = "9"; bool alteredTime = false; bool alteredDate = false; TextEditingController textEditingController; String _uploadedFileURL; DateTime selectedDate = DateTime.now(); Future<Null> _selectDate(BuildContext context) async { final DateTime picked = await showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime(2020, 7), lastDate: DateTime(2101)); if (picked != null && picked != selectedDate) setState(() { selectedDate = picked; }); print((selectedDate.toIso8601String()).substring(0, 10)); } Future pushData() async { try { if (((textEditingController.text == "" || textEditingController.text == null))) { setState(() { inProgress = false; }); BotToast.showSimpleNotification( title: 'Appointment window title is empty!'); } else { DocumentReference reference = await Firestore.instance.collection('windows').add({ 'title': textEditingController.text, 'startTime': startTime, 'endTime': endTime, 'date': (selectedDate.toIso8601String()).substring(0, 10), 'uid': Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid, 'time': FieldValue.serverTimestamp(), }); textEditingController.clear(); setState(() { inProgress = false; }); Navigator.pop(context); } } catch (e) { print(e); setState(() { inProgress = false; }); } } Future update() async { try { if (((textEditingController.text == "" || textEditingController.text == null))) { setState(() { inProgress = false; }); BotToast.showSimpleNotification( title: 'Appointment window title is empty!'); } else { await Firestore.instance .collection('windows') .document(widget.docId) .updateData({ 'title': textEditingController.text, 'startTime': alteredTime?startTime:widget.startTime, 'endTime': alteredTime?endTime:widget.endTime, 'date': alteredDate?(selectedDate.toIso8601String()).substring(0, 10):widget.date, 'uid': Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid, 'time': FieldValue.serverTimestamp(), }); textEditingController.clear(); setState(() { inProgress = false; }); Navigator.pop(context); } } catch (e) { print(e); setState(() { inProgress = false; }); } } @override void initState() { super.initState(); if (widget.editState) { textEditingController = TextEditingController(text:widget.title); } else { textEditingController = TextEditingController(); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.editState ? 'Edit Appointment Window' : 'Add Appointment Window'), backgroundColor: Color(0xFF0A0E21), ), body: GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: ModalProgressHUD( inAsyncCall: inProgress, child: SafeArea( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20), child: TextField( textCapitalization: TextCapitalization.sentences, keyboardType: TextInputType.multiline, maxLines: null, controller: textEditingController, onChanged: (value) { setState(() { text = value; }); }, decoration: InputDecoration( hintText: "Appointment Window Title", hintStyle: TextStyle(color: Colors.grey), prefixStyle: TextStyle(color: Color(0xFF0A0E21)), contentPadding: EdgeInsets.only(top: 14.0), // border: OutlineInputBorder( // //borderRadius: BorderRadius.all(Radius.circular(32.0)), // ), // enabledBorder: OutlineInputBorder( // borderSide: BorderSide(color: Color(0xFF0A0E21), width: 1.0), // ), // focusedBorder: OutlineInputBorder( // borderSide: BorderSide(color: Color(0xFF0A0E21), width: 2.0), // ), border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, suffixIcon: IconButton( icon: Icon( Icons.access_time, color: Color(0xFF0A0E21), ), onPressed: () async { TimeRange result = await showTimeRangePicker( context: context, start: TimeOfDay(hour: 10, minute: 0), end: TimeOfDay(hour: 10, minute: 15), onStartChange: (start) { print("${start.hour} ${start.minute}"); startTime = "${start.hour}:${start.minute}"; alteredTime = true; //print("start time " + start.toString()); }, onEndChange: (end) { print(end.hour); endTime = "${end.hour}:${end.minute}"; alteredTime = true; }, ); print("result " + result.toString()); }, )), ), ), SizedBox( height: 15, ), SizedBox( height: 15, ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( //mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.calendar_today, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Pick Date', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { alteredDate = true; await _selectDate(context); }), ), ), ), SizedBox( height: 10, ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.lock_open, color: Colors.white, ), SizedBox( width: 10, ), Text( widget.editState ? 'Update' : 'Set', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { setState(() { inProgress = true; }); FocusScope.of(context).unfocus(); if (widget.editState) { await update(); } else { await pushData(); } }), ), ), ), SizedBox( height: 30, ), Visibility( visible: widget.editState, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( //mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.delete_forever, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Delete Appointment Window', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { setState(() { inProgress=true; }); try { DocumentReference ref = Firestore.instance.document('windows/' + widget.docId); await Firestore.instance.runTransaction((Transaction myTransaction) async { await myTransaction.delete(ref); }); } catch (e) { BotToast.showSimpleNotification(title: 'Something went wrong :('); } setState(() { inProgress=false; }); }), ), ), ), ), ], ), ), ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/verification_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/current_user.dart'; import 'doctor_screen.dart'; import 'home_screen.dart'; import 'login_screen.dart'; class VerificationScreen extends StatefulWidget { bool isVerified; VerificationScreen(this.isVerified); @override _VerificationScreenState createState() => _VerificationScreenState(); } class _VerificationScreenState extends State<VerificationScreen> { bool loading = false; @override void didChangeDependencies() { super.didChangeDependencies(); WidgetsBinding.instance.addPostFrameCallback((_) async { if (widget.isVerified == true) { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return DoctorScreen(); })); } }); } @override Widget build(BuildContext context) { return ModalProgressHUD( inAsyncCall: loading, child: Scaffold( backgroundColor: Color(0xFF0A0E21), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'Waiting for Doctor to be verified.....', textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 24, ), ), SizedBox(height: 15,), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ IconButton( icon: Icon(Icons.refresh, color: Colors.white,size: 32,), onPressed: () async{ setState(() { loading=true; }); await Firestore.instance .collection('users') .document(Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid) .get() .then((document) { widget.isVerified = document.data['isVerified']; }); if (widget.isVerified) { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return DoctorScreen(); })); } setState(() { loading=false; }); }, ), IconButton( icon: Icon(Icons.exit_to_app), onPressed: () async { await FirebaseAuth.instance.signOut().then((value) { Navigator.of(context).popUntil((route) => route.isFirst); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) { return LoginPage(); })); }); }, ), ], ) ], ), ), ); } } //class VerificationPage extends StatefulWidget { //   VerificationPage({Key key}) : super(key: key); // //   @override //   _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); //} // //class _MyStatefulWidgetState extends State<VerificationPage> { // // //   @override //   Widget build(BuildContext context) { //     return Scaffold( //       backgroundColor: Color(0xFF0A0E21), //       appBar: AppBar( //         title: const Text('', //           style: TextStyle( //             color: Colors.white, //           ),), //       ), //       body: Center( //         child: Text( //           'Verifying user.....', //           style: TextStyle( //             fontWeight: FontWeight.bold, //             fontSize: 40, //           ), //         ), //       ), // // //     ); //   } //}
0
mirrored_repositories/Qify
mirrored_repositories/Qify/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:qifyadmin/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/countriesQuiz
mirrored_repositories/countriesQuiz/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import './pages/menu_page.dart'; void main() { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]).then((_) { runApp(new MaterialApp( home: new MenuPage(), )); }); }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/pages/score_page.dart
import 'package:flutter/material.dart'; import '../pages/menu_page.dart'; class ScorePage extends StatelessWidget { final int score; final int totalQuestion; ScorePage(this.score, this.totalQuestion); @override Widget build(BuildContext context) { return new Material( color: Colors.lightBlue, child: new InkWell( onTap: () => Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new MenuPage())), child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text("Your Score:", style: new TextStyle(color: Colors.white, fontSize: 50.0, fontWeight: FontWeight.bold)), new Text(score.toString() + "/" + totalQuestion.toString(), style: new TextStyle(color: Colors.white, fontSize: 25.0, fontWeight: FontWeight.bold)) ] ) ) ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/pages/menu_page.dart
import 'package:flutter/material.dart'; import '../pages/questions_page.dart'; class MenuPage extends StatelessWidget { @override Widget build(BuildContext context) { return new Material( color: Colors.lightBlue, child: new InkWell( onTap: () => Navigator.of(context).push(new MaterialPageRoute(builder: (BuildContext context) => new QuestionsPage())), child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text("Welcome!", style: new TextStyle(color: Colors.white, fontSize: 50.0, fontWeight: FontWeight.bold)), new Text("Tap to start guessing!", style: new TextStyle(color: Colors.white, fontSize: 25.0, fontWeight: FontWeight.bold)) ] ) ) ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/pages/questions_page.dart
import 'package:flutter/material.dart'; import '../components/question_box.dart'; import '../components/title_box.dart'; import '../components/answers_box.dart'; import '../components/overlay.dart'; import '../pages/score_page.dart'; import '../utils/country.dart'; import '../utils/countries.dart'; class QuestionsPage extends StatefulWidget { @override State createState() => new QuestionsPageState(); } class QuestionsPageState extends State<QuestionsPage> { int _questionNumber; int _allQuestions = 20; bool _isCorrect; bool _displayOverlay = false; Country _currentCountry; List<String> _randomCountries; Countries countries = new Countries([ //easy new Country('Argentina', 'ARS'), new Country('Australia', 'AUD'), new Country('Brazil', 'BRL'), new Country('Czech Republic', 'CZK'), new Country('Egypt', 'EGP'), new Country('European Union', 'EUR'), new Country('China', 'CNY'), new Country('Canada', 'CAD'), new Country('Japan', 'JPY'), new Country('India', 'INR'), new Country('Indonesia', 'IDR'), new Country('Israel', 'ILS'), new Country('Norway', 'NOK'), new Country('Malaysia', 'MYR'), new Country('Mexico', 'MXN'), new Country('New Zealand', 'NZD'), new Country('Qatar', 'QAR'), new Country('Russia', 'RUB'), new Country('South Africa', 'ZAR'), new Country('Switzerland', 'CHF'), new Country('Thailand', 'THB'), new Country('United Kingdom', 'GBP'), new Country('United States', 'USD'), //medium new Country('Belarus', 'BYN'), new Country('Bolivia', 'BOB'), new Country('Bosnia', 'BAM'), new Country('Bulgaria', 'BGN'), new Country('Chile', 'CLP'), new Country('Colombia', 'COP'), new Country('Costa Rica', 'CRC'), new Country('Croatia', 'HRK'), new Country('Denmark', 'DKK'), new Country('Georgia', 'GEL'), new Country('Ghana', 'GHS'), new Country('Hong Kong', 'HKD'), new Country('Jamaica', 'JMD'), new Country('Kazakhstan', 'KZT'), new Country('Kuwait', 'KWD'), new Country('North Korea', 'KPW'), new Country('South Korea', 'KRW'), new Country('Macedonia', 'MKD'), new Country('Moldova', 'MDL'), new Country('Morocco', 'MAD'), new Country('Nigeria', 'NGN'), new Country('Paraguay', 'PYG'), new Country('Peru', 'PEN'), new Country('Poland', 'PLN'), new Country('Romania', 'RON'), new Country('Serbia', 'RSD'), new Country('Singapore', 'BND/SGD'), new Country('Sri Lanka', 'LKR'), new Country('Tunisia', 'TND'), new Country('Turkey', 'TRY'), new Country('Ukraine', 'UAH'), new Country('Uruguay', 'UYU'), //hard new Country('Afghanistan', 'AFN'), new Country('Albania', 'ALL'), new Country('Algeria', 'DZD'), new Country('Angola', 'AOA'), new Country('Armenia', 'AMD'), new Country('Azerbaijan', 'AZN'), new Country('Bahrain', 'BHD'), new Country('Bangladesh', 'BDT'), new Country('Barbados', 'BBD'), new Country('Benin', 'XOF'), new Country('Botswana', 'BWP'), new Country('Burundi', 'BIF'), new Country('Cameroon', 'XAF'), new Country('Comoros', 'KMF'), new Country('Djibouti', 'DJF'), new Country('Dominican Rep.', 'DOP'), new Country('Eritrea', 'ERN'), new Country('Ethiopia', 'ETB'), new Country('Fiji', 'FJD'), new Country('Haiti', 'HTG'), new Country('Honduras', 'HNL'), new Country('Iran', 'IRR'), new Country('Iraq', 'IQD'), new Country('Jordan', 'JOD'), new Country('Kenya', 'KES'), new Country('Lebanon', 'LBP'), new Country('Liberia', 'LRD'), new Country('Libya', 'LYD'), new Country('Macau', 'MOP'), new Country('Madagascar', 'MGA'), new Country('Maledives', 'MVR'), new Country('Montserrat', 'XCD'), new Country('Myanmar', 'MMK'), new Country('Nepal', 'NPR'), new Country('New Caledonia', 'XPF'), new Country('Nicaragua', 'NIO'), new Country('Omar', 'OMR'), new Country('Pakistan', 'PKR'), new Country('Philippines', 'PHP'), new Country('Samoa', 'WST'), new Country('Sierra Leone', 'SLL'), new Country('Somalia', 'SOS'), new Country('Sudan', 'SDG'), new Country('Suriname', 'SRD'), new Country('Swaziland', 'SZL'), new Country('Syria', 'SYP'), new Country('Tajikistan', 'TJS'), new Country('Tanzania', 'TZS'), new Country('Tonga', 'TOP'), new Country('Turkmenistan', 'TMT'), new Country('Uganda', 'UGX'), new Country('Uzbekistan', 'UZS'), new Country('Vanuatu', 'VUV'), new Country('Venezuela', 'VEF'), new Country('Vietnam', 'VND'), new Country('Yemen', 'YER') ]); @override void initState() { super.initState(); _currentCountry = countries.nextCountry; _questionNumber = countries.questionNumber; } List<String> generateAnswers() { if (!_displayOverlay) { _randomCountries = new List<String>(); _randomCountries.add(_currentCountry.name); for(int i = 0; i <= 2; i++) { String randomCountry = countries.randomCountry.name; while(_randomCountries.contains(randomCountry)) { randomCountry = countries.randomCountry.name; } _randomCountries.add(randomCountry); } _randomCountries.shuffle(); return _randomCountries; } else { return _randomCountries; } } void checkAnswer(String answer) { _isCorrect = (_currentCountry.name == answer); countries.answer(_isCorrect); this.setState(() { _displayOverlay = true; }); } @override Widget build(BuildContext context) { return new Stack( fit: StackFit.expand, children: <Widget> [ new Column( children: <Widget>[ new TitleBox('Question ' + countries.questionNumber.toString() + '/' + _allQuestions.toString()), new QuestionBox(_currentCountry.currency), new AnswersBox(generateAnswers(), checkAnswer) ] ), _displayOverlay == true ? new AnswerOverlay( _isCorrect, () { if (_questionNumber >= _allQuestions) { Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (BuildContext context) => new ScorePage(countries.score, _allQuestions)), (Route route) => route == null); return; } _currentCountry = countries.nextCountry; this.setState((){ _displayOverlay = false; _questionNumber = countries.questionNumber; }); } ) : new Container() ], ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/components/title_box.dart
import 'package:flutter/material.dart'; class TitleBox extends StatelessWidget { final String _title; TitleBox(this._title); @override Widget build(BuildContext context) { return new Container( child: new Material( color: Colors.lightBlue, child: new Center( child: new Container( padding: new EdgeInsets.only(top: 45.0), child: new Text(_title, style: new TextStyle(color: Colors.white, fontSize: 30.0, fontWeight: FontWeight.bold)) ) ) ) ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/components/question_box.dart
import 'package:flutter/material.dart'; class QuestionBox extends StatelessWidget { final String _question; QuestionBox(this._question); @override Widget build(BuildContext context) { return new Expanded( child: new Material( color: Colors.lightBlue, child: new Center( child: new Container( padding: new EdgeInsets.all(20.0), child: new Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new Padding( padding: new EdgeInsets.only(top: 5.0), child: new Text('Whose currency is it?', style: new TextStyle(color: Colors.white, fontSize: 25.0)) ), new Padding( padding: new EdgeInsets.only(top: 25.0), child: new Text(_question, style: new TextStyle(color: Colors.white, fontSize: 75.0, fontWeight: FontWeight.bold)) ) ], ) ) ) ) ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/components/overlay.dart
import 'package:flutter/material.dart'; import 'dart:math'; class AnswerOverlay extends StatefulWidget { final bool _isCorrect; final VoidCallback _onTap; AnswerOverlay(this._isCorrect, this._onTap); @override State createState() => new AnswerOverlayState(); } class AnswerOverlayState extends State<AnswerOverlay> with SingleTickerProviderStateMixin { Animation<double> _iconAnimation; AnimationController _iconAnimationController; @override void initState() { super.initState(); _iconAnimationController = new AnimationController(duration: new Duration(seconds: 2), vsync: this); _iconAnimation = new CurvedAnimation(parent: _iconAnimationController, curve: Curves.elasticOut); _iconAnimation.addListener(() => this.setState(() {})); _iconAnimationController.forward(); } @override void dispose() { _iconAnimationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return new Material( color: Colors.black54, child: new InkWell( onTap: () => widget._onTap(), child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Container( decoration: new BoxDecoration( color: Colors.white, shape: BoxShape.circle ), child: new Transform.rotate( angle: _iconAnimation.value * 2 * PI, child: new Icon(widget._isCorrect == true ? Icons.done : Icons.clear, size: _iconAnimation.value * 80.0) ) ), new Padding( padding: new EdgeInsets.only(bottom: 20.0), ), new Text(widget._isCorrect == true ? "Correct!" : "Wrong!", style: new TextStyle(color: Colors.white, fontSize: 30.0)) ] ) ) ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/components/answers_box.dart
import 'package:flutter/material.dart'; typedef void StringCallback(String answer); class AnswersBox extends StatelessWidget { final List<String> _answers; final StringCallback callback; AnswersBox(this._answers, this.callback); @override Widget build(BuildContext context) { return new Container( height: 200.0, child: new Material( color: Colors.lightBlue, child: new Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ new Expanded( child: new Padding( padding: new EdgeInsets.all(10.0), child: new ButtonTheme( height: 75.0, child: new RaisedButton( onPressed: () => callback(_answers[0]), color: Colors.white, child: new Text(_answers[0], style: new TextStyle(fontSize: 20.0)), ) ) ) ), new Expanded( child: new Padding( padding: new EdgeInsets.all(10.0), child: new ButtonTheme( height: 75.0, child: new RaisedButton( onPressed: () => callback(_answers[1]), color: Colors.white, child: new Text(_answers[1], style: new TextStyle(fontSize: 20.0)), ) ) ) ), ] ), new Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ new Expanded( child: new Padding( padding: new EdgeInsets.all(10.0), child: new ButtonTheme( height: 75.0, child: new RaisedButton( onPressed: () => callback(_answers[2]), color: Colors.white, child: new Text(_answers[2], style: new TextStyle(fontSize: 20.0)), ) ) ) ), new Expanded( child: new Padding( padding: new EdgeInsets.all(10.0), child: new ButtonTheme( height: 75.0, child: new RaisedButton( onPressed: () => callback(_answers[3]), color: Colors.white, child: new Text(_answers[3], style: new TextStyle(fontSize: 20.0)), ) ) ) ), ] ) ], ) ) ); } }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/utils/country.dart
class Country { final String name; final String currency; Country(this.name, this.currency); }
0
mirrored_repositories/countriesQuiz/lib
mirrored_repositories/countriesQuiz/lib/utils/countries.dart
import './country.dart'; import 'dart:math'; class Countries { List<Country> _countries; int _currentCountryIndex = -1; int _score = 0; Countries(this._countries) { _countries.shuffle(); } List<Country> get countries => _countries; int get questionNumber => _currentCountryIndex + 1; int get length => _countries.length; int get score => _score; Country get randomCountry { Random _random = new Random(); return countries[_random.nextInt(countries.length)]; } Country get nextCountry { _currentCountryIndex++; if (_currentCountryIndex >= length) return null; return _countries[_currentCountryIndex]; } void answer(bool isCorrect) { if (isCorrect) _score++; } }
0
mirrored_repositories/shopzler
mirrored_repositories/shopzler/lib/constants.dart
import 'package:flutter/material.dart'; const primaryColor = Color.fromRGBO(0, 197, 105, 1);
0
mirrored_repositories/shopzler
mirrored_repositories/shopzler/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import 'helper/binding.dart'; import 'view/control_view.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( statusBarColor: Colors.transparent, )); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return OrientationBuilder( builder: (context, orientation) => ScreenUtilInit( designSize: orientation == Orientation.portrait ? Size(375, 812) : Size(812, 375), builder: () => GetMaterialApp( initialBinding: Binding(), theme: ThemeData( fontFamily: 'SourceSansPro', ), home: ControlView(), debugShowCheckedModeBanner: false, title: 'Shopzler', ), ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/cart_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../core/viewmodel/cart_viewmodel.dart'; import 'checkout_view.dart'; import '../../constants.dart'; import 'widgets/custom_text.dart'; import 'widgets/custom_button.dart'; class CartView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: GetBuilder<CartViewModel>( builder: (controller) => controller.cartProducts.isEmpty ? Center( child: Text('Empty Cart..'), ) : Column( children: [ Expanded( child: Padding( padding: EdgeInsets.only(top: 74.h, right: 16.w, left: 16.w), child: ListView.separated( padding: EdgeInsets.zero, itemBuilder: (context, index) { return Dismissible( key: Key(controller.cartProducts[index].productId), background: Container( color: Colors.red, alignment: Alignment.centerRight, padding: EdgeInsets.only(right: 33.w), child: Icon( Icons.delete_forever, color: Colors.white, size: 40, ), ), onDismissed: (direction) { if (direction == DismissDirection.endToStart) { controller.removeProduct( controller.cartProducts[index].productId); } }, child: Row( children: [ Image.network( controller.cartProducts[index].image, height: 120.h, width: 120.h, fit: BoxFit.cover, ), SizedBox( width: 30.w, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CustomText( text: controller.cartProducts[index].name, fontSize: 16, ), CustomText( text: '\$${controller.cartProducts[index].price}', fontSize: 16, color: primaryColor, ), SizedBox( height: 16.h, ), Container( height: 30.h, width: 95.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(4.r), color: Colors.grey.shade300, ), child: Padding( padding: EdgeInsets.symmetric( horizontal: 10.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ GestureDetector( child: Icon( Icons.add, size: 20, ), onTap: () { controller .increaseQuantity(index); }, ), CustomText( text: controller .cartProducts[index].quantity .toString(), fontSize: 16, alignment: Alignment.center, ), GestureDetector( child: Icon( Icons.remove, size: 20, ), onTap: () { controller .decreaseQuantity(index); }, ), ], ), ), ), ], ), ], ), ); }, separatorBuilder: (context, index) => SizedBox( height: 16.h, ), itemCount: controller.cartProducts.length, ), ), ), Material( elevation: 12, child: Container( padding: EdgeInsets.symmetric( horizontal: 30.w, vertical: 17.h), height: 84.h, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ CustomText( text: 'TOTAL', fontSize: 12, color: Colors.grey, ), CustomText( text: '\$${controller.totalPrice.toString()}', fontSize: 18, fontWeight: FontWeight.bold, color: primaryColor, ), ], ), Container( height: 50.h, width: 146.w, child: CustomButton( 'CHECKOUT', () { Get.to(CheckoutView()); }, ), ), ], ), ), ), ], ), ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/home_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../core/viewmodel/checkout_viewmodel.dart'; import '../core/viewmodel/home_viewmodel.dart'; import 'category_products_view.dart'; import 'product_detail_view.dart'; import 'search_view.dart'; import 'widgets/custom_text.dart'; import '../../constants.dart'; class HomeView extends StatelessWidget { @override Widget build(BuildContext context) { Get.put(CheckoutViewModel()); return Scaffold( body: GetBuilder<HomeViewModel>( init: Get.find<HomeViewModel>(), builder: (controller) => controller.loading ? Center( child: CircularProgressIndicator(), ) : SingleChildScrollView( padding: EdgeInsets.only( top: 65.h, bottom: 14.h, right: 16.w, left: 16.w), child: Column( children: [ Container( height: 49.h, decoration: BoxDecoration( color: Colors.grey.shade200, borderRadius: BorderRadius.circular(45.r), ), child: TextFormField( decoration: InputDecoration( border: InputBorder.none, prefixIcon: Icon( Icons.search, color: Colors.black, ), ), onFieldSubmitted: (value) { Get.to(SearchView(value)); }, ), ), SizedBox( height: 44.h, ), CustomText( text: 'Categories', fontSize: 18, fontWeight: FontWeight.bold, ), SizedBox( height: 19.h, ), ListViewCategories(), SizedBox( height: 50.h, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CustomText( text: 'Best Selling', fontSize: 18, fontWeight: FontWeight.bold, ), GestureDetector( onTap: () { Get.to(CategoryProductsView( categoryName: 'Best Selling', products: controller.products, )); }, child: CustomText( text: 'See all', fontSize: 16, ), ), ], ), SizedBox( height: 30.h, ), ListViewProducts(), ], ), ), ), ); } } class ListViewCategories extends StatelessWidget { @override Widget build(BuildContext context) { return GetBuilder<HomeViewModel>( builder: (controller) => Container( height: 90.h, child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: controller.categories.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { Get.to(CategoryProductsView( categoryName: controller.categories[index].name, products: controller.products .where((product) => product.category == controller.categories[index].name.toLowerCase()) .toList(), )); }, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Material( elevation: 1, borderRadius: BorderRadius.circular(50.r), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(50.r), color: Colors.white, ), height: 60.h, width: 60.w, child: Padding( padding: EdgeInsets.all(14.h), child: Image.network( controller.categories[index].image, ), ), ), ), CustomText( text: controller.categories[index].name, fontSize: 12, ), ], ), ); }, separatorBuilder: (context, index) { return SizedBox( width: 20.w, ); }, ), ), ); } } class ListViewProducts extends StatelessWidget { @override Widget build(BuildContext context) { return GetBuilder<HomeViewModel>( builder: (controller) => Container( height: 320.h, child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: controller.products.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { Get.to( ProductDetailView(controller.products[index]), ); }, child: Container( width: 164.w, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(4.r), color: Colors.white, ), height: 240.h, width: 164.w, child: Image.network( controller.products[index].image, fit: BoxFit.cover, ), ), CustomText( text: controller.products[index].name, fontSize: 16, ), CustomText( text: controller.products[index].description, fontSize: 12, color: Colors.grey, maxLines: 1, ), CustomText( text: '\$${controller.products[index].price}', fontSize: 16, color: primaryColor, ), ], ), ), ); }, separatorBuilder: (context, index) { return SizedBox( width: 15.w, ); }, ), ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/category_products_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../model/product_model.dart'; import 'product_detail_view.dart'; import 'widgets/custom_text.dart'; import '../constants.dart'; class CategoryProductsView extends StatelessWidget { final String categoryName; final List<ProductModel> products; CategoryProductsView({required this.categoryName, required this.products}); @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: categoryName, fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), Expanded( child: Padding( padding: EdgeInsets.only(right: 16.w, left: 16.w, bottom: 24.h), child: GridView.builder( padding: const EdgeInsets.all(0), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 16, crossAxisSpacing: 15, mainAxisExtent: 320, ), itemCount: products.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { Get.to( ProductDetailView(products[index]), ); }, child: Container( width: 164.w, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(4.r), color: Colors.white, ), height: 240.h, width: 164.w, child: Image.network( products[index].image, fit: BoxFit.cover, ), ), CustomText( text: products[index].name, fontSize: 16, ), CustomText( text: products[index].description, fontSize: 12, color: Colors.grey, maxLines: 1, ), CustomText( text: '\$${products[index].price}', fontSize: 16, color: primaryColor, ), ], ), ), ); }, ), ), ), ], ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/control_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../core/viewmodel/auth_viewmodel.dart'; import '../core/viewmodel/control_viewmodel.dart'; import '../core/network_viewmodel.dart'; import 'auth/login_view.dart'; import 'widgets/custom_text.dart'; class ControlView extends StatelessWidget { @override Widget build(BuildContext context) { return Obx(() { return Get.find<AuthViewModel>().user == null ? LoginView() : Get.find<NetworkViewModel>().connectionStatus.value == 1 || Get.find<NetworkViewModel>().connectionStatus.value == 2 ? GetBuilder<ControlViewModel>( init: ControlViewModel(), builder: (controller) => Scaffold( body: controller.currentScreen, bottomNavigationBar: CustomBottomNavigationBar(), ), ) : NoInternetConnection(); }); } } class CustomBottomNavigationBar extends StatelessWidget { @override Widget build(BuildContext context) { return SizedBox( height: 84.h, child: GetBuilder<ControlViewModel>( builder: (controller) => BottomNavigationBar( showSelectedLabels: false, showUnselectedLabels: false, elevation: 0, backgroundColor: Colors.grey.shade100, currentIndex: controller.navigatorIndex, onTap: (index) { controller.changeCurrentScreen(index); }, items: [ BottomNavigationBarItem( label: '', icon: Image.asset( 'assets/images/icons/explore.png', fit: BoxFit.contain, height: 20.h, width: 20.h, ), activeIcon: CustomText( text: 'Explore', fontSize: 14, alignment: Alignment.center, ), ), BottomNavigationBarItem( label: '', icon: Image.asset( 'assets/images/icons/cart.png', fit: BoxFit.contain, height: 20.h, width: 20.h, ), activeIcon: CustomText( text: 'Cart', fontSize: 14, alignment: Alignment.center, ), ), BottomNavigationBarItem( label: '', icon: Image.asset( 'assets/images/icons/account.png', fit: BoxFit.contain, height: 20.h, width: 20.h, ), activeIcon: CustomText( text: 'Account', fontSize: 14, alignment: Alignment.center, ), ), ], ), ), ); } } class NoInternetConnection extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(), SizedBox( height: 30.h, ), CustomText( text: 'Please check your internet connection..', fontSize: 14, alignment: Alignment.center, ), ], ), ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/search_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../core/viewmodel/home_viewmodel.dart'; import '../model/product_model.dart'; import 'product_detail_view.dart'; import 'widgets/custom_text.dart'; import '../constants.dart'; class SearchView extends StatefulWidget { final String? searchValue; SearchView(this.searchValue); @override _SearchViewState createState() => _SearchViewState(); } class _SearchViewState extends State<SearchView> { String? _searchValue; @override void initState() { _searchValue = widget.searchValue!.toLowerCase(); super.initState(); } @override Widget build(BuildContext context) { List<ProductModel> _searchProducts = _searchValue == '' ? [] : Get.find<HomeViewModel>() .products .where( (product) => product.name.toLowerCase().contains(_searchValue!)) .toList(); return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: 'Search', fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), Padding( padding: EdgeInsets.symmetric(horizontal: 16.w), child: Container( height: 49.h, decoration: BoxDecoration( color: Colors.grey.shade200, borderRadius: BorderRadius.circular(45.r), ), child: TextFormField( decoration: InputDecoration( border: InputBorder.none, prefixIcon: Icon( Icons.search, color: Colors.black, ), ), initialValue: _searchValue, onFieldSubmitted: (value) { setState(() { _searchValue = value.toLowerCase(); }); }, ), ), ), SizedBox( height: 24.h, ), Expanded( child: Padding( padding: EdgeInsets.only(right: 16.w, left: 16.w, bottom: 24.h), child: GetBuilder<HomeViewModel>( init: Get.find<HomeViewModel>(), builder: (controller) => GridView.builder( padding: const EdgeInsets.all(0), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 16, crossAxisSpacing: 15, mainAxisExtent: 320, ), itemCount: _searchProducts.length, itemBuilder: (context, index) { return GestureDetector( onTap: () { Get.to( ProductDetailView(_searchProducts[index]), ); }, child: Container( width: 164.w, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(4.r), color: Colors.white, ), height: 240.h, width: 164.w, child: Image.network( _searchProducts[index].image, fit: BoxFit.cover, ), ), CustomText( text: _searchProducts[index].name, fontSize: 16, ), CustomText( text: _searchProducts[index].description, fontSize: 12, color: Colors.grey, maxLines: 1, ), CustomText( text: '\$${_searchProducts[index].price}', fontSize: 16, color: primaryColor, ), ], ), ), ); }, ), ), ), ), ], ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/product_detail_view.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../core/viewmodel/cart_viewmodel.dart'; import '../model/cart_model.dart'; import '../model/product_model.dart'; import 'widgets/custom_button.dart'; import 'widgets/custom_text.dart'; import '../../constants.dart'; class ProductDetailView extends StatelessWidget { final ProductModel _productModel; ProductDetailView(this._productModel); @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Expanded( child: SingleChildScrollView( child: Column( children: [ Stack( alignment: Alignment.centerLeft, children: [ Container( height: 196.h, width: double.infinity, child: Image.network( _productModel.image, fit: BoxFit.cover, ), ), IconButton( onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), ], ), Padding( padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 4.h), child: Column( children: [ CustomText( text: _productModel.name, fontSize: 26, fontWeight: FontWeight.bold, ), SizedBox( height: 25.h, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ RoundedShapeInfo( title: 'Size', content: CustomText( text: _productModel.size, fontSize: 14, fontWeight: FontWeight.bold, alignment: Alignment.center, ), ), RoundedShapeInfo( title: 'Colour', content: Container( height: 22.h, width: 22.w, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), color: _productModel.color, ), ), ), ], ), SizedBox( height: 33.h, ), CustomText( text: 'Details', fontSize: 18, fontWeight: FontWeight.bold, ), SizedBox( height: 15.h, ), CustomText( text: _productModel.description, fontSize: 14, height: 2, ), ], ), ), ], ), ), ), Material( elevation: 12, color: Colors.white, child: Padding( padding: EdgeInsets.symmetric(vertical: 17.h, horizontal: 30.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ CustomText( text: 'PRICE', fontSize: 12, color: Colors.grey, ), CustomText( text: '\$${_productModel.price}', fontSize: 18, fontWeight: FontWeight.bold, color: primaryColor, ), ], ), GetBuilder<CartViewModel>( builder: (controller) => Container( width: 146.w, child: CustomButton('ADD', () { controller.addProduct( CartModel( name: _productModel.name, image: _productModel.image, price: _productModel.price, productId: _productModel.productId, ), ); }), ), ), ], ), ), ), ], ), ); } } class RoundedShapeInfo extends StatelessWidget { final String title; final Widget content; const RoundedShapeInfo({ required this.title, required this.content, }); @override Widget build(BuildContext context) { return Container( height: 40.h, width: 160.w, decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade400), borderRadius: BorderRadius.circular(25.r), ), child: Padding( padding: EdgeInsets.symmetric(horizontal: 20.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CustomText( text: title, fontSize: 14, alignment: Alignment.center, ), content, ], ), ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/profile_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../../core/viewmodel/auth_viewmodel.dart'; import '../../core/viewmodel/profile_viewmodel.dart'; import 'profile/cards_view.dart'; import 'profile/edit_profile_view.dart'; import 'profile/notifications_view.dart'; import 'profile/order_history_view.dart'; import 'widgets/custom_text.dart'; class ProfileView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: GetBuilder<ProfileViewModel>( init: ProfileViewModel(), builder: (controller) => controller.loading == true ? Center( child: CircularProgressIndicator(), ) : SingleChildScrollView( child: Padding( padding: EdgeInsets.only(top: 58.h, right: 16.w, left: 16.w), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( children: [ CircleAvatar( radius: 60.h, backgroundImage: AssetImage('assets/images/profile_pic.png'), foregroundImage: controller.currentUser!.pic != 'default' ? NetworkImage(controller.currentUser!.pic) : null, ), SizedBox( width: 30.w, ), Column( children: [ CustomText( text: controller.currentUser!.name, fontSize: 26, ), SizedBox( height: 6.h, ), CustomText( text: controller.currentUser!.email, fontSize: 14, ), ], ), ], ), SizedBox( height: 100.h, ), CustomListTile( iconName: '1', title: 'Edit Profile', onTapFn: () { Get.to(EditProfileView()); }, ), CustomListTile( iconName: '3', title: 'Order History', onTapFn: () { Get.to(OrderHistoryView()); }, ), CustomListTile( iconName: '4', title: 'Cards', onTapFn: () { Get.to(CardsView()); }, ), CustomListTile( iconName: '5', title: 'Notifications', onTapFn: () { Get.to(NotificationsView()); }, ), CustomListTile( iconName: '6', title: 'Log Out', onTapFn: () { Get.find<AuthViewModel>().signOut(); }, ), ], ), ), ), ), ); } } class CustomListTile extends StatelessWidget { final String iconName; final String title; final VoidCallback onTapFn; const CustomListTile({ required this.iconName, required this.title, required this.onTapFn, }); @override Widget build(BuildContext context) { return Column( children: [ ListTile( onTap: onTapFn, leading: Image.asset( 'assets/images/icons/menu_icons/$iconName.png', height: 40.h, width: 40.h, ), title: CustomText( text: title, fontSize: 18, ), trailing: title == 'Log Out' ? null : Icon( Icons.navigate_next, color: Colors.black, ), ), SizedBox( height: 20.h, ), ], ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/view/checkout_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../core/viewmodel/cart_viewmodel.dart'; import '../core/viewmodel/checkout_viewmodel.dart'; import 'widgets/custom_button.dart'; import '../constants.dart'; import 'widgets/custom_text.dart'; import 'widgets/custom_textFormField.dart'; class CheckoutView extends StatelessWidget { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: 'Checkout', fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), Expanded( child: SingleChildScrollView( child: Padding( padding: EdgeInsets.only(right: 16.w, left: 16.w, bottom: 24.h), child: Form( key: _formKey, child: GetBuilder<CheckoutViewModel>( init: Get.find<CheckoutViewModel>(), builder: (controller) => Column( children: [ ListViewProducts(), SizedBox( height: 20.h, ), CustomTextFormField( title: 'Street', hintText: '21, Tahrir Street', validatorFn: (value) { if (value!.isEmpty || value.length < 4) return 'Please enter valid street name.'; }, onSavedFn: (value) { controller.street = value; }, ), SizedBox( height: 20.h, ), CustomTextFormField( title: 'City', hintText: 'Downtown Cairo', validatorFn: (value) { if (value!.isEmpty || value.length < 4) return 'Please enter valid city name.'; }, onSavedFn: (value) { controller.city = value; }, ), SizedBox( height: 20.h, ), Row( children: [ Expanded( child: CustomTextFormField( title: 'State', hintText: 'Cairo', validatorFn: (value) { if (value!.isEmpty || value.length < 4) return 'Please enter valid state name.'; }, onSavedFn: (value) { controller.state = value; }, ), ), SizedBox( width: 36.w, ), Expanded( child: CustomTextFormField( title: 'Country', hintText: 'Egypt', validatorFn: (value) { if (value!.isEmpty || value.length < 4) return 'Please enter valid city name.'; }, onSavedFn: (value) { controller.country = value; }, ), ), ], ), SizedBox( height: 20.h, ), CustomTextFormField( title: 'Phone Number', hintText: '+20123456789', keyboardType: TextInputType.phone, validatorFn: (value) { if (value!.isEmpty || value.length < 10) return 'Please enter valid number.'; }, onSavedFn: (value) { controller.phone = value; }, ), SizedBox( height: 38.h, ), CustomButton( 'SUBMIT', () async { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); await controller.addCheckoutToFireStore(); Get.dialog( AlertDialog( content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon( Icons.check_circle_outline_outlined, color: primaryColor, size: 200.h, ), CustomText( text: 'Order Submitted', fontSize: 24, fontWeight: FontWeight.bold, color: primaryColor, alignment: Alignment.center, ), SizedBox( height: 40.h, ), CustomButton( 'Done', () { Get.back(); }, ), ], ), ), ), barrierDismissible: false, ); } }, ), ], ), ), ), ), ), ), ], ), ); } } class ListViewProducts extends StatelessWidget { @override Widget build(BuildContext context) { return GetBuilder<CartViewModel>( builder: (controller) => Column( children: [ Container( height: 160.h, child: ListView.separated( scrollDirection: Axis.horizontal, itemCount: controller.cartProducts.length, itemBuilder: (context, index) { return Container( width: 120.w, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(4.r), color: Colors.white, ), height: 120.h, width: 120.w, child: Image.network( controller.cartProducts[index].image, fit: BoxFit.cover, ), ), CustomText( text: controller.cartProducts[index].name, fontSize: 14, maxLines: 1, ), CustomText( text: '\$${controller.cartProducts[index].price} x ${controller.cartProducts[index].quantity}', fontSize: 14, color: primaryColor, ), ], ), ); }, separatorBuilder: (context, index) { return SizedBox( width: 15.w, ); }, ), ), SizedBox( height: 12.h, ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ CustomText( text: 'TOTAL: ', fontSize: 14, color: Colors.grey, ), CustomText( text: '\$${controller.totalPrice.toString()}', fontSize: 16, fontWeight: FontWeight.bold, color: primaryColor, ), ], ), ], ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/widgets/custom_button.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../constants.dart'; import 'custom_text.dart'; class CustomButton extends StatelessWidget { final String text; final VoidCallback? onPressedFn; CustomButton(this.text, this.onPressedFn); @override Widget build(BuildContext context) { return ElevatedButton( style: ElevatedButton.styleFrom( primary: primaryColor, elevation: 0, padding: EdgeInsets.symmetric(vertical: 16.h), ), onPressed: onPressedFn, child: CustomText( text: text, fontSize: 14, color: Colors.white, alignment: Alignment.center, ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/widgets/custom_textFormField.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../constants.dart'; import '../widgets/custom_text.dart'; class CustomTextFormField extends StatelessWidget { final String title; final String hintText; final String? Function(String?) validatorFn; final Function(String?) onSavedFn; final String initialValue; final TextInputType? keyboardType; final bool obscureText; CustomTextFormField({ required this.title, required this.hintText, required this.validatorFn, required this.onSavedFn, this.initialValue = '', this.keyboardType, this.obscureText = false, }); @override Widget build(BuildContext context) { return Column( children: [ CustomText( text: title, fontSize: 14.sp, color: Colors.grey.shade900, ), TextFormField( decoration: InputDecoration( hintText: hintText, hintStyle: TextStyle( color: Colors.grey.shade400, fontSize: 18.sp, ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: primaryColor, ), ), ), keyboardType: keyboardType, obscureText: obscureText, initialValue: initialValue, validator: validatorFn, onSaved: onSavedFn, ), ], ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/widgets/custom_text.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class CustomText extends StatelessWidget { final String text; final double fontSize; final FontWeight fontWeight; final Color color; final Alignment alignment; final int? maxLines; final double? height; CustomText({ this.text = '', this.fontSize = 16, this.fontWeight = FontWeight.normal, this.color = Colors.black, this.alignment = Alignment.topLeft, this.maxLines, this.height, }); @override Widget build(BuildContext context) { return Container( alignment: alignment, child: Text( text, style: TextStyle( fontSize: fontSize.sp, fontWeight: fontWeight, color: color, height: height, ), maxLines: maxLines, ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/profile/cards_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../widgets/custom_text.dart'; class CardsView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: 'Cards', fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), Expanded( child: Center( child: CustomText( text: 'You don\'t have cards.', fontSize: 16, color: Colors.black54, alignment: Alignment.center, ), ), ), ], ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/profile/edit_profile_view.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../../core/viewmodel/selectImage_viewmodel.dart'; import '../../core/viewmodel/profile_viewmodel.dart'; import '../widgets/custom_text.dart'; import '../widgets/custom_textFormField.dart'; import '../widgets/custom_button.dart'; class EditProfileView extends StatefulWidget { @override _EditProfileViewState createState() => _EditProfileViewState(); } class _EditProfileViewState extends State<EditProfileView> { final _formKey = GlobalKey<FormState>(); bool _isLoading = false; @override Widget build(BuildContext context) { String _loginMethod = FirebaseAuth.instance.currentUser!.providerData[0].providerId; return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: 'Edit Profile', fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), GetBuilder<SelectImageViewModel>( init: SelectImageViewModel(), builder: (controller) => Expanded( child: SingleChildScrollView( child: Padding( padding: EdgeInsets.only(right: 16.w, left: 16.w, bottom: 24.h), child: Card( child: Padding( padding: EdgeInsets.all(16.h), child: _loginMethod == 'google.com' || _loginMethod == 'facebook.com' ? Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset( _loginMethod == 'google.com' ? 'assets/images/icons/google.png' : 'assets/images/icons/facebook.png', fit: BoxFit.cover, height: 40.h, width: 40.h, ), SizedBox( height: 12.h, ), CustomText( text: _loginMethod == 'google.com' ? 'You\'re logged in using Google account!' : 'You\'re logged in using Facebook account!', fontSize: 16, alignment: Alignment.center, ), ], ) : Form( key: _formKey, child: Column( children: [ Row( children: [ CircleAvatar( radius: 60.h, backgroundImage: AssetImage( 'assets/images/profile_pic.png'), foregroundImage: controller.imageFile != null ? FileImage(controller.imageFile!) : null, ), SizedBox( width: 40.w, ), ElevatedButton( onPressed: () { Get.dialog( AlertDialog( title: CustomText( text: 'Choose option', fontSize: 20, color: Colors.blue, ), content: Column( mainAxisSize: MainAxisSize.min, children: [ Divider( height: 1, ), ListTile( onTap: () async { try { await controller .cameraImage(); Get.back(); } catch (error) { Get.back(); } }, title: CustomText( text: 'Camera', ), leading: Icon( Icons.camera, color: Colors.blue, ), ), Divider( height: 1, ), ListTile( onTap: () async { try { await controller .galleryImage(); Get.back(); } catch (error) { Get.back(); } }, title: CustomText( text: 'Gallery', ), leading: Icon( Icons.account_box, color: Colors.blue, ), ), ], ), ), ); }, child: Text('Select Image'), ), ], ), SizedBox( height: 38.h, ), CustomTextFormField( title: 'Name', hintText: Get.find<ProfileViewModel>() .currentUser! .name, initialValue: Get.find<ProfileViewModel>() .currentUser! .name, validatorFn: (value) { if (value!.isEmpty || value.length < 4) return 'Please enter valid name.'; }, onSavedFn: (value) { Get.find<ProfileViewModel>().name = value; }, ), SizedBox( height: 38.h, ), Column( children: [ CustomTextFormField( title: 'Email', hintText: Get.find<ProfileViewModel>() .currentUser! .email, initialValue: Get.find<ProfileViewModel>() .currentUser! .email, keyboardType: TextInputType.emailAddress, validatorFn: (value) { if (value!.isEmpty) return 'Please enter valid email address.'; }, onSavedFn: (value) { Get.find<ProfileViewModel>().email = value; }, ), SizedBox( height: 38.h, ), CustomTextFormField( title: 'Password', hintText: '', obscureText: true, validatorFn: (value) { if (value!.isEmpty || value.length < 6) return 'Please enter valid password with at least 6 characters.'; }, onSavedFn: (value) { Get.find<ProfileViewModel>() .password = value; }, ), ], ), SizedBox( height: 50.h, ), _isLoading ? CircularProgressIndicator() : CustomButton( 'SUBMIT', () async { if (_formKey.currentState! .validate()) { setState(() { _isLoading = true; }); try { await controller .uploadImageToFirebase(); Get.find<ProfileViewModel>() .picUrl = controller.picUrl; } catch (e) { Get.find<ProfileViewModel>() .picUrl = Get.find<ProfileViewModel>() .currentUser! .pic; } _formKey.currentState!.save(); await Get.find<ProfileViewModel>() .updateCurrentUser(); setState(() { _isLoading = false; }); } }, ), ], ), ), ), ), ), ), ), ), ], ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/profile/notifications_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../widgets/custom_text.dart'; class NotificationsView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: 'Notifications', fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), Expanded( child: Center( child: CustomText( text: 'You don\'t have notifications right now.', fontSize: 16, color: Colors.black54, alignment: Alignment.center, ), ), ), ], ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/profile/order_history_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../../constants.dart'; import '../../core/viewmodel/checkout_viewmodel.dart'; import '../widgets/custom_text.dart'; class OrderHistoryView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( height: 130.h, child: Padding( padding: EdgeInsets.only(bottom: 24.h, left: 16.w, right: 16.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ IconButton( padding: EdgeInsets.zero, constraints: BoxConstraints(), onPressed: () { Get.back(); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), CustomText( text: 'Order History', fontSize: 20, alignment: Alignment.bottomCenter, ), Container( width: 24, ), ], ), ), ), Expanded( child: GetBuilder<CheckoutViewModel>( init: Get.find<CheckoutViewModel>(), builder: (controller) => ListView.separated( itemBuilder: (context, index) { return Padding( padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h), child: Card( child: Padding( padding: EdgeInsets.all(16.h), child: Container( child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CustomText( text: controller.checkouts[index].date, color: Colors.grey, ), CustomText( text: 'Pending', color: Colors.red.shade300, ), ], ), Divider( thickness: 1, color: Colors.grey.shade200, ), CustomText( text: controller.checkouts[index].street, ), CustomText( text: controller.checkouts[index].city, ), CustomText( text: controller.checkouts[index].state, ), CustomText( text: controller.checkouts[index].country, ), CustomText( text: controller.checkouts[index].phone, ), Divider( thickness: 1, color: Colors.grey.shade200, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CustomText( text: 'Total Billed', color: primaryColor, ), CustomText( text: '\$${controller.checkouts[index].totalPrice}', color: primaryColor, ), ], ), ], ), ), ), ), ); }, separatorBuilder: (context, index) => Divider( thickness: 1, color: Colors.grey.shade200, ), itemCount: controller.checkouts.length, ), ), ), ], ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/auth/login_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../../core/viewmodel/auth_viewmodel.dart'; import 'register_view.dart'; import '../../constants.dart'; import '../widgets/custom_text.dart'; import '../widgets/custom_textFormField.dart'; import '../widgets/custom_button.dart'; class LoginView extends GetWidget<AuthViewModel> { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return OrientationBuilder( builder: (context, orientation) => Scaffold( body: SingleChildScrollView( child: Padding( padding: EdgeInsets.only( right: 16.w, left: 16.w, top: 126.h, bottom: 42.h), child: Column( children: [ Card( child: Padding( padding: EdgeInsets.all(16.h), child: Form( key: _formKey, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CustomText( text: 'Welcome,', fontSize: 30, fontWeight: FontWeight.bold, ), GestureDetector( onTap: () { Get.to(RegisterView()); }, child: CustomText( text: 'Sign Up', fontSize: 18, color: primaryColor, ), ), ], ), SizedBox( height: 10.h, ), CustomText( text: 'Sign in to Continue', fontSize: 14, color: Colors.grey, ), SizedBox( height: 48.h, ), CustomTextFormField( title: 'Email', hintText: '[email protected]', keyboardType: TextInputType.emailAddress, validatorFn: (value) { if (value!.isEmpty) return 'Email invalid or not found'; }, onSavedFn: (value) { controller.email = value; }, ), SizedBox( height: 38.h, ), CustomTextFormField( title: 'Password', hintText: '***********', obscureText: true, validatorFn: (value) { if (value!.isEmpty) return 'Password is incorrect'; }, onSavedFn: (value) { controller.password = value; }, ), SizedBox( height: 20.h, ), CustomText( text: 'Forgot Password?', fontSize: 14, alignment: Alignment.centerRight, ), SizedBox( height: 20.h, ), CustomButton( 'SIGN IN', () { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); controller.signInWithEmailAndPassword(); } }, ), ], ), ), ), ), SizedBox( height: 28.h, ), CustomText( text: '-OR-', fontSize: 18, alignment: Alignment.center, ), SizedBox( height: 43.h, ), CustomButtonSocial( title: 'Sign In with Facebook', image: 'facebook', onPressedFn: () { controller.signInWithFacebookAccount(); }, ), SizedBox( height: 20.h, ), CustomButtonSocial( title: 'Sign In with Google', image: 'google', onPressedFn: () { controller.signInWithGoogleAccount(); }, ), ], ), ), ), ), ); } } class CustomButtonSocial extends StatelessWidget { final VoidCallback onPressedFn; final String image; final String title; const CustomButtonSocial({ required this.onPressedFn, required this.image, required this.title, }); @override Widget build(BuildContext context) { return OutlinedButton( onPressed: onPressedFn, child: Padding( padding: EdgeInsets.symmetric(vertical: 14.h, horizontal: 30.w), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Image.asset( 'assets/images/icons/$image.png', fit: BoxFit.cover, height: 20.h, width: 20.h, ), CustomText( text: title, fontSize: 14, ), Container(width: 20.h), ], ), ), ); } }
0
mirrored_repositories/shopzler/lib/view
mirrored_repositories/shopzler/lib/view/auth/register_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import '../../core/viewmodel/auth_viewmodel.dart'; import 'login_view.dart'; import '../widgets/custom_text.dart'; import '../widgets/custom_textFormField.dart'; import '../widgets/custom_button.dart'; class RegisterView extends GetWidget<AuthViewModel> { final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( appBar: PreferredSize( preferredSize: Size.fromHeight(130.h), child: AppBar( elevation: 0, backgroundColor: Colors.white, automaticallyImplyLeading: false, flexibleSpace: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ IconButton( padding: EdgeInsets.only(left: 16.w, bottom: 30.h), onPressed: () { Get.off(LoginView()); }, icon: Icon( Icons.arrow_back_ios, color: Colors.black, ), ), ], ), ), ), body: SingleChildScrollView( child: Padding( padding: EdgeInsets.only(right: 16.w, left: 16.w, top: 32.h, bottom: 44.h), child: Column( children: [ Card( child: Padding( padding: EdgeInsets.all(16.h), child: Form( key: _formKey, child: Column( children: [ CustomText( text: 'Sign Up', fontSize: 30, fontWeight: FontWeight.bold, ), SizedBox( height: 48.h, ), CustomTextFormField( title: 'Name', hintText: 'Ahmed Elsayed', validatorFn: (value) { if (value!.isEmpty || value.length < 4) return 'Please enter valid name.'; }, onSavedFn: (value) { controller.name = value; }, ), SizedBox( height: 38.h, ), CustomTextFormField( title: 'Email', hintText: '[email protected]', keyboardType: TextInputType.emailAddress, validatorFn: (value) { if (value!.isEmpty) return 'Please enter valid email address.'; }, onSavedFn: (value) { controller.email = value; }, ), SizedBox( height: 38.h, ), CustomTextFormField( title: 'Password', hintText: '***********', obscureText: true, validatorFn: (value) { if (value!.isEmpty || value.length < 6) return 'Please enter valid password with at least 6 characters.'; }, onSavedFn: (value) { controller.password = value; }, ), SizedBox( height: 60.h, ), CustomButton( 'SIGN UP', () { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); controller.signUpWithEmailAndPassword(); } }, ), ], ), ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/model/product_model.dart
import 'package:flutter/material.dart'; import 'package:shopzler/helper/hexColor_extension.dart'; class ProductModel { late String name, image, description, size, price, productId, category; late Color color; ProductModel({ required this.name, required this.image, required this.description, required this.size, required this.price, required this.productId, required this.category, required this.color, }); ProductModel.fromJson(Map<dynamic, dynamic> map) { name = map['name']; image = map['image']; description = map['description']; size = map['size']; price = map['price']; productId = map['productId']; category = map['category']; color = HexColor.fromHex(map['color']); } toJson() { return { 'name': name, 'image': image, 'description': description, 'size': size, 'color': color.toString(), 'price': price, 'productId': productId, 'category': category, }; } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/model/checkout_model.dart
class CheckoutModel { late String street, city, state, country, phone, totalPrice, date; CheckoutModel({ required this.street, required this.city, required this.state, required this.country, required this.phone, required this.totalPrice, required this.date, }); CheckoutModel.fromJson(Map<dynamic, dynamic> map) { street = map['street']; city = map['city']; state = map['state']; country = map['country']; phone = map['phone']; totalPrice = map['totalPrice']; date = map['date']; } toJson() { return { 'street': street, 'city': city, 'state': state, 'country': country, 'phone': phone, 'totalPrice': totalPrice, 'date': date, }; } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/model/cart_model.dart
class CartModel { late String name, image, price, productId; late int quantity; CartModel({ required this.name, required this.image, required this.price, required this.productId, this.quantity = 1, }); CartModel.fromJson(Map<dynamic, dynamic> map) { name = map['name']; image = map['image']; price = map['price']; productId = map['productId']; quantity = map['quantity']; } toJson() { return { 'name': name, 'image': image, 'price': price, 'productId': productId, 'quantity': quantity, }; } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/model/category_model.dart
class CategoryModel { late String name, image; CategoryModel({ required this.name, required this.image, }); CategoryModel.fromJson(Map<dynamic, dynamic> map) { name = map['name']; image = map['image']; } toJson() { return { 'name': name, 'image': image, }; } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/model/user_model.dart
class UserModel { late String userId, email, name, pic; UserModel({ required this.userId, required this.email, required this.name, required this.pic, }); UserModel.fromJson(Map<dynamic, dynamic> map) { userId = map['userId']; email = map['email']; name = map['name']; pic = map['pic']; } toJson() { return { 'userId': userId, 'email': email, 'name': name, 'pic': pic, }; } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/core/network_viewmodel.dart
import 'dart:async'; import 'package:get/get.dart'; import 'package:connectivity/connectivity.dart'; class NetworkViewModel extends GetxController { var connectionStatus = 0.obs; late StreamSubscription<ConnectivityResult> _connectivitySubscription; @override void onInit() { super.onInit(); _connectivitySubscription = Connectivity().onConnectivityChanged.listen(_updateConnectionStatus); } _updateConnectionStatus(ConnectivityResult result) async { try { result = await Connectivity().checkConnectivity(); } catch (e) { print(e); } switch (result) { case ConnectivityResult.wifi: connectionStatus.value = 1; break; case ConnectivityResult.mobile: connectionStatus.value = 2; break; case ConnectivityResult.none: connectionStatus.value = 0; break; } } @override void onClose() { super.onClose(); _connectivitySubscription.cancel(); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/profile_viewmodel.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:get/get.dart'; import '../services/firestore_user.dart'; import '../services/local_storage_user.dart'; import '../../model/user_model.dart'; class ProfileViewModel extends GetxController { UserModel? _currentUser; String? name, email, password, picUrl; UserModel? get currentUser => _currentUser; bool _loading = false; bool get loading => _loading; @override void onInit() { super.onInit(); getCurrentUser(); } getCurrentUser() async { _loading = true; _currentUser = await LocalStorageUser.getUserData(); _loading = false; update(); } updateCurrentUser() async { try { UserModel _userModel = UserModel( userId: _currentUser!.userId, email: email!, name: name!, pic: picUrl == null ? _currentUser!.pic : picUrl!, ); await FirebaseAuth.instance.currentUser!.updateEmail(email!); await FirebaseAuth.instance.currentUser!.updatePassword(password!); FirestoreUser().addUserToFirestore(_userModel); await LocalStorageUser.setUserData(_userModel); getCurrentUser(); Get.back(); } catch (error) { String errorMessage = error.toString().substring(error.toString().indexOf(' ') + 1); Get.snackbar( 'Failed to update..', errorMessage, snackPosition: SnackPosition.BOTTOM, ); } } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/cart_viewmodel.dart
import 'package:get/get.dart'; import '../services/local_database_cart.dart'; import '../../model/cart_model.dart'; class CartViewModel extends GetxController { List<CartModel> _cartProducts = []; List<CartModel> get cartProducts => _cartProducts; double _totalPrice = 0; double get totalPrice => _totalPrice; @override void onInit() { super.onInit(); getCartProducts(); } getCartProducts() async { _cartProducts = await LocalDatabaseCart.db.getAllProducts(); getTotalPrice(); update(); } addProduct(CartModel cartModel) async { bool _isExist = false; _cartProducts.forEach((element) { if (element.productId == cartModel.productId) { _isExist = true; } }); if (!_isExist) { await LocalDatabaseCart.db.insertProduct(cartModel); getCartProducts(); } } removeProduct(String productId) async { await LocalDatabaseCart.db.deleteProduct(productId); getCartProducts(); } removeAllProducts() async { await LocalDatabaseCart.db.deleteAllProducts(); getCartProducts(); } getTotalPrice() { _totalPrice = 0; _cartProducts.forEach((cartProduct) { _totalPrice += (double.parse(cartProduct.price) * cartProduct.quantity); }); } increaseQuantity(int index) async { _cartProducts[index].quantity++; getTotalPrice(); await LocalDatabaseCart.db.update(_cartProducts[index]); update(); } decreaseQuantity(int index) async { if (_cartProducts[index].quantity != 0) { _cartProducts[index].quantity--; getTotalPrice(); await LocalDatabaseCart.db.update(_cartProducts[index]); update(); } } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/checkout_viewmodel.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import '../services/firestore_checkout.dart'; import '../viewmodel/cart_viewmodel.dart'; import '../../model/checkout_model.dart'; class CheckoutViewModel extends GetxController { String? street, city, state, country, phone; List<CheckoutModel> _checkouts = []; List<CheckoutModel> get checkouts => _checkouts; bool _isLoading = false; bool get isLoading => _isLoading; @override void onInit() { super.onInit(); _getCheckoutsFromFireStore(); } _getCheckoutsFromFireStore() async { _isLoading = true; _checkouts = []; List<QueryDocumentSnapshot> _checkoutsSnapshot = await FirestoreCheckout().getOrdersFromFirestore(); _checkoutsSnapshot.forEach((order) { _checkouts .add(CheckoutModel.fromJson(order.data() as Map<String, dynamic>)); }); _isLoading = false; update(); } addCheckoutToFireStore() async { await FirestoreCheckout().addOrderToFirestore(CheckoutModel( street: street!, city: city!, state: state!, country: country!, phone: phone!, totalPrice: Get.find<CartViewModel>().totalPrice.toString(), date: DateFormat.yMMMd().add_jm().format(DateTime.now()), )); Get.find<CartViewModel>().removeAllProducts(); Get.back(); _getCheckoutsFromFireStore(); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/control_viewmodel.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../../view/profile_view.dart'; import '../../view/cart_view.dart'; import '../../view/home_view.dart'; class ControlViewModel extends GetxController { Widget _currentScreen = HomeView(); int _navigatorIndex = 0; Widget get currentScreen => _currentScreen; int get navigatorIndex => _navigatorIndex; changeCurrentScreen(int index){ _navigatorIndex = index; switch(index){ case 0: _currentScreen = HomeView(); break; case 1: _currentScreen = CartView(); break; case 2: _currentScreen = ProfileView(); break; } update(); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/selectImage_viewmodel.dart
import 'dart:io'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; import 'package:path/path.dart'; import 'package:firebase_storage/firebase_storage.dart'; class SelectImageViewModel extends GetxController { File? imageFile; String? picUrl; cameraImage() async { final _pickedFile = await ImagePicker().pickImage( source: ImageSource.camera, maxHeight: 400, maxWidth: 400, ); imageFile = File(_pickedFile!.path); update(); } galleryImage() async { final _pickedFile = await ImagePicker().pickImage( source: ImageSource.gallery, maxHeight: 400, maxWidth: 400, ); imageFile = File(_pickedFile!.path); update(); } uploadImageToFirebase() async { String _fileName = basename(imageFile!.path); Reference _firebaseStorageRef = FirebaseStorage.instance.ref().child('profilePics/$_fileName'); UploadTask _uploadTask = _firebaseStorageRef.putFile(imageFile!); picUrl = await (await _uploadTask).ref.getDownloadURL(); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/auth_viewmodel.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:get/get.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:flutter_facebook_auth/flutter_facebook_auth.dart'; import '../services/local_storage_user.dart'; import '../services/firestore_user.dart'; import '../../model/user_model.dart'; import '../../view/control_view.dart'; class AuthViewModel extends GetxController { String? email, password, name; Rxn<User>? _user = Rxn<User>(); String? get user => _user?.value?.email; final _auth = FirebaseAuth.instance; @override void onInit() { super.onInit(); _user!.bindStream(_auth.authStateChanges()); } void signUpWithEmailAndPassword() async { try { await _auth .createUserWithEmailAndPassword(email: email!, password: password!) .then((user) { saveUser(user); }); Get.offAll(ControlView()); } catch (error) { String errorMessage = error.toString().substring(error.toString().indexOf(' ') + 1); Get.snackbar( 'Failed to login..', errorMessage, snackPosition: SnackPosition.BOTTOM, ); } } void signInWithEmailAndPassword() async { try { await _auth .signInWithEmailAndPassword(email: email!, password: password!) .then((user) { FirestoreUser().getUserFromFirestore(user.user!.uid).then((doc) { saveUserLocal( UserModel.fromJson(doc.data() as Map<dynamic, dynamic>)); }); }); Get.offAll(ControlView()); } catch (error) { String errorMessage = error.toString().substring(error.toString().indexOf(' ') + 1); Get.snackbar( 'Failed to login..', errorMessage, snackPosition: SnackPosition.BOTTOM, ); } } void signInWithGoogleAccount() async { try { GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['email']); final GoogleSignInAccount? _googleUser = await _googleSignIn.signIn(); GoogleSignInAuthentication _googleSignInAuthentication = await _googleUser!.authentication; final _googleAuthCredential = GoogleAuthProvider.credential( idToken: _googleSignInAuthentication.idToken, accessToken: _googleSignInAuthentication.accessToken, ); await _auth.signInWithCredential(_googleAuthCredential).then((user) { saveUser(user); }); Get.offAll(ControlView()); } catch (error) { String errorMessage = error.toString().substring(error.toString().indexOf(' ') + 1); Get.snackbar( 'Failed to login..', errorMessage, snackPosition: SnackPosition.BOTTOM, ); } } void signInWithFacebookAccount() async { try { final _facebookSignIn = await FacebookAuth.instance.login(); final _facebookAuthCredential = FacebookAuthProvider.credential(_facebookSignIn.accessToken!.token); await _auth.signInWithCredential(_facebookAuthCredential).then((user) { saveUser(user); }); Get.offAll(ControlView()); } catch (error) { Get.snackbar( 'Failed to login..', error.toString(), snackPosition: SnackPosition.BOTTOM, ); } } void signOut() async { try { await _auth.signOut(); LocalStorageUser.clearUserData(); } catch (error) { print(error); } } void saveUser(UserCredential userCredential) async { UserModel _userModel = UserModel( userId: userCredential.user!.uid, email: userCredential.user!.email!, name: name == null ? userCredential.user!.displayName! : this.name!, pic: userCredential.user!.photoURL == null ? 'default' : userCredential.user!.photoURL! + "?width=400", ); FirestoreUser().addUserToFirestore(_userModel); saveUserLocal(_userModel); } void saveUserLocal(UserModel userModel) async { LocalStorageUser.setUserData(userModel); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/viewmodel/home_viewmodel.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:get/get.dart'; import '../services/firestore_home.dart'; import '../../model/category_model.dart'; import '../../model/product_model.dart'; class HomeViewModel extends GetxController { List<CategoryModel> _categories = []; List<ProductModel> _products = []; List<CategoryModel> get categories => _categories; List<ProductModel> get products => _products; bool _loading = false; bool get loading => _loading; @override void onInit() { super.onInit(); _getCategoriesFromFireStore(); _getProductsFromFireStore(); } _getCategoriesFromFireStore() async { _loading = true; List<QueryDocumentSnapshot> categoriesSnapshot = await FirestoreHome().getCategoriesFromFirestore(); categoriesSnapshot.forEach((category) { _categories .add(CategoryModel.fromJson(category.data() as Map<String, dynamic>)); }); _loading = false; update(); } _getProductsFromFireStore() async { _loading = true; List<QueryDocumentSnapshot> productsSnapshot = await FirestoreHome().getProductsFromFirestore(); productsSnapshot.forEach((product) { _products .add(ProductModel.fromJson(product.data() as Map<String, dynamic>)); }); _loading = false; update(); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/services/firestore_checkout.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import '../../model/checkout_model.dart'; class FirestoreCheckout { final CollectionReference _ordersCollection = FirebaseFirestore.instance .collection('users') .doc(FirebaseAuth.instance.currentUser!.uid) .collection('orders'); Future<List<QueryDocumentSnapshot>> getOrdersFromFirestore() async { var _orders = await _ordersCollection.orderBy('date', descending: true).get(); return _orders.docs; } addOrderToFirestore(CheckoutModel checkoutModel) async { await _ordersCollection.doc().set(checkoutModel.toJson()); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/services/firestore_user.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import '../../model/user_model.dart'; class FirestoreUser { final CollectionReference _usersCollection = FirebaseFirestore.instance.collection('users'); addUserToFirestore(UserModel userModel) async { await _usersCollection.doc(userModel.userId).set(userModel.toJson()); } Future<DocumentSnapshot> getUserFromFirestore(String uid) async { return await _usersCollection.doc(uid).get(); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/services/local_database_cart.dart
import 'package:sqflite/sqflite.dart'; import 'package:path/path.dart'; import '../../model/cart_model.dart'; class LocalDatabaseCart { LocalDatabaseCart._(); static final LocalDatabaseCart db = LocalDatabaseCart._(); static Database? _database; Future<Database> get database async { if (_database != null) return _database!; _database = await initDb(); return _database!; } Future<Database> initDb() async { String _path = join(await getDatabasesPath(), 'CartProducts.db'); Database _database = await openDatabase(_path, version: 1, onCreate: (Database db, int version) async { await db.execute(''' CREATE TABLE cartProducts ( name TEXT NOT NULL, image TEXT NOT NULL, price TEXT NOT NULL, quantity INTEGER NOT NULL, productId TEXT NOT NULL) '''); }); return _database; } Future<List<CartModel>> getAllProducts() async { Database _db = await database; List<Map> _maps = await _db.query('cartProducts'); List<CartModel> _list = _maps.isNotEmpty ? _maps.map((cartProduct) => CartModel.fromJson(cartProduct)).toList() : []; return _list; } insertProduct(CartModel cartModel) async { Database _db = await database; await _db.insert( 'cartProducts', cartModel.toJson(), conflictAlgorithm: ConflictAlgorithm.replace, ); } deleteProduct(String productId) async { Database _db = await database; await _db.delete( 'cartProducts', where: 'productId = ?', whereArgs: [productId], ); } deleteAllProducts() async { Database _db = await database; await _db.delete('cartProducts'); } update(CartModel cartModel) async { Database _db = await database; await _db.update( 'cartProducts', cartModel.toJson(), where: 'productId = ?', whereArgs: [cartModel.productId], ); } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/services/firestore_home.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class FirestoreHome { final CollectionReference _categoriesCollection = FirebaseFirestore.instance.collection('categories'); final CollectionReference _productsCollection = FirebaseFirestore.instance.collection('products'); Future<List<QueryDocumentSnapshot>> getCategoriesFromFirestore() async { var categories = await _categoriesCollection.get(); return categories.docs; } Future<List<QueryDocumentSnapshot>> getProductsFromFirestore() async { var products = await _productsCollection.get(); return products.docs; } }
0
mirrored_repositories/shopzler/lib/core
mirrored_repositories/shopzler/lib/core/services/local_storage_user.dart
import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert'; import '../../model/user_model.dart'; class LocalStorageUser { static setUserData(UserModel userModel) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString('user', json.encode(userModel.toJson())); } static Future<UserModel> getUserData() async { SharedPreferences prefs = await SharedPreferences.getInstance(); return UserModel.fromJson( json.decode(prefs.getString('user')!) as Map<dynamic, dynamic>); } static clearUserData() async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.clear(); } }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/helper/hexColor_extension.dart
import 'package:flutter/material.dart'; extension HexColor on Color { /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#". static Color fromHex(String hexString) { final buffer = StringBuffer(); if (hexString.length == 6 || hexString.length == 7) buffer.write('ff'); buffer.write(hexString.replaceFirst('#', '')); return Color(int.parse(buffer.toString(), radix: 16)); } /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`). String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}' '${alpha.toRadixString(16).padLeft(2, '0')}' '${red.toRadixString(16).padLeft(2, '0')}' '${green.toRadixString(16).padLeft(2, '0')}' '${blue.toRadixString(16).padLeft(2, '0')}'; }
0
mirrored_repositories/shopzler/lib
mirrored_repositories/shopzler/lib/helper/binding.dart
import 'package:get/get.dart'; import '../core/network_viewmodel.dart'; import '../core/viewmodel/auth_viewmodel.dart'; import '../core/viewmodel/cart_viewmodel.dart'; import '../core/viewmodel/home_viewmodel.dart'; class Binding extends Bindings { @override void dependencies() { Get.lazyPut(() => AuthViewModel()); Get.lazyPut(() => HomeViewModel()); Get.put(CartViewModel()); Get.lazyPut(() => NetworkViewModel()); } }
0
mirrored_repositories/xno-game-ui
mirrored_repositories/xno-game-ui/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/l10n/l10n.dart'; import 'package:xno_game_ui/provider/language_provider.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/screens/create_room_screen.dart'; import 'package:xno_game_ui/screens/game_board.dart'; import 'package:xno_game_ui/screens/game_screen.dart'; import 'package:xno_game_ui/screens/join_room_screen.dart'; import 'package:xno_game_ui/screens/main_menu_screen.dart'; import 'package:xno_game_ui/screens/same_device_screen.dart'; import 'package:xno_game_ui/utils/constants.dart'; Future<void> main() async { await dotenv.load(fileName: "dotenv"); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider( create: (context) => RoomDataProvider(), ), ChangeNotifierProvider( create: (context) => LanguageProvider(), ), ], builder: (context, _) { final languageProvider = Provider.of<LanguageProvider>(context); return MaterialApp( debugShowCheckedModeBanner: false, title: 'X\'s & O\'s', theme: ThemeData( fontFamily: 'PressStart2P', brightness: Brightness.dark, scaffoldBackgroundColor: backgroundColor, dialogBackgroundColor: backgroundColor, snackBarTheme: const SnackBarThemeData( contentTextStyle: TextStyle( color: white, fontFamily: 'PressStart2P', ), ), ), routes: { MainMenuScreen.route: (context) => const MainMenuScreen(), CreateRoomScreen.route: (context) => const CreateRoomScreen(), JoinRoomScreen.route: (context) => const JoinRoomScreen(), SameDeviceScreen.route: (context) => const SameDeviceScreen(), GameScreen.route: (context) => const GameScreen(), GameBoard.route: (context) => const GameBoard(), }, supportedLocales: L10n.all, locale: Locale(languageProvider.whatLanguage), localizationsDelegates: const [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], initialRoute: MainMenuScreen.route, ); }, ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/views/scoreboard.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; class Scoreboard extends StatelessWidget { const Scoreboard({super.key}); Widget score(String nickname, String points, int color) { return Padding( padding: const EdgeInsets.all(30), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CustomText( text: nickname, textAlign: TextAlign.center, fontSize: 30, shadows: [ Shadow( blurRadius: 10, color: playerColor.elementAt(color), ), ], color: playerColor.elementAt(color), ), CustomText( text: points, textAlign: TextAlign.center, fontSize: 30, shadows: [ Shadow( blurRadius: 10, color: playerColor.elementAt(color), ), ], color: white, ), ], ), ); } @override Widget build(BuildContext context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context); return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ score( roomDataProvider.player1.nickname, roomDataProvider.player1.points.toInt().toString(), roomDataProvider.player1.color.toInt(), ), score( roomDataProvider.player2.nickname, roomDataProvider.player2.points.toInt().toString(), roomDataProvider.player2.color.toInt(), ), ], ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/views/waiting_lobby.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; import 'package:xno_game_ui/widgets/custom_text_field.dart'; class WaintingLobby extends StatefulWidget { const WaintingLobby({super.key}); @override State<WaintingLobby> createState() => _WaintingLobbyState(); } class _WaintingLobbyState extends State<WaintingLobby> { late TextEditingController roonIdController; @override void initState() { super.initState(); roonIdController = TextEditingController( text: Provider.of<RoomDataProvider>(context, listen: false).roomData['_id'], ); } @override void dispose() { super.dispose(); roonIdController.dispose(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(50), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const CustomText( text: 'Waiting for a player to join 🕓', shadows: [ Shadow( blurRadius: 10, color: white, ), ], color: white, fontSize: 20, ), height20, const CustomText( text: 'Game ID', shadows: [ Shadow( blurRadius: 10, color: white, ), ], color: white, fontSize: 15, ), height20, CustomTextField( controller: roonIdController, hintText: '', validator: null, isRedyOnly: true, ), ], ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/views/tictactoe_board.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/resources/socket_methods.dart'; import 'package:xno_game_ui/widgets/grid_box.dart'; class TicTactoeBoard extends StatefulWidget { const TicTactoeBoard({super.key}); @override State<TicTactoeBoard> createState() => _TicTactoeBoardState(); } class _TicTactoeBoardState extends State<TicTactoeBoard> { final SocketMethods _socketMethods = SocketMethods(); @override void initState() { super.initState(); _socketMethods.tappedListener(context); } void tapped(int index, RoomDataProvider roomDataProvider) { _socketMethods.tapGrid( index, roomDataProvider.roomData['_id'], roomDataProvider.displayElements, ); } @override void dispose() { _socketMethods.socketClient.dispose(); super.dispose(); } @override Widget build(BuildContext context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context); return GridBox( absorbingPoint: roomDataProvider.roomData['turn']['socketID'] != _socketMethods.socketClient.id, tappedFunction: tapped); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/views/tictactoe_board_same.dart
import 'package:flutter/material.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/resources/game_methods.dart'; import 'package:xno_game_ui/widgets/grid_box.dart'; class TicTactoeBoardSame extends StatefulWidget { const TicTactoeBoardSame({super.key}); @override State<TicTactoeBoardSame> createState() => _TicTactoeBoardSameState(); } class _TicTactoeBoardSameState extends State<TicTactoeBoardSame> { void tapped(int index, RoomDataProvider roomDataProvider) { if (roomDataProvider.displayElements[index] == '') { final choice = roomDataProvider.roomData['turn']['playerType']; final roomUpdate = roomDataProvider.roomData; if (roomDataProvider.roomData['turnIndex'] == 0) { roomUpdate['turn'] = roomDataProvider.player2.toMap(); roomUpdate['turnIndex'] = 1; } else { roomUpdate['turn'] = roomDataProvider.player1.toMap(); roomUpdate['turnIndex'] = 0; } roomDataProvider.updateRoomData(roomUpdate); roomDataProvider.updateDisplayElements( index, choice, ); GameMethods().checkWinner(context, null); } } @override Widget build(BuildContext context) { return GridBox( absorbingPoint: false, tappedFunction: tapped, ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/custom_button.dart
import 'package:flutter/material.dart'; import 'package:xno_game_ui/utils/constants.dart'; class CustomButton extends StatelessWidget { const CustomButton({ super.key, required this.onTap, required this.text, this.color, this.border, this.backColor, }); final VoidCallback onTap; final String text; final Color? color; final bool? border; final Color? backColor; @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Container( decoration: BoxDecoration( shape: border == null ? BoxShape.rectangle : BoxShape.circle, boxShadow: [ BoxShadow( color: color ?? Colors.white, blurRadius: 10, spreadRadius: 2, blurStyle: BlurStyle.solid), ], ), child: ElevatedButton( onPressed: onTap, style: ElevatedButton.styleFrom( shape: border == null ? const RoundedRectangleBorder() : const CircleBorder(), backgroundColor: backColor ?? backgroundColor, minimumSize: Size( width / 5, 50, ), ), child: Text( text, style: TextStyle( fontSize: 15, color: color ?? Colors.white, ), ), ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/grid_box.dart
import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; class GridBox extends StatelessWidget { const GridBox({ super.key, required this.absorbingPoint, required this.tappedFunction, }); final bool absorbingPoint; final Function tappedFunction; @override Widget build(BuildContext context) { final Size size = MediaQuery.of(context).size; RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context); return ConstrainedBox( constraints: const BoxConstraints( maxHeight: 400, maxWidth: 400, ), child: AbsorbPointer( absorbing: absorbingPoint, child: GridView.builder( itemCount: 9, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, ), itemBuilder: (context, index) { return GestureDetector( onTap: () => tappedFunction(index, roomDataProvider), child: Container( decoration: BoxDecoration( border: Border.all( color: roomDataProvider.displayElements[index] == '' ? white : roomDataProvider.displayElements[index] == 'O' ? playerColor .elementAt(roomDataProvider.player2.color) : playerColor .elementAt(roomDataProvider.player1.color), ), ), child: Center( child: CustomText( text: roomDataProvider.displayElements[index], fontSize: size.width < 600 ? 50 : 100, color: roomDataProvider.displayElements[index] == 'O' ? playerColor.elementAt(roomDataProvider.player2.color) : playerColor.elementAt(roomDataProvider.player1.color), shadows: [ Shadow( blurRadius: 40, color: roomDataProvider.displayElements[index] == 'O' ? playerColor .elementAt(roomDataProvider.player2.color) : playerColor .elementAt(roomDataProvider.player1.color), ), ], ) .animate( onPlay: (controller) => controller.loop(), ) .shake(duration: 700.ms) .shimmer(duration: 1000.ms) .then(delay: 2000.ms), ), ), ); }, ), ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/screen_section.dart
import 'package:flutter/material.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/utils/utils.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; import 'package:xno_game_ui/widgets/custom_text_field.dart'; class ScreenSection extends StatelessWidget { const ScreenSection({ super.key, required this.title, required this.bottons, required this.nameController, required this.rounds, required this.gameButton, required this.sameDevice, this.bottonsO, required this.join, }); final String title; final Widget bottons; final TextEditingController? nameController; final Widget? rounds; final Widget gameButton; final bool sameDevice; final Widget? bottonsO; final bool join; @override Widget build(BuildContext context) { double size = MediaQuery.of(context).size.width; return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ height50, CustomText( color: white, shadows: const [ Shadow( blurRadius: 10, color: white, ), ], text: title, fontSize: size < 600 ? 30 : 50, ), height20, bottons, if (sameDevice) Column( children: [ height30, CustomText( shadows: const [ Shadow( blurRadius: 20, color: white, ), ], text: S.current.playerO, fontSize: size < 600 ? 30 : 50, color: white, ), height10, bottonsO!, ], ), if (!sameDevice) Column( children: [ height20, Padding( padding: const EdgeInsets.symmetric(horizontal: 40), child: CustomTextField( controller: nameController!, validator: null, hintText: size < 600 ? S.current.nickname : S.current.enterNickname, ), ), ], ), height20, if (!join) rounds!, height20, gameButton, height20, goBackButton(context), ], ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/custom_text_field.dart
import 'package:flutter/material.dart'; import 'package:xno_game_ui/utils/constants.dart'; class CustomTextField extends StatelessWidget { final TextEditingController controller; final bool isRedyOnly; final String hintText; final String? Function(String?)? validator; const CustomTextField({ super.key, required this.controller, required this.hintText, this.isRedyOnly = false, required this.validator, }); @override Widget build(BuildContext context) { return Container( decoration: const BoxDecoration( color: backgroundColor, boxShadow: [ BoxShadow( color: white, blurRadius: 5, spreadRadius: 2, ), ], ), child: TextFormField( controller: controller, style: const TextStyle(fontSize: 15), validator: validator, textAlign: TextAlign.center, decoration: InputDecoration( errorStyle: const TextStyle( backgroundColor: backgroundColor, color: red, ), fillColor: backgroundColor, filled: true, hintText: hintText, ), readOnly: isRedyOnly, ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/screen_view.dart
import 'package:flutter/material.dart'; class ScreenView extends StatelessWidget { const ScreenView({ super.key, required this.child, this.height, this.width, }); final Widget child; final double? height; final double? width; @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Center( child: Padding( padding: EdgeInsets.symmetric( vertical: height ?? 30, horizontal: width ?? 10, ), child: child, ), ), ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/custom_text.dart
import 'package:flutter/material.dart'; class CustomText extends StatelessWidget { const CustomText({ super.key, required this.shadows, required this.text, required this.fontSize, this.color, this.textAlign, }); final List<Shadow> shadows; final String text; final double fontSize; final Color? color; final TextAlign? textAlign; @override Widget build(BuildContext context) { return Text( text, textAlign: textAlign ?? TextAlign.center, style: TextStyle( color: color ?? Colors.lightGreenAccent, fontSize: fontSize, fontWeight: FontWeight.bold, shadows: shadows, ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/widgets/change_language.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/provider/language_provider.dart'; import 'package:xno_game_ui/utils/constants.dart'; class ChangeLanguage extends StatelessWidget { const ChangeLanguage({super.key}); @override Widget build(BuildContext context) { final languageProvider = Provider.of<LanguageProvider>(context); return Padding( padding: const EdgeInsets.all(8), child: IconButton( onPressed: () => languageProvider.changeLanguage(), icon: const Icon( Icons.language, color: white, size: 24, ), tooltip: S.of(context).changeLanguage, ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/resources/socket_methods.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:socket_io_client/socket_io_client.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/resources/game_methods.dart'; import 'package:xno_game_ui/resources/socket_client.dart'; import 'package:xno_game_ui/screens/game_screen.dart'; import 'package:xno_game_ui/utils/utils.dart'; class SocketMethods { final _socketClient = SocketClient.intance.socket!; Socket get socketClient => _socketClient; // Emits void createRoom(String nickname, int color, int maxRounds) { if (nickname.isNotEmpty) { _socketClient.emit('createRoom', { 'nickname': nickname, 'color': color, 'maxRounds': maxRounds, }); } } void joinRoom(String nickname, String roomId, int color) { if (nickname.isNotEmpty && roomId.isNotEmpty) { _socketClient.emit('joinRoom', { 'nickname': nickname, 'roomId': roomId, 'color': color, }); } } void joinAuth(String roomId) { if (roomId.isNotEmpty) { _socketClient.emit('joinAuth', roomId); } } void sameDevice(int color1, int color2, int maxRounds) { _socketClient.emit('sameDevice', { 'color1': color1, 'color2': color2, 'maxRounds': maxRounds, }); } void tapGrid(int index, String roomId, List<String> displayElements) { if (displayElements[index] == '') { _socketClient.emit('tap', { 'index': index, 'roomId': roomId, }); } } void again(String roomId) { _socketClient.emit('again', roomId); } // Listeners void createRoomSuccessListener(BuildContext context) { _socketClient.on('createRoomSuccess', (room) { Provider.of<RoomDataProvider>(context, listen: false) .updateRoomData(room); Navigator.pushNamed(context, GameScreen.route); }); } void joinRoomSuccessListener(BuildContext context) { _socketClient.on('joinRoomSuccess', (room) { Provider.of<RoomDataProvider>(context, listen: false) .updateRoomData(room); Navigator.pushNamed(context, GameScreen.route); }); } void joinAuthSuccessListener(BuildContext context) { _socketClient.on('joinAuthSuccess', (room) { Provider.of<RoomDataProvider>(context, listen: false) .updateRoomData(room); }); } void sameDeviceSuccessListener(BuildContext context) { _socketClient.on('sameDeviceSuccess', (room) { Provider.of<RoomDataProvider>(context, listen: false) .updateRoomData(room); Navigator.pushNamed(context, GameScreen.route); }); } void errorOccurredListener(BuildContext context) { _socketClient.on('errorOccurred', (data) { showSnackBar(context, data, Colors.red); }); } void updateRoomListener(BuildContext context) { _socketClient.on('updateRoom', (data) { Provider.of<RoomDataProvider>(context, listen: false) .updateRoomData(data); }); } void updatePlayersStateListener(BuildContext context) { _socketClient.on('updatePlayers', (playerData) { Provider.of<RoomDataProvider>(context, listen: false).updatePlayer1( playerData[0], ); Provider.of<RoomDataProvider>(context, listen: false).updatePlayer2( playerData[1], ); }); } void tappedListener(BuildContext context) { _socketClient.on('tapped', (data) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>( context, listen: false, ); roomDataProvider.updateDisplayElements( data['index'], data['choice'], ); roomDataProvider.updateRoomData(data['room']); GameMethods().checkWinner(context, _socketClient); }); } void pointIncreaseListener(BuildContext context) { _socketClient.on('pointIncrease', (playerData) { var roomDataProvider = Provider.of<RoomDataProvider>(context, listen: false); if (playerData['socketID'] == roomDataProvider.player1.socketID) { roomDataProvider.updatePlayer1(playerData); } else { roomDataProvider.updatePlayer2(playerData); } }); } void endGameListener(BuildContext context) { _socketClient.on('endGame', (playerData) { var roomDataProvider = Provider.of<RoomDataProvider>(context, listen: false); if (playerData['socketID'] == roomDataProvider.player1.socketID) { roomDataProvider.updatePlayer1(playerData); } else { roomDataProvider.updatePlayer2(playerData); } showGameDialog( context, '${playerData['nickname']} won the game! 😎🥳🎉', roomId: playerData['roomID'], ); }); } void exitListener(BuildContext context) { _socketClient.on('exitSuccess', (data) { Navigator.of(context).popUntil((route) => false); showGameDialog( context, data.toString(), again: true, ); }); } void againListener(BuildContext context) { _socketClient.on('againSuccess', (room) { Provider.of<RoomDataProvider>(context, listen: false) .updateRoomData(room); Navigator.pop(context); }); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/resources/game_methods.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:socket_io_client/socket_io_client.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/models/player.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/utils/utils.dart'; class GameMethods { void checkWinner(BuildContext context, Socket? socketClient) async { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>( context, listen: false, ); String winner = ''; final List<List<int>> lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (var i = 0; i < lines.length; i++) { List<int> line = lines[i]; if (roomDataProvider.displayElements[line[0]] == roomDataProvider.displayElements[line[1]] && roomDataProvider.displayElements[line[0]] == roomDataProvider.displayElements[line[2]] && roomDataProvider.displayElements[line[0]] != '') { winner = roomDataProvider.displayElements[line[0]]; break; } else if (roomDataProvider.filledBoxes == 10 && winner == '') { showSnackBar( context, S.current.draw, white, ); await Future.delayed( const Duration(milliseconds: 500), ); // ignore: use_build_context_synchronously GameMethods().clearBoard(context); } } if (winner != '') { if (roomDataProvider.player1.playerType == winner && (roomDataProvider.player1.points) != roomDataProvider.roomData['maxRounds'].toInt()) { // ignore: use_build_context_synchronously showSnackBar( context, S.current.wonSms( roomDataProvider.player1.nickname, ), white, ); await Future.delayed( const Duration(milliseconds: 500), ); // ignore: use_build_context_synchronously GameMethods().clearBoard(context); if (socketClient != null) { socketClient.emit('winner', { 'winnerId': roomDataProvider.player1.socketID, 'roomId': roomDataProvider.roomData['_id'], }); } else { final newPoints = roomDataProvider.player1.points + 1; Player playerUpdate = Player( nickname: 'X', socketID: '', roomID: '', points: newPoints, playerType: 'X', color: roomDataProvider.player1.color, ); roomDataProvider.updatePlayer1(playerUpdate.toMap()); if (playerUpdate.points == roomDataProvider.roomData['maxRounds']) { // ignore: use_build_context_synchronously showGameDialog( context, S.current.winnerMessage( roomDataProvider.player1.nickname, ), ); } } } else if (roomDataProvider.player2.playerType == winner && (roomDataProvider.player2.points) != roomDataProvider.roomData['maxRounds'].toInt()) { // ignore: use_build_context_synchronously showSnackBar( context, S.current.wonSms( roomDataProvider.player2.nickname, ), white, ); await Future.delayed( const Duration(milliseconds: 500), ); // ignore: use_build_context_synchronously GameMethods().clearBoard(context); if (socketClient != null) { socketClient.emit('winner', { 'winnerId': roomDataProvider.player2.socketID, 'roomId': roomDataProvider.roomData['_id'], }); } else { final newPoints = roomDataProvider.player2.points + 1; Player playerUpdate = Player( nickname: 'O', socketID: '', roomID: '', points: newPoints, playerType: 'O', color: roomDataProvider.player2.color, ); roomDataProvider.updatePlayer2(playerUpdate.toMap()); if (playerUpdate.points == roomDataProvider.roomData['maxRounds']) { // ignore: use_build_context_synchronously showGameDialog( context, S.current.winnerMessage( roomDataProvider.player2.nickname, ), ); } } } } } void clearBoard(BuildContext context, {bool again = false}) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>( context, listen: false, ); for (int i = 0; i < roomDataProvider.displayElements.length; i++) { roomDataProvider.updateDisplayElements(i, ''); } roomDataProvider.setFilledBoxesToZero(); /* if (again) { Navigator.pop(context); } */ } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/resources/socket_client.dart
import 'package:socket_io_client/socket_io_client.dart' as io; import 'package:xno_game_ui/utils/constants.dart'; class SocketClient { io.Socket? socket; static SocketClient? _instance; SocketClient._internal() { socket = io.io(uri, <String, dynamic>{ 'transports': ['websocket'], 'autoConnect': false, }); socket!.connect(); } static SocketClient get intance { _instance ??= SocketClient._internal(); return _instance!; } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/models/player.dart
// Player model class Player { final String nickname; final String socketID; final String roomID; final double points; final String playerType; final int color; Player({ required this.nickname, required this.socketID, required this.roomID, required this.points, required this.playerType, required this.color, }); Map<String, dynamic> toMap() { return { 'nickname': nickname, 'socketID': socketID, 'roomID': roomID, 'points': points, 'playerType': playerType, 'color': color, }; } factory Player.fromMap(Map<String, dynamic> map) { return Player( nickname: map['nickname'] ?? '', socketID: map['socketID'] ?? '', roomID: map['roomID'] ?? '', points: map['points']?.toDouble() ?? 0.0, playerType: map['playerType'] ?? '', color: map['color']?.toInt() ?? 0, ); } Player copyWith({ String? nickname, String? socketID, String? roomID, double? points, String? playerType, int? color, }) { return Player( nickname: nickname ?? this.nickname, socketID: socketID ?? this.socketID, roomID: roomID ?? this.roomID, points: points ?? this.points, playerType: playerType ?? this.playerType, color: color ?? this.color, ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/provider/room_data_provider.dart
import 'package:flutter/cupertino.dart'; import 'package:xno_game_ui/models/player.dart'; class RoomDataProvider extends ChangeNotifier { Map<String, dynamic> _roomData = {}; final List<String> _displayElements = [ '', '', '', '', '', '', '', '', '', ]; int _filledBoxes = 0; Player _player1 = Player( nickname: '', socketID: '', roomID: '', points: 0, playerType: 'X', color: 0, ); Player _player2 = Player( nickname: '', socketID: '', roomID: '', points: 0, playerType: 'O', color: 0, ); Map<String, dynamic> get roomData => _roomData; List<String> get displayElements => _displayElements; Player get player1 => _player1; Player get player2 => _player2; int get filledBoxes => _filledBoxes; void updateRoomData(Map<String, dynamic> data) { _roomData = data; notifyListeners(); } void updatePlayer1(Map<String, dynamic> player1Data) { _player1 = Player.fromMap(player1Data); notifyListeners(); } void updatePlayer2(Map<String, dynamic> player2Data) { _player2 = Player.fromMap(player2Data); notifyListeners(); } void updateDisplayElements(int index, String choice) { _displayElements[index] = choice; _filledBoxes += 1; notifyListeners(); } void setFilledBoxesToZero() { _filledBoxes = 0; } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/provider/language_provider.dart
import 'package:flutter/material.dart'; class LanguageProvider extends ChangeNotifier { bool language = true; String get whatLanguage => language ? 'es' : 'en'; void changeLanguage() { language = !language; notifyListeners(); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/utils/constants.dart
import 'package:flutter/material.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; // Colors const backgroundColor = Color.fromARGB(255, 40, 38, 51); const white = Colors.white; const purple = Colors.deepPurpleAccent; const pink = Colors.pinkAccent; const red = Colors.redAccent; const yellow = Colors.yellowAccent; const orange = Colors.orange; const green = Colors.greenAccent; const cyan = Colors.cyanAccent; const blue = Colors.blueAccent; const playerColor = [ purple, pink, red, orange, yellow, green, cyan, blue, ]; final uri = dotenv.env['CONNECT']!; // Spacers const height5 = SizedBox(height: 5); const height10 = SizedBox(height: 10); const height20 = SizedBox(height: 20); const height30 = SizedBox(height: 30); const height40 = SizedBox(height: 40); const height50 = SizedBox(height: 50); const width50 = SizedBox(width: 50);
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/utils/utils.dart
import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/resources/game_methods.dart'; import 'package:xno_game_ui/resources/socket_methods.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/widgets/custom_button.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; final SocketMethods _socketMethods = SocketMethods(); Widget bottonsPressedFunction( bool player, List<bool> isColorPressed, Function function, ) { List<Widget> colores = []; for (var i = 0; i < playerColor.length; i++) { colores.add( CustomButton( onTap: () => function(i), backColor: isColorPressed[i] ? playerColor[i] : backgroundColor, text: player ? 'X' : 'O', color: isColorPressed[i] ? backgroundColor : playerColor[i], ) .animate( onPlay: (controller) => isColorPressed[i] == true ? controller.loop() : null, ) .shake(duration: 700.ms) .shimmer(duration: 1000.ms) .then(delay: 500.ms), ); } return Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 48.0, ), child: Wrap( direction: Axis.horizontal, alignment: WrapAlignment.center, spacing: 10, runSpacing: 10, children: colores, ), ); } CustomButton goBackButton(BuildContext context) => CustomButton( onTap: () => Navigator.of(context).pop(), text: S.of(context).goBack, ); Widget selectRounds( Function buttonFunction1, Function buttonFunction2, int maxRounds, double size, ) { return Column( children: [ CustomText( color: white, shadows: const [ Shadow( blurRadius: 10, color: white, ), ], text: S.current.rounds, fontSize: size < 600 ? 20 : 40, ), Padding( padding: const EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CustomButton( onTap: () => buttonFunction1(maxRounds), text: '5', backColor: maxRounds == 5 ? blue : backgroundColor, color: maxRounds == 5 ? backgroundColor : blue, ) .animate( onPlay: (controller) => maxRounds == 5 ? controller.loop() : null, ) .shake(duration: 700.ms) .shimmer(duration: 1000.ms) .then(delay: 500.ms), width50, CustomButton( onTap: () => buttonFunction2(maxRounds), text: '10', backColor: maxRounds == 10 ? pink : backgroundColor, color: maxRounds == 10 ? backgroundColor : pink, ) .animate( onPlay: (controller) => maxRounds == 10 ? controller.loop() : null, ) .shake(duration: 700.ms) .shimmer(duration: 1000.ms) .then(delay: 500.ms), ], ), ), ], ); } void showSnackBar(BuildContext context, String content, Color color) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( shape: const StadiumBorder(), backgroundColor: backgroundColor, duration: const Duration(seconds: 2), elevation: 10, dismissDirection: DismissDirection.horizontal, content: CustomText( text: content, color: color, fontSize: 25, textAlign: TextAlign.center, shadows: [ Shadow( blurRadius: 60, color: color, ), ], ), ), ); } void showGameDialog( BuildContext context, String text, { String roomId = '', bool again = false, }) { showDialog( context: context, builder: (context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context, listen: false); return AlertDialog( elevation: 20, actionsPadding: const EdgeInsets.symmetric( vertical: 16, horizontal: 8, ), title: CustomText( text: text, fontSize: 15, shadows: const [ Shadow( blurRadius: 10, color: white, ), ], color: white, ), actions: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (!again) CustomButton( onTap: () { GameMethods().clearBoard( context, again: true, ); if (roomId != '') { _socketMethods.again(roomId); } else { roomDataProvider.updatePlayer1( { 'nickname': 'X', 'socketID': '', 'roomID': '', 'points': 0, 'playerType': 'X', 'color': roomDataProvider.player1.color, 'uid': '', }, ); roomDataProvider.updatePlayer2( { 'nickname': 'O', 'socketID': '', 'roomID': '', 'points': 0, 'playerType': 'O', 'color': roomDataProvider.player2.color, 'uid': '', }, ); Navigator.pop(context); } }, text: S.current.againButton, color: blue, ), if (again) CustomText( text: '${S.current.leave}✌️😢', fontSize: 15, shadows: const [ Shadow( blurRadius: 10, color: white, ), ], color: white, ), const SizedBox( height: 20, ), ], ), ], ), ], ); }, ); }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/screens/game_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/resources/socket_methods.dart'; import 'package:xno_game_ui/screens/game_board.dart'; import 'package:xno_game_ui/views/waiting_lobby.dart'; class GameScreen extends StatefulWidget { const GameScreen({super.key}); static String route = '/game'; @override State<GameScreen> createState() => _GameScreenState(); } class _GameScreenState extends State<GameScreen> { final SocketMethods _socketMethods = SocketMethods(); @override void initState() { super.initState(); _socketMethods.updateRoomListener(context); _socketMethods.updatePlayersStateListener(context); _socketMethods.pointIncreaseListener(context); _socketMethods.endGameListener(context); _socketMethods.againListener(context); _socketMethods.exitListener(context); } @override Widget build(BuildContext context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context); return Scaffold( body: roomDataProvider.roomData['isJoin'] ? const WaintingLobby() : /* ListView( children: [ SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const Scoreboard(), const TicTactoeBoard(), Padding( padding: const EdgeInsets.all(24.0), child: CustomText( text: '${roomDataProvider.roomData['turn']['nickname']}\'s turn', textAlign: TextAlign.center, fontSize: 30, shadows: [ Shadow( blurRadius: 10, color: playerColor[ roomDataProvider.roomData['turn']['color']], ), ], color: playerColor[roomDataProvider.roomData['turn'] ['color']], ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms) .then(delay: 2000.ms), ), ], ), ), ], ), */ const GameBoard(), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/screens/main_menu_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/screens/create_room_screen.dart'; import 'package:xno_game_ui/screens/join_room_screen.dart'; import 'package:xno_game_ui/screens/same_device_screen.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/widgets/change_language.dart'; import 'package:xno_game_ui/widgets/custom_button.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; import 'package:xno_game_ui/widgets/screen_view.dart'; class MainMenuScreen extends StatefulWidget { static String route = '/main-menu'; static Route<void> mainMenu() { return MaterialPageRoute( builder: (context) => const MainMenuScreen(), ); } const MainMenuScreen({super.key}); @override State<MainMenuScreen> createState() => _MainMenuScreenState(); } class _MainMenuScreenState extends State<MainMenuScreen> { void createRoom(BuildContext context) { Navigator.pushNamed(context, CreateRoomScreen.route); } void joinRoom(BuildContext context) { Navigator.pushNamed(context, JoinRoomScreen.route); } void sameDevice(BuildContext context) { Navigator.pushNamed(context, SameDeviceScreen.route); } @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Scaffold( floatingActionButton: const ChangeLanguage(), floatingActionButtonLocation: FloatingActionButtonLocation.endTop, body: ScreenView( height: 120, width: 8, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ height20, CustomText( shadows: const [ Shadow( blurRadius: 60, color: pink, ), ], text: 'X\'s', fontSize: size.width < 400 ? 60 : 80, color: pink, textAlign: TextAlign.start, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height5, CustomText( color: yellow, shadows: const [ Shadow( blurRadius: 60, color: yellow, ), ], text: '&', fontSize: size.width < 400 ? 40 : 60, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height5, CustomText( shadows: const [ Shadow( blurRadius: 60, color: blue, ), ], text: 'O\'s', fontSize: size.width < 400 ? 60 : 80, color: cyan, textAlign: TextAlign.end, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height40, CustomButton( onTap: () => createRoom(context), text: S.of(context).createRoom, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height30, CustomButton( onTap: () => joinRoom(context), text: S.of(context).joinRoom, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height30, CustomButton( onTap: () => sameDevice(context), text: S.of(context).sameDevice, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), ], ), ), ); /* return ScreenView( height: 120, width: 8, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ height50, CustomText( shadows: const [ Shadow( blurRadius: 60, color: pink, ), ], text: 'X\'s', fontSize: size.width < 400 ? 60 : 80, color: pink, textAlign: TextAlign.start, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height5, CustomText( color: yellow, shadows: const [ Shadow( blurRadius: 60, color: yellow, ), ], text: '&', fontSize: size.width < 400 ? 40 : 60, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height5, CustomText( shadows: const [ Shadow( blurRadius: 60, color: blue, ), ], text: 'O\'s', fontSize: size.width < 400 ? 60 : 80, color: cyan, textAlign: TextAlign.end, ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height40, CustomButton( onTap: () => createRoom(context), text: 'Create Room', ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height30, CustomButton( onTap: () => joinRoom(context), text: 'Join Room', ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), height30, CustomButton( onTap: () => sameDevice(context), text: 'Same Device', ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms, delay: 2000.ms), ], ), ); */ } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/screens/create_room_screen.dart
import 'package:flutter/material.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/resources/socket_methods.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/utils/utils.dart'; import 'package:xno_game_ui/widgets/custom_button.dart'; import 'package:xno_game_ui/widgets/screen_view.dart'; import 'package:xno_game_ui/widgets/screen_section.dart'; class CreateRoomScreen extends StatefulWidget { static String route = '/create-room'; const CreateRoomScreen({super.key}); @override State<CreateRoomScreen> createState() => _CreateRoomScreenState(); } class _CreateRoomScreenState extends State<CreateRoomScreen> { final TextEditingController _nameController = TextEditingController(); final SocketMethods _socketMethods = SocketMethods(); int color = -1; List<bool> isColorPressed = [ false, false, false, false, false, false, false, false ]; int maxRounds = 0; @override void initState() { super.initState(); _socketMethods.createRoomSuccessListener(context); _socketMethods.updateRoomListener(context); } @override void dispose() { super.dispose(); _nameController.dispose(); } @override Widget build(BuildContext context) { double size = MediaQuery.of(context).size.width; return ScreenView( child: ScreenSection( title: S.current.createRoom, bottons: bottonsPressedFunction( true, isColorPressed, (int i) => setState(() { for (var j = 0; j < playerColor.length; j++) { isColorPressed[j] = false; } isColorPressed[i] = true; color = i; }), ), nameController: _nameController, rounds: selectRounds( (int maxRoundsSelected) => setState(() { maxRounds = 5; }), (int maxRoundsSelected) => setState(() { maxRounds = 10; }), maxRounds, size, ), gameButton: CustomButton( onTap: () { if (color != -1) { if (maxRounds != 0) { _socketMethods.createRoom( _nameController.text, color, maxRounds, ); } else { showSnackBar( context, S.current.maxRoundsMessage, red, ); } } else { showSnackBar( context, S.current.chooseColorMessage, red, ); } }, text: S.current.createButton, ), sameDevice: false, join: false, ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/screens/game_board.dart
import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/views/scoreboard.dart'; import 'package:xno_game_ui/views/tictactoe_board.dart'; import 'package:xno_game_ui/views/tictactoe_board_same.dart'; import 'package:xno_game_ui/widgets/custom_text.dart'; class GameBoard extends StatefulWidget { const GameBoard({super.key}); static String route = '/game-board'; @override State<GameBoard> createState() => _GameBoardState(); } class _GameBoardState extends State<GameBoard> { @override Widget build(BuildContext context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context); return Scaffold( body: ListView( children: [ SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ const Scoreboard(), roomDataProvider.player1.roomID == '' ? const TicTactoeBoardSame() : const TicTactoeBoard(), Padding( padding: const EdgeInsets.all(16.0), child: CustomText( text: S.current .turn(roomDataProvider.roomData['turn']['nickname']), textAlign: TextAlign.center, fontSize: 30, shadows: [ Shadow( blurRadius: 10, color: playerColor[roomDataProvider.roomData['turn'] ['color']], ), ], color: playerColor[roomDataProvider.roomData['turn']['color']], ) .animate( onPlay: (controller) => controller.loop(), ) .shimmer(duration: 1000.ms) .then(delay: 2000.ms), ), ], ), ), ], ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/screens/join_room_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/resources/socket_methods.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/utils/utils.dart'; import 'package:xno_game_ui/widgets/custom_button.dart'; import 'package:xno_game_ui/widgets/custom_text_field.dart'; import 'package:xno_game_ui/widgets/screen_view.dart'; import 'package:xno_game_ui/widgets/screen_section.dart'; class JoinRoomScreen extends StatefulWidget { static String route = '/join-room'; const JoinRoomScreen({super.key}); @override State<JoinRoomScreen> createState() => _JoinRoomScreenState(); } class _JoinRoomScreenState extends State<JoinRoomScreen> { final TextEditingController _nameController = TextEditingController(); final TextEditingController _gameIdController = TextEditingController(); final SocketMethods _socketMethods = SocketMethods(); final _formKey = GlobalKey<FormState>(); int color = -1; List<bool> isColorPressed = [ false, false, false, false, false, false, false, false ]; bool join = true; @override void initState() { super.initState(); _socketMethods.joinRoomSuccessListener(context); _socketMethods.updateRoomListener(context); _socketMethods.updatePlayersStateListener(context); _socketMethods.errorOccurredListener(context); _socketMethods.joinAuthSuccessListener(context); } @override void dispose() { super.dispose(); _nameController.dispose(); _gameIdController.dispose(); } @override Widget build(BuildContext context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context); Size size = MediaQuery.of(context).size; return ScreenView( height: join ? size.height * 0.45 : 50, child: join ? Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Form( key: _formKey, child: CustomTextField( controller: _gameIdController, hintText: size.width < 600 ? S.current.gameId : S.current.gameIdEx, validator: (val) { if (val == null || val.isEmpty) { return S.current.gameIdEmpty; } final isValid = RegExp(r'^[0-9a-fA-F]{24}$').hasMatch(val); if (!isValid) { return S.current.gameIdValidate; } return null; }, ), ), height20, CustomButton( onTap: () { if (_formKey.currentState!.validate()) { _socketMethods.joinAuth(_gameIdController.text); setState(() { join = !join; }); } }, text: S.current.joinButton, ), height20, goBackButton(context), ], ) : ScreenSection( title: S.current.joinRoom, bottons: bottonsPressedFunction( false, isColorPressed, (int i) => setState(() { for (var j = 0; j < playerColor.length; j++) { isColorPressed[j] = false; } isColorPressed[i] = true; color = i; }), ), nameController: _nameController, rounds: null, gameButton: CustomButton( onTap: () { if (color != (roomDataProvider.roomData['turn']['color']) && color != -1) { _socketMethods.joinRoom( _nameController.text, _gameIdController.text, color, ); } else if (color == -1) { showSnackBar( context, S.current.chooseColorMessage, blue, ); } else { showSnackBar( context, S.current.sorrySms( roomDataProvider.roomData['turn']['nickname'], ), red, ); } }, text: S.current.gameOnMessage, ), sameDevice: false, join: true, ), ); } }
0
mirrored_repositories/xno-game-ui/lib
mirrored_repositories/xno-game-ui/lib/screens/same_device_screen.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:xno_game_ui/generated/l10n.dart'; import 'package:xno_game_ui/models/player.dart'; import 'package:xno_game_ui/provider/room_data_provider.dart'; import 'package:xno_game_ui/screens/game_board.dart'; import 'package:xno_game_ui/utils/constants.dart'; import 'package:xno_game_ui/utils/utils.dart'; import 'package:xno_game_ui/widgets/custom_button.dart'; import 'package:xno_game_ui/widgets/screen_view.dart'; import 'package:xno_game_ui/widgets/screen_section.dart'; class SameDeviceScreen extends StatefulWidget { static String route = '/same-device'; const SameDeviceScreen({super.key}); @override State<SameDeviceScreen> createState() => _SameDeviceScreenState(); } class _SameDeviceScreenState extends State<SameDeviceScreen> { int color1 = -1; int color2 = -1; List<bool> isColor1Pressed = [ false, false, false, false, false, false, false, false ]; List<bool> isColor2Pressed = [ false, false, false, false, false, false, false, false ]; int maxRounds = 0; @override Widget build(BuildContext context) { RoomDataProvider roomDataProvider = Provider.of<RoomDataProvider>(context, listen: false); double size = MediaQuery.of(context).size.width; return ScreenView( child: ScreenSection( title: S.current.playerX, bottons: bottonsPressedFunction( true, isColor1Pressed, (int i) => setState(() { for (var j = 0; j < playerColor.length; j++) { isColor1Pressed[j] = false; } isColor1Pressed[i] = true; color1 = i; }), ), nameController: null, rounds: selectRounds( (int maxRoundsSelected) => setState(() { maxRounds = 5; }), (int maxRoundsSelected) => setState(() { maxRounds = 10; }), maxRounds, size, ), gameButton: CustomButton( onTap: () { if (color2 != color1 && color1 != -1 && color2 != -1 && maxRounds != 0) { if (maxRounds != 0) { Player player1 = Player( nickname: 'X', socketID: '', roomID: '', points: 0, playerType: 'X', color: color1, ); Player player2 = Player( nickname: 'O', socketID: '', roomID: '', points: 0, playerType: 'O', color: color2, ); final Map<String, dynamic> room = { 'turn': player1.toMap(), 'turnIndex': 0, 'maxRounds': maxRounds, }; roomDataProvider.updateRoomData(room); roomDataProvider.updatePlayer1(player1.toMap()); roomDataProvider.updatePlayer2(player2.toMap()); Navigator.pushNamed(context, GameBoard.route); } } else if (color1 == color2) { if (color1 == -1) { showSnackBar( context, S.current.bothColor, red, ); } else { showSnackBar( context, S.current.differentColor, yellow, ); } } else if (color1 == -1) { showSnackBar( context, S.current.xColor, blue, ); } else if (color2 == -1) { showSnackBar( context, S.current.oColor, blue, ); } else if (maxRounds == 0) { showSnackBar( context, S.current.maxRoundsMessage, red, ); } }, text: S.current.gameOnMessage, ), sameDevice: true, bottonsO: bottonsPressedFunction( false, isColor2Pressed, (int i) => setState(() { for (var j = 0; j < playerColor.length; j++) { isColor2Pressed[j] = false; } isColor2Pressed[i] = true; color2 = i; }), ), join: false, ), ); } }
0
mirrored_repositories/xno-game-ui
mirrored_repositories/xno-game-ui/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:xno_game_ui/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/shadermask_example
mirrored_repositories/shadermask_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; import 'package:shadermask_example/widget/image/basic_image_widget.dart'; import 'package:shadermask_example/widget/image/image_shader_widget.dart'; import 'package:shadermask_example/widget/text/basic_text_widget.dart'; import 'package:shadermask_example/widget/text/image_text_widget.dart'; import 'package:shadermask_example/widget/image/linear_gradient_widget.dart'; import 'package:shadermask_example/widget/text/linear_text_widget.dart'; import 'package:shadermask_example/widget/image/radial_gradient_widget.dart'; import 'package:shadermask_example/widget/text/radial_text_widget.dart'; import 'package:shadermask_example/widget/image/sweep_gradient_widget.dart'; import 'package:shadermask_example/widget/text/sweep_text_widget.dart'; import 'package:shadermask_example/widget/tabbar_widget.dart'; final urlImage = 'https://images.unsplash.com/photo-1584361853901-dd1904bb7987?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); runApp(MyApp()); } class MyApp extends StatelessWidget { static final String title = 'ShaderMask'; @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData( scaffoldBackgroundColor: Colors.black, primarySwatch: Colors.indigo, ), home: MainPage(title: title), ); } class MainPage extends StatefulWidget { final String title; const MainPage({ @required this.title, }); @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { int selectedIndex = 0; @override Widget build(BuildContext context) => Scaffold( body: TabBarWidget( children: selectedIndex == 0 ? [ BasicImageWidget(), LinearGradientWidget(), RadialGradientWidget(), SweepGradientWidget(), ImageShaderWidget(), ] : [ BasicTextWidget(), LinearTextWidget(), RadialTextWidget(), SweepTextWidget(), ImageTextWidget(), ], tabs: [ Tab(icon: Icon(Icons.close), text: 'No Effect'), Tab(icon: Icon(Icons.home), text: 'Linear Gradient'), Tab(icon: Icon(Icons.touch_app), text: 'Radial Gradient'), Tab(icon: Icon(Icons.swipe), text: 'Sweep Gradient'), Tab(icon: Icon(Icons.zoom_out), text: 'ImageShader'), ], title: widget.title, ), bottomNavigationBar: BottomNavigationBar( backgroundColor: Theme.of(context).primaryColor, selectedItemColor: Colors.white, unselectedItemColor: Colors.white38, currentIndex: selectedIndex, onTap: (index) => setState(() => selectedIndex = index), items: [ BottomNavigationBarItem( icon: Icon(Icons.image), label: 'Image', ), BottomNavigationBarItem( icon: Icon(Icons.text_fields), label: 'Text', ), ], ), ); }
0
mirrored_repositories/shadermask_example/lib
mirrored_repositories/shadermask_example/lib/widget/tabbar_widget.dart
import 'package:flutter/material.dart'; class TabBarWidget extends StatelessWidget { final String title; final List<Tab> tabs; final List<Widget> children; const TabBarWidget({ Key key, @required this.title, @required this.tabs, @required this.children, }) : super(key: key); @override Widget build(BuildContext context) => DefaultTabController( length: tabs.length, child: Scaffold( appBar: AppBar( title: Text(title), centerTitle: true, flexibleSpace: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.purple, Colors.blue], begin: Alignment.bottomRight, end: Alignment.topLeft, ), ), ), bottom: TabBar( isScrollable: true, indicatorColor: Colors.white, indicatorWeight: 5, tabs: tabs, ), elevation: 20, titleSpacing: 20, ), body: TabBarView(children: children), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/text/linear_text_widget.dart
import 'package:flutter/material.dart'; class LinearTextWidget extends StatelessWidget { @override Widget build(BuildContext context) => Container( child: Center( child: ShaderMask( blendMode: BlendMode.srcIn, shaderCallback: (rect) => LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.red, Colors.green, ], ).createShader(rect), child: Text( 'This is a text with LinearGradient Shader', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold), ), ), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/text/basic_text_widget.dart
import 'package:flutter/material.dart'; class BasicTextWidget extends StatelessWidget { @override Widget build(BuildContext context) => Center( child: Text( 'This is a text with RadialGradient Shader', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold, ), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/text/sweep_text_widget.dart
import 'dart:math' as math; import 'package:flutter/material.dart'; class SweepTextWidget extends StatelessWidget { @override Widget build(BuildContext context) => Container( child: ShaderMask( blendMode: BlendMode.srcIn, shaderCallback: (rect) => SweepGradient( startAngle: 0, endAngle: math.pi * 2, colors: [ Colors.red, Colors.purple, ], ).createShader(rect), child: Center( child: Text( 'This is a text with SweepGradient Shader', textAlign: TextAlign.center, style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), ), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/text/radial_text_widget.dart
import 'package:flutter/material.dart'; class RadialTextWidget extends StatelessWidget { @override Widget build(BuildContext context) => Container( child: ShaderMask( blendMode: BlendMode.srcIn, shaderCallback: (rect) => RadialGradient( colors: [ Colors.yellow, Colors.red, ], ).createShader(rect), child: Center( child: Text( 'This is a text with RadialGradient Shader', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold, ), ), ), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/text/image_text_widget.dart
import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:shadermask_example/main.dart'; class ImageTextWidget extends StatelessWidget { Future<ui.Image> _loadImage() async { final imageBytes = await rootBundle.load('assets/example.jpg'); return decodeImageFromList(imageBytes.buffer.asUint8List()); } @override Widget build(BuildContext context) => Container( child: FutureBuilder<ui.Image>( future: _loadImage(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else { final image = snapshot.data; return ShaderMask( blendMode: BlendMode.srcIn, shaderCallback: (rect) => ImageShader( image, TileMode.mirror, TileMode.mirror, Matrix4.identity().storage, ), child: Center( child: Text( 'This is a text with ImageShader', textAlign: TextAlign.center, style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), ), ); } }, ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/image/sweep_gradient_widget.dart
import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:shadermask_example/main.dart'; class SweepGradientWidget extends StatelessWidget { @override Widget build(BuildContext context) => ShaderMask( blendMode: BlendMode.color, shaderCallback: (rect) => SweepGradient( startAngle: 0, endAngle: math.pi, colors: [ Colors.blue, Colors.red, ], transform: GradientRotation(math.pi / 2), ).createShader(rect), child: Image.network(urlImage, fit: BoxFit.cover), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/image/basic_image_widget.dart
import 'package:flutter/material.dart'; import '../../main.dart'; class BasicImageWidget extends StatelessWidget { @override Widget build(BuildContext context) => Image.network(urlImage, fit: BoxFit.cover); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/image/linear_gradient_widget.dart
import 'package:flutter/material.dart'; import 'package:shadermask_example/main.dart'; class LinearGradientWidget extends StatelessWidget { @override Widget build(BuildContext context) => Container( child: ShaderMask( blendMode: BlendMode.color, shaderCallback: (rect) => LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Colors.red, Colors.green, ], ).createShader(rect), child: Image.network(urlImage, fit: BoxFit.cover), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/image/radial_gradient_widget.dart
import 'package:flutter/material.dart'; import 'package:shadermask_example/main.dart'; class RadialGradientWidget extends StatelessWidget { @override Widget build(BuildContext context) => Container( child: ShaderMask( blendMode: BlendMode.screen, shaderCallback: (rect) => RadialGradient( radius: 0.8, colors: [ Colors.blue, Colors.red, ], ).createShader(rect), child: Image.network(urlImage, fit: BoxFit.cover), ), ); }
0
mirrored_repositories/shadermask_example/lib/widget
mirrored_repositories/shadermask_example/lib/widget/image/image_shader_widget.dart
import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:shadermask_example/main.dart'; class ImageShaderWidget extends StatelessWidget { @override Widget build(BuildContext context) => Container( child: FutureBuilder<ui.Image>( future: loadImage(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else { final image = snapshot.data; return ShaderMask( blendMode: BlendMode.overlay, shaderCallback: (rect) => ImageShader( image, TileMode.mirror, TileMode.mirror, Matrix4.identity().storage, ), child: Image.network(urlImage, fit: BoxFit.cover), ); } }, ), ); Future<ui.Image> loadImage() async { final imageBytes = await rootBundle.load('assets/example.jpg'); return decodeImageFromList(imageBytes.buffer.asUint8List()); } }
0