repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home/widgets/list_products_home.dart
import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/response/response_products_home.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/screen/products/details_product_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class ListProductsForHome extends StatelessWidget { const ListProductsForHome({Key? key}):super(key: key); @override Widget build(BuildContext context) { final productBloc = BlocProvider.of<ProductBloc>(context); return FutureBuilder<List<ListProducts>>( future: productServices.listProductsHome(), builder: (context, snapshot) { return !snapshot.hasData ? Column( children: const [ ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), SizedBox(height: 10.0), ShimmerFrave(), ], ) : GridView.builder( physics: NeverScrollableScrollPhysics(), shrinkWrap: true, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 25, mainAxisSpacing: 20, mainAxisExtent: 220 ), itemCount: snapshot.data!.length, itemBuilder: (context, i) => Container( padding: EdgeInsets.all(10.0), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(25.0), ), child: GestureDetector( onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => DetailsProductPage(product: snapshot.data![i]))), child: Stack( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: Hero( tag: snapshot.data![i].uidProduct.toString(), child: Image.network(Environment.baseUrl + snapshot.data![i].picture, height: 120) ), ), TextFrave(text: snapshot.data![i].nameProduct, fontSize: 17, overflow: TextOverflow.ellipsis), TextFrave(text: '\$ ${snapshot.data![i].price}', fontSize: 16 ), ], ), Positioned( right: 0, child: snapshot.data![i].isFavorite == 1 ? InkWell( onTap: () => productBloc.add( OnAddOrDeleteProductFavoriteEvent(uidProduct: snapshot.data![i].uidProduct.toString())), child: const Icon(Icons.favorite_rounded, color: Colors.red), ) : InkWell( onTap: () => productBloc.add( OnAddOrDeleteProductFavoriteEvent(uidProduct: snapshot.data![i].uidProduct.toString())), child: Icon(Icons.favorite_outline_rounded) ) ), ], ), ), ), ); }, ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/home/widgets/header_home.dart
import 'package:animate_do/animate_do.dart'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/cart/payment_card_page.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; class HeaderHome extends StatelessWidget { const HeaderHome({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FadeInLeft( child: BlocBuilder<UserBloc, UserState>( buildWhen: (previous, current) => previous != current, builder: (context, state) => state.user != null ? Row( children: [ state.user!.image != '' ? CircleAvatar( radius: 20, backgroundImage: NetworkImage(Environment.baseUrl + state.user!.image), ) : CircleAvatar( radius: 20, backgroundColor: ColorsFrave.primaryColorFrave, child: TextFrave(text: state.user!.users.substring(0,2).toUpperCase(), fontWeight: FontWeight.bold, color: Colors.white,), ), const SizedBox(width: 5.0), TextFrave(text: state.user!.users, fontSize: 18,) ], ) : const SizedBox() ), ), InkWell( borderRadius: BorderRadius.circular(20.0), onTap: () => Navigator.of(context).pushAndRemoveUntil(routeSlide(page: PaymentCardPage()), (_) => false), child: Stack( children: [ FadeInRight( child: Container( height: 32, width: 32, child: SvgPicture.asset('assets/bolso-negro.svg', height: 25 ) ) ), Positioned( left: 0, top: 12, child: FadeInDown( child: Container( height: 20, width: 20, decoration: BoxDecoration( color: ColorsFrave.primaryColorFrave, shape: BoxShape.circle ), child: Center( child: BlocBuilder<ProductBloc, ProductState>( builder: (context, state) => state.amount == 0 ? TextFrave(text: '0', color: Colors.white, fontWeight: FontWeight.bold ) : TextFrave(text: '${state.products!.length}', color: Colors.white, fontWeight: FontWeight.bold ) ) ), ), ), ) ], ), ) ], ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/start/start_home_page.dart
import 'package:e_commers/presentation/components/widgets.dart'; import 'package:flutter/material.dart'; class StartHomePage extends StatelessWidget { @override Widget build(BuildContext context){ final size = MediaQuery.of(context).size; return Scaffold( backgroundColor: Color(0xff1E4DD8), body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( flex: 4, child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( radius: 70, child: ClipRRect( borderRadius: BorderRadius.circular(120), child: Image.asset('assets/fraved_logo.png') ), ), const SizedBox(height: 15.0), const TextFrave( text: 'Fraved Shop', isTitle: true, fontSize: 32, fontWeight: FontWeight.bold, color: Colors.white ), const TextFrave( text: 'All your products in your hands', fontSize: 20, isTitle: true, color: Colors.white70 ), ], ), ), ), Expanded( flex: 2, child: Container( child: ListView( physics: const BouncingScrollPhysics(), children: [ BtnFrave( text: 'Sign in with email', isTitle: true, height: 55, fontSize: 18, border: 60, fontWeight: FontWeight.w600, colorText: Colors.white, backgroundColor: Color(0xff1C2834), onPressed: () => Navigator.of(context).pushNamed('signInPage'), width: size.width ), const SizedBox(height: 15.0), BtnFrave( text: 'Sign in with Google', colorText: Colors.black87, fontSize: 18, border: 60, isTitle: true, fontWeight: FontWeight.w600, backgroundColor: Color(0xFFE9EFF9), width: size.width ), const SizedBox(height: 10.0), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFrave( text: 'Don\'t have an account?', fontSize: 17, color: Colors.white70, ), TextButton( child: TextFrave(text: 'Sign up', fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white), onPressed: () => Navigator.of(context).pushNamed('signUpPage'), ), ], ), ], ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products/details_product_page.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/product.dart'; import 'package:e_commers/domain/models/response/response_products_home.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/helpers/helpers.dart'; import 'package:e_commers/presentation/screen/products/widgets/app_bar_product.dart'; import 'package:e_commers/presentation/screen/products/widgets/cover_product.dart'; import 'package:e_commers/presentation/screen/products/widgets/rating_product.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:google_fonts/google_fonts.dart'; class DetailsProductPage extends StatefulWidget{ final ListProducts product; DetailsProductPage({ required this.product }); @override State<DetailsProductPage> createState() => _DetailsProductPageState(); } class _DetailsProductPageState extends State<DetailsProductPage> { @override Widget build(BuildContext context){ final productBloc = BlocProvider.of<ProductBloc>(context); final size = MediaQuery.of(context).size; return BlocListener<ProductBloc, ProductState>( listener: (context, state){ if( state is LoadingProductState ){ modalLoadingShort(context); }else if( state is FailureProductState ){ Navigator.pop(context); errorMessageSnack(context, state.error); }else if( state is SuccessProductState ){ Navigator.pop(context); setState(() {}); } else if ( state is SetAddProductToCartState ){ modalSuccess(context, 'Product Added', onPressed: () => Navigator.pop(context)); } }, child: Scaffold( backgroundColor: Colors.white, body: SafeArea( child: Stack( children: [ ListView( padding: EdgeInsets.only(top: 10.0, bottom: 100.0), children: [ AppBarProduct( nameProduct: widget.product.nameProduct, uidProduct: widget.product.uidProduct.toString(), isFavorite: widget.product.isFavorite ), const SizedBox(height: 20.0), CoverProduct( uidProduct: widget.product.uidProduct.toString(), imageProduct: widget.product.picture ), const SizedBox(height: 15.0), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Wrap( children: [ TextFrave(text: widget.product.nameProduct, fontSize: 25, fontWeight: FontWeight.bold ) ], ), ), const SizedBox(height: 10.0), RatingProduct(), const SizedBox(height: 10.0), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Container( height: 50, child: Row( children: [ SvgPicture.asset('Assets/garantia.svg'), RichText( text: TextSpan( children: [ TextSpan(text: 'This product has a ', style: GoogleFonts.getFont('Roboto', color: Colors.black, fontSize: 18)), TextSpan(text: 'delivery guarantee', style: GoogleFonts.getFont('Roboto', color: Colors.blue, fontSize: 18)) ] ), ) ], ) ), ), const SizedBox(height: 20.0), Padding( padding: const EdgeInsets.only(left: 20, right: 215), child: Container( padding: EdgeInsets.symmetric(vertical: 3.0, horizontal: 5.0), decoration: BoxDecoration( color: Color(0xff8956FF), borderRadius: BorderRadius.circular(5.0) ), child: const TextFrave(text: 'Shipping normally', fontSize: 18, color: Colors.white ), ), ), const SizedBox(height: 20.0), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: SizedBox( child: Row( children: const [ TextFrave(text: 'Available. ', fontSize: 18, color: Colors.green ), TextFrave(text: 'In Stock', fontSize: 18, ), ], ), ), ), const SizedBox(height: 20.0), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: const TextFrave(text: 'Description', fontSize: 20, fontWeight: FontWeight.bold ), ), const SizedBox(height: 10.0), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Wrap( children: [ TextFrave(text: widget.product.description, fontSize: 17) ], ), ), const SizedBox(height: 30.0 ), Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: const TextFrave(text: 'Payment methods', fontSize: 20, fontWeight: FontWeight.bold ), ), Container( height: 60, color: Color(0xfff5f5f5), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SvgPicture.asset('Assets/visa.svg', height: 60), SvgPicture.asset('Assets/mastercard.svg', height: 60,), SvgPicture.asset('Assets/american express.svg', height: 60,), SvgPicture.asset('Assets/paypal.svg', height: 55 ), ], ), ) ], ), Positioned( bottom: 0, child: Container( height: 75, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow(color: Colors.grey[200]!, blurRadius: 15, spreadRadius: 15) ] ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( alignment: Alignment.center, height: 55, width: size.width * .45, child: TextFrave(text: '\$ ${widget.product.price}', fontSize: 22, fontWeight: FontWeight.bold), ), // SizedBox(width: 15.0), Container( height: 55, width: size.width * .45, decoration: BoxDecoration( color: ColorsFrave.primaryColorFrave, borderRadius: BorderRadius.circular(25.0) ), child: TextButton( style: TextButton.styleFrom( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50.0)) ), child: const TextFrave(text: 'Add to cart', fontSize: 20, color: Colors.white, fontWeight: FontWeight.w500 ), onPressed: (){ final productSelect = ProductCart( uidProduct: widget.product.uidProduct.toString(), image: widget.product.picture, name: widget.product.nameProduct, price: widget.product.price.toDouble(), amount: 1 ); productBloc.add( OnAddProductToCartEvent( productSelect )); }, ), ) ], ), ), ) ], ), ), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products/widgets/rating_product.dart
import 'package:e_commers/presentation/components/widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; class RatingProduct extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.symmetric(horizontal: 20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( height: 50, width: 160, child: RatingBarIndicator( rating: 4, itemCount: 5, itemSize: 30.0, physics: BouncingScrollPhysics(), itemBuilder: (context, _) => const Icon( Icons.star, color: Colors.amber), ), ), const TextFrave(text: '124 Reviews', fontSize: 17, color: Colors.grey) ], ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products/widgets/cover_product.dart
import 'package:e_commers/data/env/env.dart'; import 'package:flutter/material.dart'; class CoverProduct extends StatelessWidget { final String imageProduct; final String uidProduct; const CoverProduct({required this.uidProduct, required this.imageProduct}); @override Widget build(BuildContext context) { return Hero( tag: '$uidProduct', child: Container( height: 250, width: MediaQuery.of(context).size.width, child: Image.network(Environment.baseUrl+ imageProduct), ), ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/screen/products/widgets/app_bar_product.dart
import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AppBarProduct extends StatelessWidget { final String nameProduct; final String uidProduct; final int isFavorite; const AppBarProduct({ Key? key, required this.nameProduct, required this.uidProduct, required this.isFavorite }):super(key: key); @override Widget build(BuildContext context) { final productBloc = BlocProvider.of<ProductBloc>(context); return Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ InkWell( borderRadius: BorderRadius.circular(50.0), onTap: () => Navigator.pop(context), child: CircleAvatar( backgroundColor: Color(0xffF3F4F6), radius: 24, child: Icon(Icons.arrow_back_ios_rounded, color: Colors.black ), ), ), Container( width: 250, child: TextFrave(text: nameProduct, overflow: TextOverflow.ellipsis, fontSize: 19, color: Colors.grey) ), CircleAvatar( backgroundColor: Color(0xffF5F5F5), radius: 24, child: IconButton( icon: isFavorite == 1 ? Icon(Icons.favorite_rounded, color: Colors.red ) : Icon(Icons.favorite_border_rounded, color: Colors.black ), onPressed: () => productBloc.add( OnAddOrDeleteProductFavoriteEvent(uidProduct: uidProduct)), ), ), ], ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/helpers.dart
import 'package:animate_do/animate_do.dart'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/domain/blocs/blocs.dart'; import 'package:e_commers/domain/models/response/response_categories_home.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:e_commers/presentation/components/shimmer_frave.dart'; import 'package:e_commers/presentation/components/widgets.dart'; import 'package:e_commers/presentation/themes/colors_frave.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:image_picker/image_picker.dart'; import 'package:permission_handler/permission_handler.dart'; part 'animation_route.dart'; part 'modal_success.dart'; part 'modal_loading.dart'; part 'error_message.dart'; part 'modal_warning.dart'; part 'loading_upload.dart'; part 'modal_add_cart.dart'; part 'access_permission.dart'; part 'modal_picture.dart'; part 'modal_loading_short.dart'; part 'modal_categories.dart';
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/error_message.dart
part of 'helpers.dart'; void errorMessageSnack(BuildContext context, String error){ ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: TextFrave(text: error, color: Colors.white), backgroundColor: Colors.red ) ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_add_cart.dart
part of 'helpers.dart'; void modalAddCartSuccess( BuildContext context, String image ){ showDialog( context: context, barrierColor: Colors.white60, builder: (context) { return BounceInDown( child: AlertDialog( backgroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), content: Container( height: 130, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const TextFrave(text: 'Frave Shop', fontSize: 22, color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w500), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.network(Environment.baseUrl + image, height: 80.0,), SizedBox(width: 10.0), BounceInLeft(child: Icon(Icons.check_circle_outlined, color: Colors.green, size: 80 )), ], ), ], ), ), ), ); }, ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_loading.dart
part of 'helpers.dart'; void modalLoading(BuildContext context, String text){ showDialog( context: context, barrierDismissible: false, barrierColor: Colors.black45, builder: (context) => AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)), content: SizedBox( height: 100, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ TextFrave(text: 'Frave ', color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w500 ), TextFrave(text: 'Shop', fontWeight: FontWeight.w500), ], ), const Divider(), const SizedBox(height: 10.0), Row( children:[ const CircularProgressIndicator( color: ColorsFrave.primaryColorFrave), const SizedBox(width: 15.0), TextFrave(text: text) ], ), ], ), ), ), ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/loading_upload.dart
part of 'helpers.dart'; void loadinUploadFile(BuildContext context){ showDialog( context: context, barrierColor: Colors.white54, builder: (context) { return AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)), title: TextFrave(text: 'Uploading Image', color: ColorsFrave.primaryColorFrave), content: Container( height: 200, width: 350, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(15.0) ), child: TweenAnimationBuilder( tween: Tween(begin: 0.0, end: 1.0), duration: Duration(seconds: 1500), builder: (context, double value, child) { int percent = ( value * 100 ).ceil(); return Container( width: 230, height: 230, child: Stack( children: [ Align( alignment: Alignment.center, child: ShaderMask( shaderCallback: (rect){ return SweepGradient( startAngle: 0.0, endAngle: 3.14 * 2, stops: [ value, value ], center: Alignment.center, colors: [ ColorsFrave.primaryColorFrave, Colors.transparent ] ).createShader(rect); }, child: Container( height: 230, width: 230, decoration: BoxDecoration( color: ColorsFrave.primaryColorFrave, shape: BoxShape.circle ), ), ), ), Align( alignment: Alignment.center, child: Container( height: 160, width: 160, decoration: BoxDecoration( color: Colors.white, shape: BoxShape.circle ), child: Center(child: TextFrave(text: '$percent %', fontSize: 40,)), ), ) ], ), ); }, ), ), ); }, ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_warning.dart
part of 'helpers.dart'; void modalWarning(BuildContext context, String text){ showDialog( context: context, barrierDismissible: false, barrierColor: Colors.black12, builder: (context) => AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), content: SizedBox( height: 250, child: Column( children: [ Row( children: const[ TextFrave(text: 'Frave ', color: Colors.amber, fontWeight: FontWeight.w500 ), TextFrave(text: 'Shop', fontWeight: FontWeight.w500), ], ), const Divider(), const SizedBox(height: 10.0), Container( height: 90, width: 90, decoration: const BoxDecoration( shape: BoxShape.circle, gradient: LinearGradient( begin: Alignment.centerLeft, colors: [ Colors.white, Colors.amber ] ) ), child: Container( margin: const EdgeInsets.all(10.0), decoration: const BoxDecoration( shape: BoxShape.circle, color: Colors.amber ), child: const Icon(Icons.priority_high_rounded, color: Colors.white, size: 38), ), ), const SizedBox(height: 35.0), TextFrave(text: text, fontSize: 17, fontWeight: FontWeight.w400 ), const SizedBox(height: 20.0), InkWell( onTap: () => Navigator.pop(context), child: Container( alignment: Alignment.center, height: 35, width: 150, decoration: BoxDecoration( color: Colors.amber, borderRadius: BorderRadius.circular(5.0) ), child: const TextFrave(text: 'Ok', fontSize: 17, color: Colors.black87 ), ), ) ], ), ), ), ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/access_permission.dart
part of 'helpers.dart'; class AccessPermission { final ImagePicker _picker = ImagePicker(); Future<void> permissionAccessGalleryOrCameraForProfile(PermissionStatus status, BuildContext context, ImageSource source) async { switch (status){ case PermissionStatus.granted: final XFile? imagePath = await _picker.pickImage(source: source); if( imagePath != null ){ BlocProvider.of<UserBloc>(context).add( OnUpdateProfilePictureEvent(imagePath.path) ); } break; case PermissionStatus.denied: case PermissionStatus.restricted: case PermissionStatus.limited: break; case PermissionStatus.permanentlyDenied: openAppSettings(); break; } } Future<void> permissionAccessGalleryOrCameraForProduct(PermissionStatus status, BuildContext context, ImageSource source) async { switch (status){ case PermissionStatus.granted: final XFile? imagePath = await _picker.pickImage(source: source); if( imagePath != null ){ BlocProvider.of<ProductBloc>(context).add( OnSelectPathImageProductEvent(imagePath.path) ); } break; case PermissionStatus.denied: case PermissionStatus.restricted: case PermissionStatus.limited: break; case PermissionStatus.permanentlyDenied: openAppSettings(); break; } } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_loading_short.dart
part of 'helpers.dart'; void modalLoadingShort(BuildContext context){ showDialog( context: context, barrierDismissible: false, barrierColor: Colors.black45, builder: (context) => AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)), insetPadding: const EdgeInsets.symmetric(horizontal: 150), content: const SizedBox( height: 40, width: 40, child: CircularProgressIndicator( color: ColorsFrave.primaryColorFrave), ), ), ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/animation_route.dart
part of 'helpers.dart'; Route routeSlide({required Widget page, Curve curved = Curves.easeInOut}) { return PageRouteBuilder( transitionDuration: Duration(milliseconds: 450), pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => page, transitionsBuilder: (context, animation, secondaryAnimation, child) { final curvedAnimation = CurvedAnimation(parent: animation, curve: curved); return SlideTransition( position: Tween<Offset>(begin: Offset(0.0, 1.0), end: Offset.zero).animate(curvedAnimation), child: child, ); }, ); } Route routeFade({ required Widget page, Curve curved = Curves.easeInOut }){ return PageRouteBuilder( transitionDuration: const Duration(milliseconds: 350), pageBuilder: (context, animation, secondaryAnimation) => page, transitionsBuilder: (context, animation, secondaryAnimation, child) { final curvedAnimation = CurvedAnimation(parent: animation, curve: curved); return FadeTransition( opacity: curvedAnimation, child: child, ); }, ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_success.dart
part of 'helpers.dart'; void modalSuccess(BuildContext context, String text, {required VoidCallback onPressed}){ showDialog( context: context, barrierDismissible: false, barrierColor: Colors.black12, builder: (context) { return AlertDialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)), content: SizedBox( height: 250, child: Column( children: [ Row( children: const[ TextFrave(text: 'Frave ', color: ColorsFrave.primaryColorFrave, fontWeight: FontWeight.w500 ), TextFrave(text: 'Shop', fontWeight: FontWeight.w500), ], ), const Divider(), const SizedBox(height: 10.0), Container( height: 90, width: 90, decoration: const BoxDecoration( shape: BoxShape.circle, gradient: LinearGradient( begin: Alignment.centerLeft, colors: [ Colors.white, ColorsFrave.primaryColorFrave ] ) ), child: Container( margin: const EdgeInsets.all(10.0), decoration: const BoxDecoration( shape: BoxShape.circle, color: ColorsFrave.primaryColorFrave ), child: const Icon(Icons.check, color: Colors.white, size: 38), ) ), const SizedBox(height: 35.0), TextFrave(text: text, fontSize: 17, fontWeight: FontWeight.w400 ), const SizedBox(height: 20.0), InkWell( onTap: onPressed, child: Container( alignment: Alignment.center, height: 35, width: 150, decoration: BoxDecoration( color: ColorsFrave.primaryColorFrave, borderRadius: BorderRadius.circular(5.0) ), child: const TextFrave(text: 'Done', color: Colors.white, fontSize: 17 ), ), ) ], ), ), ); }, ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_categories.dart
part of 'helpers.dart'; modalCategoies(BuildContext context, Size size) { final categoryBloc = BlocProvider.of<CategoryBloc>(context); showModalBottomSheet( context: context, barrierColor: Colors.black38, shape: const RoundedRectangleBorder(borderRadius: BorderRadiusDirectional.vertical(top: Radius.circular(20.0))), backgroundColor: Colors.white, builder: (context) => Container( height: size.height * .6, width: size.width, decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadiusDirectional.vertical(top: Radius.circular(20.0)) ), child: Padding( padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Align( alignment: Alignment.center, child: Container( height: 5, width: 50, decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular(50.0) ), ), ), const SizedBox(height: 20.0), const TextFrave(text: 'Select Category'), const SizedBox(height: 20.0), Expanded( child: FutureBuilder<List<Categories>>( future: productServices.getAllCategories(), builder: (context, snapshot) => snapshot.hasData ? ListView.builder( itemCount: snapshot.data!.length, itemBuilder: (context, i) => InkWell( onTap: () => categoryBloc.add( OnSelectUidCategoryEvent(snapshot.data![i].uidCategory, snapshot.data![i].category )), child: Padding( padding: const EdgeInsets.only(bottom: 10.0), child: Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(left: 10.0), height: 45, width: size.width, // color: Colors.grey[100], child: BlocBuilder<CategoryBloc, CategoryState>( builder: (context, state) => Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ TextFrave(text: snapshot.data![i].category), state.uidCategory == snapshot.data![i].uidCategory ? const Icon(Icons.check_rounded, color: ColorsFrave.primaryColorFrave) : const SizedBox() ], ), ), ), ), ), ) : const ShimmerFrave() ) ) ], ), ), ), ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/modal_picture.dart
part of 'helpers.dart'; void modalSelectPicture({ required BuildContext context, Function()? onPressedImage, Function()? onPressedPhoto }) { showModalBottomSheet( context: context, barrierColor: Colors.black12, backgroundColor: Colors.transparent, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25.0)), builder: (context) => Container( height: 170, margin: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 20.0), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(25.0) ), child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFrave(text: 'Update profile picture', fontWeight: FontWeight.w500, fontSize: 16), const SizedBox(height: 10.0), SizedBox( width: double.infinity, child: TextButton( onPressed: onPressedImage, style: TextButton.styleFrom( padding: const EdgeInsets.only(left: 0, top: 10, bottom: 10), foregroundColor: Colors.grey ), child: Align( alignment: Alignment.centerLeft, child: Row( children: const [ Icon(Icons.wallpaper_rounded, color: Colors.black87), SizedBox(width: 10.0), TextFrave(text: 'Select from gallery', fontSize: 17), ], )) ), ), SizedBox( width: double.infinity, child: TextButton( onPressed: onPressedPhoto, style: TextButton.styleFrom( padding: const EdgeInsets.only(left: 0, top: 10, bottom: 10), foregroundColor: Colors.grey ), child: Align( alignment: Alignment.centerLeft, child: Row( children: const [ Icon(Icons.photo_camera_outlined, color: Colors.black87), SizedBox(width: 10.0), TextFrave(text: 'Take picture', fontSize: 17), ], )) ), ), ], ), ), ), ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation
mirrored_repositories/ECommerce-Products-Flutter/lib/presentation/helpers/validation_form.dart
import 'package:form_field_validator/form_field_validator.dart'; final validatedEmail = MultiValidator([ RequiredValidator(errorText: 'Email ID is required'), EmailValidator(errorText: 'Enter a valid Email ID') ]); final passwordValidator = MultiValidator([ RequiredValidator(errorText: 'Password is required'), MinLengthValidator(8, errorText: 'Password must be to least 8 digits long') ]); final passwordRepeatValidator = MultiValidator([ RequiredValidator(errorText: 'Repeat Password is required'), ]);
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/blocs.dart
export 'package:e_commers/domain/blocs/user/user_bloc.dart'; export 'package:e_commers/domain/blocs/General/general_bloc.dart'; export 'package:e_commers/domain/blocs/category/category_bloc.dart'; export 'package:e_commers/domain/blocs/Auth/auth_bloc.dart'; export 'package:e_commers/domain/blocs/Product/product_bloc.dart'; export 'package:e_commers/domain/blocs/Cart/cart_bloc.dart';
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/cart/cart_event.dart
part of 'cart_bloc.dart'; @immutable abstract class CartEvent {} class OnSelectCardEvent extends CartEvent { final CreditCardFrave creditCardFrave; OnSelectCardEvent(this.creditCardFrave); } class OnCancelCart extends CartEvent {} class OnMakePaymentEvent extends CartEvent { final String amount; final CreditCardFrave creditCardFrave; OnMakePaymentEvent({ required this.amount, required this.creditCardFrave }); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/cart/cart_bloc.dart
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:e_commers/domain/models/card/credit_card_frave.dart'; import 'package:meta/meta.dart'; part 'cart_event.dart'; part 'cart_state.dart'; class CartBloc extends Bloc<CartEvent, CartState> { CartBloc() : super(CartInitial()){ on<OnSelectCardEvent>(_selectCard); on<OnMakePaymentEvent>(_makePayment); } Future<void> _selectCard( OnSelectCardEvent event, Emitter<CartState> emit ) async { emit( SetActiveCardState(active: true, creditCard: event.creditCardFrave) ); } Future<void> _makePayment( OnMakePaymentEvent event, Emitter<CartState> emit ) async { try { emit(LoadingPaymentState()); // final mesAnio = event.creditCardFrave.expiracyDate.split('/'); // final resp = await stripeService.payWithCardExists( // amount: event.amount, // currency: state.currency, // creditCard: CreditCard( // number: event.creditCardFrave.cardNumber, // expMonth: int.parse(mesAnio[0]), // expYear: int.parse(mesAnio[1]), // ) // ); // if( resp.ok ){ // emit(SuccessPaymentState()); // } else { // emit(FailurePaymentState(resp.msg)); // } } catch (e) { emit(FailurePaymentState(e.toString())); } } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/cart/cart_state.dart
part of 'cart_bloc.dart'; @immutable abstract class CartState { final String totalAmount; final String currency; final bool? cardActive; final CreditCardFrave? creditCardFrave; const CartState({ this.totalAmount = '00.0', this.currency = 'USD', this.cardActive, this.creditCardFrave }); // String get amountPayString => '${ ( this.totalAmount * 100 ).floor() }'; } class CartInitial extends CartState { CartInitial():super(cardActive: false); } class LoadingPaymentState extends CartState {} class SuccessPaymentState extends CartState {} class FailurePaymentState extends CartState { final String err; FailurePaymentState(this.err); } class SetActiveCardState extends CartState { final bool active; final CreditCardFrave creditCard; SetActiveCardState({required this.active, required this.creditCard}): super(cardActive: active, creditCardFrave: creditCard); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/user/user_event.dart
part of 'user_bloc.dart'; @immutable abstract class UserEvent {} class OnAddNewUser extends UserEvent { final String username; final String email; final String password; OnAddNewUser(this.username, this.email, this.password); } class OnGetUserEvent extends UserEvent {} class OnUpdateProfilePictureEvent extends UserEvent { final String pathProfile; OnUpdateProfilePictureEvent(this.pathProfile); } class OnUpdateInformationUserEvent extends UserEvent { final String firstname; final String lastname; final String number; final String street; final String reference; OnUpdateInformationUserEvent(this.firstname, this.lastname, this.number, this.street, this.reference); } class OnUpdateStreetAdressEvent extends UserEvent { final String street; final String reference; OnUpdateStreetAdressEvent(this.street, this.reference); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/user/user_state.dart
part of 'user_bloc.dart'; @immutable abstract class UserState { final User? user; UserState({ this.user, }); } class UserInitial extends UserState {} class SetUserState extends UserState { final User user; SetUserState({ required this.user}): super(user: user); } class LoadingUserState extends UserState {} class SuccessUserState extends UserState {} class FailureUserState extends UserState { final error; FailureUserState(this.error); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/user/user_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:e_commers/domain/models/response/response_user.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:meta/meta.dart'; part 'user_event.dart'; part 'user_state.dart'; class UserBloc extends Bloc<UserEvent, UserState> { UserBloc() : super(UserInitial()) { on<OnAddNewUser>(_addNewUser); on<OnGetUserEvent>(_getUser); on<OnUpdateProfilePictureEvent>(_updatePictureProfile); on<OnUpdateInformationUserEvent>(_updateInformationUser); on<OnUpdateStreetAdressEvent>(_updateStreetAddress); } Future<void> _getUser( OnGetUserEvent event, Emitter<UserState> emit ) async { final user = await userServices.getUserById(); emit( SetUserState(user: user)); } Future<void> _addNewUser( OnAddNewUser event, Emitter<UserState> emit ) async { try { emit(LoadingUserState()); final data = await userServices.addNewUser(event.username, event.email, event.password); if(data.resp){ emit( SuccessUserState()); }else{ emit(FailureUserState(data.message)); } } catch (e) { emit( FailureUserState(e.toString())); } } Future<void> _updatePictureProfile( OnUpdateProfilePictureEvent event, Emitter<UserState> emit ) async { try { emit( LoadingUserState()); final data = await userServices.updatePictureProfile(event.pathProfile); if(data.resp){ final user = await userServices.getUserById(); emit(SetUserState(user: user)); }else{ emit(FailureUserState(data.message)); } } catch (e) { emit(FailureUserState(e.toString())); } } Future<void> _updateInformationUser( OnUpdateInformationUserEvent event, Emitter<UserState> emit ) async { try { emit(LoadingUserState()); final data = await userServices.updateInformationUser(event.firstname, event.lastname, event.number, event.street, event.reference); if(data.resp){ final user = await userServices.getUserById(); emit( SetUserState(user: user)); }else{ emit(FailureUserState(data.message)); } } catch (e) { emit(FailureUserState(e.toString())); } } Future<void> _updateStreetAddress( OnUpdateStreetAdressEvent event, Emitter<UserState> emit ) async { try { emit(LoadingUserState()); final data = await userServices.updateStreetAddress(event.street, event.reference); if(data.resp){ final user = await userServices.getUserById(); emit( SetUserState(user: user)); }else{ emit(FailureUserState(data.message)); } } catch (e) { emit(FailureUserState(e.toString())); } } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/product/product_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:e_commers/domain/models/product.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:meta/meta.dart'; part 'product_event.dart'; part 'product_state.dart'; class ProductBloc extends Bloc<ProductEvent, ProductState> { List<ProductCart> product = []; ProductBloc() : super(ProductInitial()){ on<OnAddOrDeleteProductFavoriteEvent>(_addOrDeleteProductFavorite); on<OnAddProductToCartEvent>(_addProductToCart); on<OnDeleteProductToCartEvent>(_deleteProductCart); on<OnPlusQuantityProductEvent>(_plusQuantityProduct); on<OnSubtractQuantityProductEvent>(_subtractQuantityProduct); on<OnClearProductsEvent>(_clearProduct); on<OnSaveProductsBuyToDatabaseEvent>(_saveProductToDatabase); on<OnSelectPathImageProductEvent>(_selectImageForProduct); on<OnSaveNewProductEvent>(_addNewProduct); } Future<void> _addOrDeleteProductFavorite( OnAddOrDeleteProductFavoriteEvent event, Emitter<ProductState> emit ) async { try { emit(LoadingProductState()); final data = await productServices.addOrDeleteProductFavorite(event.uidProduct); if(data.resp){ emit(SuccessProductState()); }else{ emit(FailureProductState(data.message)); } } catch (e) { emit(FailureProductState(e.toString())); } } Future<void> _addProductToCart( OnAddProductToCartEvent event, Emitter<ProductState> emit ) async { final hasProduct = product.contains( event.product ); if( !hasProduct ){ product.add( event.product ); double sum = 0; product.forEach((e) => sum = sum + e.price ); emit( SetAddProductToCartState(products: product, total: sum, amount: product.length )); } } Future<void> _deleteProductCart( OnDeleteProductToCartEvent event, Emitter<ProductState> emit ) async { product.removeAt(event.index); double sum = 0; product.forEach((e) => sum = sum + e.price); emit( SetAddProductToCartState(products: product, total: sum, amount: product.length)); } Future<void> _plusQuantityProduct( OnPlusQuantityProductEvent event, Emitter<ProductState> emit ) async { product[event.plus].amount++; double total = 0; product.forEach((e) => total = total + (e.price * e.amount)); emit( SetAddProductToCartState(products: product, total: total, amount: product.length)); } Future<void> _subtractQuantityProduct( OnSubtractQuantityProductEvent event, Emitter<ProductState> emit ) async { product[event.subtract].amount--; double total = 0; product.forEach((e) => total = total - (e.price * e.amount)); emit( SetAddProductToCartState(products: product, total: total.abs(), amount: product.length)); } Future<void> _clearProduct( OnClearProductsEvent event, Emitter<ProductState> emit ) async { product.clear(); emit( ProductInitial() ); } Future<void> _saveProductToDatabase( OnSaveProductsBuyToDatabaseEvent event, Emitter<ProductState> emit ) async { try { emit(LoadingProductState()); final data = await productServices.saveOrderBuyProductToDatabase('Ticket', event.amount, event.product); if(data.resp){ emit(SuccessProductState()); }else{ emit(FailureProductState(data.message)); } } catch (e) { emit(FailureProductState(e.toString())); } } Future<void> _selectImageForProduct( OnSelectPathImageProductEvent event, Emitter<ProductState> emit ) async { emit( SetImageForProductState(event.image) ); } Future<void> _addNewProduct( OnSaveNewProductEvent event, Emitter<ProductState> emit ) async { try { emit(LoadingProductState()); final data = await productServices.addNewProduct(event.name, event.description, event.stock, event.price, event.uidCategory, event.image); if(data.resp){ emit(SuccessProductState()); }else{ emit(FailureProductState(data.message)); } } catch (e) { emit(FailureProductState(e.toString())); } } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/product/product_event.dart
part of 'product_bloc.dart'; @immutable abstract class ProductEvent {} class OnAddOrDeleteProductFavoriteEvent extends ProductEvent{ final String uidProduct; OnAddOrDeleteProductFavoriteEvent({required this.uidProduct}); } class OnAddProductToCartEvent extends ProductEvent { final ProductCart product; OnAddProductToCartEvent(this.product); } class OnDeleteProductToCartEvent extends ProductEvent { final int index; OnDeleteProductToCartEvent(this.index); } class OnPlusQuantityProductEvent extends ProductEvent { final int plus; OnPlusQuantityProductEvent(this.plus); } class OnSubtractQuantityProductEvent extends ProductEvent { final int subtract; OnSubtractQuantityProductEvent(this.subtract); } class OnClearProductsEvent extends ProductEvent {} class OnSaveProductsBuyToDatabaseEvent extends ProductEvent { final String amount; final List<ProductCart> product; OnSaveProductsBuyToDatabaseEvent(this.amount, this.product); } class OnSelectPathImageProductEvent extends ProductEvent { final String image; OnSelectPathImageProductEvent(this.image); } class OnSaveNewProductEvent extends ProductEvent { final String name; final String description; final String stock; final String price; final String uidCategory; final String image; OnSaveNewProductEvent(this.name, this.description, this.stock, this.price, this.uidCategory, this.image); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/product/product_state.dart
part of 'product_bloc.dart'; @immutable abstract class ProductState { final List<ProductCart>? products; final double total; final int amount; final double delivery; final double insurance; final String? pathImage; ProductState({ this.products, this.total = 00.0, this.amount = 0, this.delivery = 15.0, this.insurance = 10.0, this.pathImage }); } class ProductInitial extends ProductState { ProductInitial(): super(products: [], total: 00.0, amount: 0); } class LoadingProductState extends ProductState {} class SuccessProductState extends ProductState {} class FailureProductState extends ProductState { final String error; FailureProductState(this.error); } class SetAddProductToCartState extends ProductState{ final List<ProductCart> products; final double total; final int amount; SetAddProductToCartState({ required this.products, required this.total, required this.amount }):super(products: products, total: total, amount: amount); } class SetImageForProductState extends ProductState { final String path; SetImageForProductState(this.path):super(pathImage: path); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/category/category_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:meta/meta.dart'; part 'category_event.dart'; part 'category_state.dart'; class CategoryBloc extends Bloc<CategoryEvent, CategoryState> { CategoryBloc() : super(CategoryInitial()) { on<OnSelectUidCategoryEvent>(_selectUidCategory); } Future<void> _selectUidCategory( OnSelectUidCategoryEvent event, Emitter<CategoryState> emit ) async { emit( SetSelectCategoryState(event.uidCategory, event.category) ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/category/category_event.dart
part of 'category_bloc.dart'; @immutable abstract class CategoryEvent {} class OnSelectUidCategoryEvent extends CategoryEvent { final int uidCategory; final String category; OnSelectUidCategoryEvent(this.uidCategory, this.category); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/category/category_state.dart
part of 'category_bloc.dart'; @immutable abstract class CategoryState { final int? uidCategory; final String? nameCategory; CategoryState({ this.uidCategory, this.nameCategory }); } class CategoryInitial extends CategoryState {} class SetSelectCategoryState extends CategoryState { final uid; final category; SetSelectCategoryState(this.uid, this.category):super(uidCategory: uid, nameCategory: category); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/general/general_bloc.dart
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:meta/meta.dart'; part 'general_event.dart'; part 'general_state.dart'; class GeneralBloc extends Bloc<GeneralEvent, GeneralState>{ GeneralBloc() : super(GeneralInitial()){ on<OnShowOrHideMenuEvent>(_showHideMenu ); } Future<void> _showHideMenu( OnShowOrHideMenuEvent event, Emitter<GeneralState> emit ) async { emit( SetMenuHomeState(menu: event.showMenu) ); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/general/general_event.dart
part of 'general_bloc.dart'; @immutable abstract class GeneralEvent {} class OnShowOrHideMenuEvent extends GeneralEvent { final bool showMenu; OnShowOrHideMenuEvent({required this.showMenu}); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/general/general_state.dart
part of 'general_bloc.dart'; @immutable abstract class GeneralState { final bool showMenuHome; GeneralState({ this.showMenuHome = true }); } class GeneralInitial extends GeneralState {} class SetMenuHomeState extends GeneralState{ final bool menu; SetMenuHomeState({required this.menu}) : super(showMenuHome: menu); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/auth/auth_bloc.dart
import 'dart:async'; import 'package:e_commers/data/local_storage/secure_storage.dart'; import 'package:e_commers/domain/services/services.dart'; import 'package:meta/meta.dart'; import 'package:bloc/bloc.dart'; part 'auth_event.dart'; part 'auth_state.dart'; class AuthBloc extends Bloc<AuthEvent, AuthState> { AuthBloc() : super(AuthInitial()){ on<LoginEvent>( _login ); on<CheckLoginEvent>( _checkingLogin ); on<LogOutEvent>( _logout ); } Future<void> _login(LoginEvent event, Emitter<AuthState> emit ) async { try { emit(LoadingAuthState()); final data = await authServices.login(email: event.email, password: event.password); await Future.delayed(Duration(milliseconds: 350)); if( data.resp ){ await secureStorage.deleteSecureStorage(); await secureStorage.persistenToken(data.token); emit(SuccessAuthState()); } else { emit(FailureAuthState(error: data.message )); } } catch (e) { emit(FailureAuthState(error: e.toString())); } } Future<void> _checkingLogin( CheckLoginEvent event, Emitter<AuthState> emit ) async { try { emit(LoadingAuthState()); if( await secureStorage.readToken() != null ){ final data = await authServices.renewToken(); if( data.resp ){ await secureStorage.persistenToken(data.token); emit(SuccessAuthState()); }else{ await secureStorage.deleteSecureStorage(); emit(LogOutState()); } }else{ await secureStorage.deleteSecureStorage(); emit(LogOutState()); } } catch (e) { await secureStorage.deleteSecureStorage(); emit(LogOutState()); } } Future<void> _logout(LogOutEvent event, Emitter<AuthState> emit) async { secureStorage.deleteSecureStorage(); emit(LogOutState()); } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/auth/auth_event.dart
part of 'auth_bloc.dart'; @immutable abstract class AuthEvent {} class LoginEvent extends AuthEvent { final String email; final String password; LoginEvent(this.email, this.password); } class LogOutEvent extends AuthEvent {} class CheckLoginEvent extends AuthEvent {}
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/blocs/auth/auth_state.dart
part of 'auth_bloc.dart'; @immutable abstract class AuthState {} class AuthInitial extends AuthState {} class LogOutState extends AuthState {} class SuccessAuthState extends AuthState {} class LoadingAuthState extends AuthState {} class FailureAuthState extends AuthState { final String error; FailureAuthState({ required this.error}); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/product.dart
class ProductCart { final String uidProduct; final String image; final String name; double price; int amount; ProductCart({ required this.uidProduct, required this.image, required this.name, required this.price, required this.amount, }); Map<String, dynamic> toJson() { return { 'uidProduct': uidProduct, 'price' : price, 'amount': amount }; } }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_auth.dart
class ResponseAuth { ResponseAuth({ required this.resp, required this.message, required this.token, }); final bool resp; final String message; final String token; factory ResponseAuth.fromJson(Map<String, dynamic> json) => ResponseAuth( resp: json["resp"], message: json["message"], token: json["token"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_order_details.dart
class ResponseOrderDetails { const ResponseOrderDetails({ required this.resp, required this.msg, required this.orderDetails, }); final bool resp; final String msg; final List<OrderDetail> orderDetails; factory ResponseOrderDetails.fromJson(Map<String, dynamic> json) => ResponseOrderDetails( resp: json["resp"], msg: json["msg"], orderDetails: List<OrderDetail>.from(json["orderDetails"].map((x) => OrderDetail.fromJson(x))), ); } class OrderDetail { const OrderDetail({ required this.uidOrderDetails, required this.productId, required this.nameProduct, required this.picture, required this.quantity, required this.price, }); final int uidOrderDetails; final int productId; final String nameProduct; final String picture; final int quantity; final int price; factory OrderDetail.fromJson(Map<String, dynamic> json) => OrderDetail( uidOrderDetails: json["uidOrderDetails"], productId: json["product_id"], nameProduct: json["nameProduct"], picture: json["picture"], quantity: json["quantity"], price: json["price"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_slide_products.dart
class ResponseSlideProducts { const ResponseSlideProducts({ required this.resp, required this.message, required this.slideProducts, }); final bool resp; final String message; final List<SlideProduct> slideProducts; factory ResponseSlideProducts.fromJson(Map<String, dynamic> json) => ResponseSlideProducts( resp: json["resp"], message: json["message"], slideProducts: List<SlideProduct>.from(json["slideProducts"].map((x) => SlideProduct.fromJson(x))), ); } class SlideProduct { const SlideProduct({ required this.uidCarousel, required this.image, required this.category, }); final int uidCarousel; final String image; final String category; factory SlideProduct.fromJson(Map<String, dynamic> json) => SlideProduct( uidCarousel: json["uidCarousel"], image: json["image"], category: json["category"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_categories_home.dart
class ResponseCategoriesHome { const ResponseCategoriesHome({ required this.resp, required this.message, required this.categories, }); final bool resp; final String message; final List<Categories> categories; factory ResponseCategoriesHome.fromJson(Map<String, dynamic> json) => ResponseCategoriesHome( resp: json["resp"], message: json["message"], categories: List<Categories>.from(json["categories"].map((x) => Categories.fromJson(x))), ); } class Categories { const Categories({ required this.uidCategory, required this.category, required this.picture, required this.status, }); final int uidCategory; final String category; final String picture; final int status; factory Categories.fromJson(Map<String, dynamic> json) => Categories( uidCategory: json["uidCategory"], category: json["category"], picture: json["picture"], status: json["status"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_order_buy.dart
class ResponseOrderBuy { const ResponseOrderBuy({ required this.resp, required this.msg, required this.orderBuy, }); final bool resp; final String msg; final List<OrderBuy> orderBuy; factory ResponseOrderBuy.fromJson(Map<String, dynamic> json) => ResponseOrderBuy( resp: json["resp"], msg: json["msg"], orderBuy: List<OrderBuy>.from(json["orderBuy"].map((x) => OrderBuy.fromJson(x))), ); } class OrderBuy { const OrderBuy({ required this.uidOrderBuy, required this.userId, required this.receipt, required this.createdAt, required this.amount, }); final int uidOrderBuy; final int userId; final String receipt; final DateTime createdAt; final int amount; factory OrderBuy.fromJson(Map<String, dynamic> json) => OrderBuy( uidOrderBuy: json["uidOrderBuy"], userId: json["user_id"], receipt: json["receipt"], createdAt: DateTime.parse(json["created_at"]), amount: json["amount"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_default.dart
class ResponseDefault { const ResponseDefault({ required this.resp, required this.message, }); final bool resp; final String message; factory ResponseDefault.fromJson(Map<String, dynamic> json) => ResponseDefault( resp: json["resp"], message: json["message"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_user.dart
class ResponseUser { const ResponseUser({ required this.resp, required this.message, required this.user, }); final bool resp; final String message; final User user; factory ResponseUser.fromJson(Map<String, dynamic> json) => ResponseUser( resp: json["resp"], message: json["message"], user: User.fromJson(json["user"]), ); } class User { const User({ required this.uid, required this.firstName, required this.lastName, required this.phone, required this.address, required this.reference, required this.image, required this.users, required this.email, }); final int uid; final String firstName; final String lastName; final String phone; final String address; final String reference; final String image; final String users; final String email; factory User.fromJson(Map<String, dynamic> json) => User( uid: json["uid"] ?? 0, firstName: json["firstName"] ?? "", lastName: json["lastName"] ?? '', phone: json["phone"] ?? '', address: json["address"] ?? '', reference: json["reference"] ?? '', image: json["image"] ?? '', users: json["users"] ?? '', email: json["email"] ?? '', ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/response/response_products_home.dart
class ResponseProductsHome { const ResponseProductsHome({ required this.resp, required this.message, required this.listProducts, }); final bool resp; final String message; final List<ListProducts> listProducts; factory ResponseProductsHome.fromJson(Map<String, dynamic> json) => ResponseProductsHome( resp: json["resp"], message: json["message"], listProducts: List<ListProducts>.from(json["listProducts"].map((x) => ListProducts.fromJson(x))), ); } class ListProducts { const ListProducts({ required this.uidProduct, required this.nameProduct, required this.description, required this.codeProduct, required this.stock, required this.price, required this.status, required this.picture, required this.category, required this.isFavorite, }); final int uidProduct; final String nameProduct; final String description; final String codeProduct; final int stock; final double price; final String status; final String picture; final String category; final int isFavorite; factory ListProducts.fromJson(Map<String, dynamic> json) => ListProducts( uidProduct: json["uidProduct"], nameProduct: json["nameProduct"], description: json["description"], codeProduct: json["codeProduct"], stock: json["stock"], price: double.parse(json["price"].toString()), status: json["status"] ?? '', picture: json["picture"], category: json["category"], isFavorite: json["is_favorite"], ); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/card/credit_card_frave.dart
class CreditCardFrave { final String cardNumberHidden; final String cardNumber; final String brand; final String cvv; final String expiracyDate; final String cardHolderName; const CreditCardFrave({ required this.cardNumberHidden, required this.cardNumber, required this.brand, required this.cvv, required this.expiracyDate, required this.cardHolderName }); }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/models/stripe/PaymentIntentResponse.dart
import 'dart:convert'; PaymentIntentResponse paymentIntentResponseFromJson(String str) => PaymentIntentResponse.fromJson(json.decode(str)); String paymentIntentResponseToJson(PaymentIntentResponse data) => json.encode(data.toJson()); class PaymentIntentResponse { PaymentIntentResponse({ required this.id, required this.object, required this.amount, required this.amountCapturable, required this.amountReceived, this.application, this.applicationFeeAmount, this.canceledAt, this.cancellationReason, required this.captureMethod, required this.charges, required this.clientSecret, required this.confirmationMethod, required this.created, required this.currency, this.customer, this.description, this.invoice, this.lastPaymentError, required this.livemode, required this.metadata, this.nextAction, this.onBehalfOf, this.paymentMethod, required this.paymentMethodOptions, required this.paymentMethodTypes, this.receiptEmail, this.review, this.setupFutureUsage, this.shipping, this.source, this.statementDescriptor, this.statementDescriptorSuffix, required this.status, this.transferData, this.transferGroup, }); String id; String object; int amount; int amountCapturable; int amountReceived; dynamic application; dynamic applicationFeeAmount; dynamic canceledAt; dynamic cancellationReason; String captureMethod; Charges charges; String clientSecret; String confirmationMethod; int created; String currency; dynamic customer; dynamic description; dynamic invoice; dynamic lastPaymentError; bool livemode; Metadata metadata; dynamic nextAction; dynamic onBehalfOf; dynamic paymentMethod; PaymentMethodOptions paymentMethodOptions; List<String> paymentMethodTypes; dynamic receiptEmail; dynamic review; dynamic setupFutureUsage; dynamic shipping; dynamic source; dynamic statementDescriptor; dynamic statementDescriptorSuffix; String status; dynamic transferData; dynamic transferGroup; factory PaymentIntentResponse.fromJson(Map<String, dynamic> json) => PaymentIntentResponse( id: json["id"], object: json["object"], amount: json["amount"], amountCapturable: json["amount_capturable"], amountReceived: json["amount_received"], application: json["application"], applicationFeeAmount: json["application_fee_amount"], canceledAt: json["canceled_at"], cancellationReason: json["cancellation_reason"], captureMethod: json["capture_method"], charges: Charges.fromJson(json["charges"]), clientSecret: json["client_secret"], confirmationMethod: json["confirmation_method"], created: json["created"], currency: json["currency"], customer: json["customer"], description: json["description"], invoice: json["invoice"], lastPaymentError: json["last_payment_error"], livemode: json["livemode"], metadata: Metadata.fromJson(json["metadata"]), nextAction: json["next_action"], onBehalfOf: json["on_behalf_of"], paymentMethod: json["payment_method"], paymentMethodOptions: PaymentMethodOptions.fromJson(json["payment_method_options"]), paymentMethodTypes: List<String>.from(json["payment_method_types"].map((x) => x)), receiptEmail: json["receipt_email"], review: json["review"], setupFutureUsage: json["setup_future_usage"], shipping: json["shipping"], source: json["source"], statementDescriptor: json["statement_descriptor"], statementDescriptorSuffix: json["statement_descriptor_suffix"], status: json["status"], transferData: json["transfer_data"], transferGroup: json["transfer_group"], ); Map<String, dynamic> toJson() => { "id": id, "object": object, "amount": amount, "amount_capturable": amountCapturable, "amount_received": amountReceived, "application": application, "application_fee_amount": applicationFeeAmount, "canceled_at": canceledAt, "cancellation_reason": cancellationReason, "capture_method": captureMethod, "charges": charges.toJson(), "client_secret": clientSecret, "confirmation_method": confirmationMethod, "created": created, "currency": currency, "customer": customer, "description": description, "invoice": invoice, "last_payment_error": lastPaymentError, "livemode": livemode, "metadata": metadata.toJson(), "next_action": nextAction, "on_behalf_of": onBehalfOf, "payment_method": paymentMethod, "payment_method_options": paymentMethodOptions.toJson(), "payment_method_types": List<dynamic>.from(paymentMethodTypes.map((x) => x)), "receipt_email": receiptEmail, "review": review, "setup_future_usage": setupFutureUsage, "shipping": shipping, "source": source, "statement_descriptor": statementDescriptor, "statement_descriptor_suffix": statementDescriptorSuffix, "status": status, "transfer_data": transferData, "transfer_group": transferGroup, }; } class Charges { Charges({ required this.object, required this.data, required this.hasMore, required this.totalCount, required this.url, }); String object; List<dynamic> data; bool hasMore; int totalCount; String url; factory Charges.fromJson(Map<String, dynamic> json) => Charges( object: json["object"], data: List<dynamic>.from(json["data"].map((x) => x)), hasMore: json["has_more"], totalCount: json["total_count"], url: json["url"], ); Map<String, dynamic> toJson() => { "object": object, "data": List<dynamic>.from(data.map((x) => x)), "has_more": hasMore, "total_count": totalCount, "url": url, }; } class Metadata { Metadata(); factory Metadata.fromJson(Map<String, dynamic> json) => Metadata( ); Map<String, dynamic> toJson() => { }; } class PaymentMethodOptions { PaymentMethodOptions({ required this.card, }); Card card; factory PaymentMethodOptions.fromJson(Map<String, dynamic> json) => PaymentMethodOptions( card: Card.fromJson(json["card"]), ); Map<String, dynamic> toJson() => { "card": card.toJson(), }; } class Card { Card({ this.installments, this.network, required this.requestThreeDSecure, }); dynamic installments; dynamic network; String requestThreeDSecure; factory Card.fromJson(Map<String, dynamic> json) => Card( installments: json["installments"], network: json["network"], requestThreeDSecure: json["request_three_d_secure"], ); Map<String, dynamic> toJson() => { "installments": installments, "network": network, "request_three_d_secure": requestThreeDSecure, }; }
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/services/auth_services.dart
import 'dart:convert'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/data/local_storage/secure_storage.dart'; import 'package:e_commers/domain/models/response/response_auth.dart'; import 'package:http/http.dart' as http; class AuthServices { Future<ResponseAuth> login({ required String email, required String password }) async { final resp = await http.post(Uri.parse('${Environment.urlApi}/auth/login'), headers: { 'Accept' : 'application/json' }, body: { 'email' : email, 'passwordd' : password } ); return ResponseAuth.fromJson( jsonDecode( resp.body ) ); } Future<ResponseAuth> renewToken() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/auth/renew-login'), headers: { 'Accept' : 'application/json', 'xxx-token' : token!} ); return ResponseAuth.fromJson( jsonDecode( resp.body ) ); } } final authServices = AuthServices();
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/services/product_services.dart
import 'dart:convert'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/data/local_storage/secure_storage.dart'; import 'package:e_commers/domain/models/product.dart'; import 'package:e_commers/domain/models/response/response_categories_home.dart'; import 'package:e_commers/domain/models/response/response_default.dart'; import 'package:e_commers/domain/models/response/response_order_buy.dart'; import 'package:e_commers/domain/models/response/response_order_details.dart'; import 'package:e_commers/domain/models/response/response_products_home.dart'; import 'package:e_commers/domain/models/response/response_slide_products.dart'; import 'package:http/http.dart' as http; class ProductServices { Future<List<SlideProduct>> listProductsHomeCarousel() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/product/get-home-products-carousel'), headers: { 'Accept': 'application/json', 'xxx-token' : token! } ); return ResponseSlideProducts.fromJson(jsonDecode(resp.body)).slideProducts; } Future<List<Categories>> listCategoriesHome() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/category/get-all-categories'), headers: { 'Accept': 'application/json', 'xxx-token' : token! } ); return ResponseCategoriesHome.fromJson(jsonDecode(resp.body)).categories; } Future<List<ListProducts>> listProductsHome() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/product/get-products-home'), headers: { 'Accept': 'application/json', 'xxx-token' : token! } ); return ResponseProductsHome.fromJson(jsonDecode(resp.body)).listProducts; } Future<ResponseDefault> addOrDeleteProductFavorite(String uidProduct) async { final token = await secureStorage.readToken(); final resp = await http.post(Uri.parse('${Environment.urlApi}/product/like-or-unlike-product'), headers: { 'Accept' : 'application/json', 'xxx-token' : token! }, body: { 'uidProduct' : uidProduct } ); return ResponseDefault.fromJson( jsonDecode( resp.body ) ); } Future<List<Categories>> getAllCategories() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/category/get-all-categories'), headers: { 'Accept': 'application/json', 'xxx-token' : token! } ); return ResponseCategoriesHome.fromJson(jsonDecode(resp.body)).categories; } Future<List<ListProducts>> allFavoriteProducts() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/product/get-all-favorite'), headers: { 'Accept' : 'application/json', 'xxx-token' : token! }, ); return ResponseProductsHome.fromJson(jsonDecode(resp.body)).listProducts; } Future<List<ListProducts>> getProductsForCategories(String id) async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/product/get-products-for-category/'+ id ), headers: { 'Content-type' : 'application/json', 'xxx-token' : token! }, ); return ResponseProductsHome.fromJson(jsonDecode(resp.body)).listProducts; } Future<ResponseDefault> saveOrderBuyProductToDatabase(String receipt, String amount, List<ProductCart> products) async { final token = await secureStorage.readToken(); Map<String, dynamic> data = { 'receipt' : receipt, 'amount' : amount, 'products': products }; final body = json.encode( data ); final resp = await http.post(Uri.parse('${Environment.urlApi}/product/save-order-buy-product'), headers: { 'Content-type' : 'application/json', 'xxx-token' : token! }, body: body ); return ResponseDefault.fromJson( jsonDecode( resp.body ) ); } Future<ResponseDefault> addNewProduct(String name, String description, String stock, String price, String uidCategory, String image) async { final token = await secureStorage.readToken(); var request = http.MultipartRequest('POST', Uri.parse('${Environment.urlApi}/product/add-new-product')) ..headers['Accept'] = 'application/json' ..headers['xxx-token'] = token! ..fields['name'] = name ..fields['description'] = description ..fields['stock'] = stock ..fields['price'] = price ..fields['uidCategory'] = uidCategory ..files.add( await http.MultipartFile.fromPath('productImage', image)); final resp = await request.send(); var data = await http.Response.fromStream( resp ); return ResponseDefault.fromJson(jsonDecode(data.body)); } Future<List<OrderBuy>> getPurchasedProducts() async { final token = await secureStorage.readToken(); final response = await http.get(Uri.parse('${Environment.urlApi}/product/get-all-purchased-products'), headers: { 'Content-type' : 'application/json', 'xxx-token' : token! }, ); return ResponseOrderBuy.fromJson(jsonDecode( response.body )).orderBuy; } Future<List<OrderDetail>> getOrderDetails(String uidOrder) async { final token = await secureStorage.readToken(); final response = await http.get(Uri.parse('${Environment.urlApi}/product/get-orders-details/'+ uidOrder), headers: { 'Content-type' : 'application/json', 'xxx-token' : token! }, ); return ResponseOrderDetails.fromJson(jsonDecode( response.body )).orderDetails; } } final productServices = ProductServices();
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/services/services.dart
export 'package:e_commers/domain/services/auth_services.dart'; export 'package:e_commers/domain/services/user_services.dart'; export 'package:e_commers/domain/services/product_services.dart';
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/services/stripeService.dart
// import 'dart:convert'; // import 'package:http/http.dart' as http ; // import 'package:stripe_payment/stripe_payment.dart'; // import 'package:e_commers/Models/Stripe/PaymentIntentResponse.dart'; // class StripeService { // StripeService._privateConstructor(); // static final _intance = StripeService._privateConstructor(); // factory StripeService() => _intance; // String _paymentApiUrl = "https://api.stripe.com/v1/payment_intents"; // String _secretKey = "Here your Secret Key - Stripe"; // String _apiKey = "Here you Api Key - Stripe"; // void init(){ // StripePayment.setOptions( // StripeOptions( // publishableKey: _apiKey, // androidPayMode: 'test', // merchantId: 'test' // ) // ); // } // Future<StripeResponseCustom> payWithCardExists({ required String amount, required String currency, required CreditCard creditCard }) async { // try { // final paymentMethod = await StripePayment.createPaymentMethod( PaymentMethodRequest( card: creditCard ) ); // return await _makePayment(amount: amount, currency: currency, paymentMethod: paymentMethod ); // } catch (e) { // return StripeResponseCustom(ok: false, msg: e.toString()); // } // } // Future<StripeResponseCustom> payWithNewCard({ required String amount, required String currency }) async { // try { // final paymentMethod = await StripePayment.paymentRequestWithCardForm( // CardFormPaymentRequest() // ); // return await _makePayment(amount: amount, currency: currency, paymentMethod: paymentMethod ); // } catch (e) { // return StripeResponseCustom(ok: false, msg: e.toString()); // } // } // Future<PaymentIntentResponse> _paymentIntent({ required String amount, required String currency }) async { // try { // final resp = await http.post(Uri.parse( _paymentApiUrl ), // headers: { // 'Accept': 'application/json', // 'Authorization' : 'Bearer $_secretKey' // }, // body: { // 'amount': amount, // 'currency': currency // } // ); // return PaymentIntentResponse.fromJson( jsonDecode( resp.body ) ); // } catch (e) { // return PaymentIntentResponse(status: '400'); // } // } // Future<StripeResponseCustom> _makePayment({ required String amount, required String currency, required PaymentMethod paymentMethod }) async { // try { // final paymentIntent = await _paymentIntent(amount: amount, currency: currency); // final paymentResult = await StripePayment.confirmPaymentIntent( // PaymentIntent( // clientSecret: paymentIntent.clientSecret, // paymentMethodId: paymentMethod.id // ) // ); // if( paymentResult.status == 'succeeded' ){ // return StripeResponseCustom(ok: true); // } else { // return StripeResponseCustom(ok: false, msg: 'Something went wrong'); // } // } catch (e) { // return StripeResponseCustom(ok: false, msg: e.toString()); // } // } // } // final stripeService = StripeService();
0
mirrored_repositories/ECommerce-Products-Flutter/lib/domain
mirrored_repositories/ECommerce-Products-Flutter/lib/domain/services/user_services.dart
import 'dart:convert'; import 'package:e_commers/data/env/env.dart'; import 'package:e_commers/data/local_storage/secure_storage.dart'; import 'package:e_commers/domain/models/response/response_default.dart'; import 'package:e_commers/domain/models/response/response_user.dart'; import 'package:http/http.dart' as http; class UserServices { Future<ResponseDefault> addNewUser(String username, String email, String password ) async { final resp = await http.post(Uri.parse('${Environment.urlApi}/user/add-new-user'), headers: { 'Accept': 'application/json'}, body: { 'username': username, 'email': email, 'passwordd': password } ); return ResponseDefault.fromJson(jsonDecode(resp.body)); } Future<User> getUserById() async { final token = await secureStorage.readToken(); final resp = await http.get(Uri.parse('${Environment.urlApi}/user/get-user-by-id'), headers: { 'Accept': 'application/json', 'xxx-token' : token! } ); return ResponseUser.fromJson(jsonDecode(resp.body)).user; } Future<ResponseDefault> updatePictureProfile(String image) async { final token = await secureStorage.readToken(); var request = http.MultipartRequest('PUT', Uri.parse('${Environment.urlApi}/user/update-picture-profile')) ..headers['Accept'] = 'application/json' ..headers['xxx-token'] = token! ..files.add( await http.MultipartFile.fromPath('image', image ) ); final resp = await request.send(); var data = await http.Response.fromStream( resp ); return ResponseDefault.fromJson(jsonDecode(data.body)); } Future<ResponseDefault> updateInformationUser(String name, String last, String phone, String address, String reference) async { final token = await secureStorage.readToken(); final resp = await http.put( Uri.parse('${Environment.urlApi}/user/update-information-user'), headers: { 'Accept' : 'application/json', 'xxx-token' : token! }, body: { 'firstname' : name, 'lastname' : last, 'phone' : phone, 'address' : address, 'reference' : reference } ); return ResponseDefault.fromJson( jsonDecode( resp.body ) ); } Future<ResponseDefault> updateStreetAddress(String address, String reference) async { final token = await secureStorage.readToken(); final resp = await http.put( Uri.parse('${Environment.urlApi}/user/update-street-address'), headers: { 'Accept' : 'application/json', 'xxx-token' : token! }, body: { 'address' : address, 'reference' : reference } ); return ResponseDefault.fromJson( jsonDecode( resp.body ) ); } } final userServices = UserServices();
0
mirrored_repositories/ECommerce-Products-Flutter
mirrored_repositories/ECommerce-Products-Flutter/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:e_commers/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/COCO_UI
mirrored_repositories/COCO_UI/lib/store_main_page.dart
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:store_ui/ListViewChilderens/detay_sayfasi.dart'; import 'package:store_ui/User%20InterFace/user_login.dart'; import 'package:store_ui/const/constant.dart'; class StoreMainPage extends StatefulWidget { const StoreMainPage({Key? key}) : super(key: key); //////////////////////////////////////////// ///follor For more ig: @Countrol4offical ///@countrolfour@gmail.com //////////////////////////////////////////// @override _StoreMainPageState createState() => _StoreMainPageState(); } class _StoreMainPageState extends State<StoreMainPage> { @override Widget build(BuildContext context) { return SafeArea(child: Builder(builder: (context) { return Scaffold( drawer: ClipRRect( borderRadius: const BorderRadius.only( topRight: Radius.circular(100), bottomRight: Radius.circular(600)), child: Drawer( elevation: 0, child: Container( child: ListView( scrollDirection: Axis.vertical, children: [ SizedBox( height: 150, width: 10, child: CircleAvatar( backgroundImage: const AssetImage("images/coco.png"), backgroundColor: Colors.transparent, maxRadius: 350, child: Container( margin: const EdgeInsets.fromLTRB(0, 100, 0, 0), child: const Text( "COCO", style: TextStyle( fontFamily: "monster", color: Colors.black, fontWeight: FontWeight.bold, fontSize: 30), ), ), ), ), Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.fromLTRB(0, 30, 0, 0), color: Colors.black, height: 35, child: Row( children: [ Container( margin: const EdgeInsets.fromLTRB(33, 0, 5, 0), child: const Icon(Icons.mail_outline_sharp, color: Colors.white, size: 35), ), Text( "Countrolfour@gmail.com", style: Constants.ao, ) ], ), ), Container( margin: const EdgeInsets.fromLTRB(24, 80, 0, 0), child: TextButton.icon( onPressed: () { // Respond to button press }, icon: const Icon( Icons.person, size: 35, color: Colors.black, ), label: Text( "KULLANICI BİLGİLERİM", style: Constants.oa, ), ), ), Container( margin: const EdgeInsets.fromLTRB(24, 10, 0, 0), child: TextButton.icon( onPressed: () { // Respond to button press }, icon: const Icon( Icons.cases_outlined, size: 35, color: Colors.black, ), label: Text( "SİPARİŞLERİM", style: Constants.oa, ), ), ), Container( margin: const EdgeInsets.fromLTRB(24, 10, 0, 0), child: TextButton.icon( onPressed: () { // Respond to button press }, icon: const Icon( Icons.location_on_outlined, size: 35, color: Colors.black, ), label: Text( "ADRES BİLGİLERİM ", style: Constants.oa, ), ), ), Container( margin: const EdgeInsets.fromLTRB(24, 10, 0, 0), child: TextButton.icon( onPressed: () { // Respond to button press }, icon: const Icon( Icons.settings, size: 35, color: Colors.black, ), label: Text( "AYARLAR", style: Constants.oa, ), ), ), const SizedBox( height: 100, ), Row( children: [ TextButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => UserLogin(), )); }, child: Constants.cikis), TextButton( onPressed: () {}, child: Constants.destek) ], ), ], ), ], ), color: Colors.orange[50], ), ), ), appBar: AppBar( actions: [ Container( margin: const EdgeInsets.fromLTRB(0, 12, 0, 0), child: Column( children: [ Row( children: [ const Icon( Icons.shopping_cart, size: 30, ), Container( margin: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: const Icon( Icons.favorite, size: 30, ), ) ], ) ], ), ), ], backgroundColor: Colors.black, title: const Text( "COCO", style: TextStyle( fontFamily: "monster", color: Colors.white, fontWeight: FontWeight.bold, fontSize: 30), ), leadingWidth: 35, ), body: SafeArea( child: LayoutBuilder(builder: (BuildContext contex, BoxConstraints viewportConstraints) { return Container( color: Colors.orange[50], child: ListView(scrollDirection: Axis.horizontal, children: [ Column( //***********************************İMAGE 1-2****************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/1.webp"))); }, child: Hero( tag: "images/1.webp", child: Container( margin: EdgeInsets.fromLTRB(0, 20, 0, 0), width: 200, height: 250, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/1.webp", ), fit: BoxFit.fill)), child: Container( height: 50, width: 40, margin: EdgeInsets.fromLTRB( 0, 0, 150, 200, ), child: Icon(Icons.remove_red_eye, size: 40)), ), ), ), Container( margin: EdgeInsets.fromLTRB(0, 0, 0, 0), child: Text( "YÜN VE ALPAKA KARIŞIMLI \nTRİKO ELBİSE\n 499 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/2.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(100, 30, 0, 0), width: 200, height: 300, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/2.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35), ), ), ), Container( margin: EdgeInsets.fromLTRB(100, 0, 0, 0), child: Text( "METALİK İPLİKLİ ÖRGÜ ELBİSE \n 599 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), ], ), Column( //************************İMAGE3***************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/3.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(20, 150, 20, 0), width: 250, height: 350, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/3.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 190, 260, ), child: InkWell( child: Icon(Icons.remove_red_eye, size: 35), onTap: () {}, ), ), ), ), Container( margin: EdgeInsets.fromLTRB(5, 0, 10, 0), child: Text( "POLO YAKA OVERSIZE TRİKO ELBİSE \n 599 TL", textAlign: TextAlign.center, style: Constants.kadinBuyuk, ), ), ], ), Column( //***********************************İMAGE 4-5****************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/4.webp"))); }, child: Hero( tag: "images/4.webp", child: Container( margin: EdgeInsets.fromLTRB(0, 20, 30, 0), width: 200, height: 250, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/4.webp", ), fit: BoxFit.fill)), child: Container( height: 50, width: 40, margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35)), ), ), ), Container( margin: EdgeInsets.fromLTRB(0, 0, 30, 0), child: Text( "FİTİLLİ TRİKO ELBİSE\n 399 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/5.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(80, 30, 0, 0), width: 200, height: 300, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/5.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35), ), ), ), Container( margin: EdgeInsets.fromLTRB(80, 0, 0, 0), child: Text( "FİTİLLİ TRİKO ELBİSE \n 399 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), ], ), Column( //************************İMAGE6***************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/6.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(20, 150, 20, 0), width: 250, height: 350, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/6.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 190, 260, ), child: InkWell( child: Icon(Icons.remove_red_eye, size: 35), onTap: () {}, ), ), ), ), Container( margin: EdgeInsets.fromLTRB(5, 0, 10, 0), child: Text( "DESENLİ DRAPE ELBİSE \n 599 TL", textAlign: TextAlign.center, style: Constants.kadinBuyuk, ), ), ], ), Column( //***********************************İMAGE 7-8****************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/7.webp"))); }, child: Hero( tag: "images/7.webp", child: Container( margin: EdgeInsets.fromLTRB(0, 20, 30, 0), width: 200, height: 250, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/7.webp", ), fit: BoxFit.fill)), child: Container( height: 50, width: 40, margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35)), ), ), ), Container( margin: EdgeInsets.fromLTRB(0, 0, 30, 0), child: Text( "YALTIN RENGİ DÜĞMELİ TRİKO ELBİSE\n 449 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/8.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(80, 30, 0, 0), width: 200, height: 300, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/8.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35), ), ), ), Container( margin: EdgeInsets.fromLTRB(80, 0, 0, 0), child: Text( "PAYETLİ HALTER YAKA ELBİSE\n 599 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), ], ), Column( //************************İMAGE9***************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/9.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(20, 150, 20, 0), width: 250, height: 350, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/9.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 190, 260, ), child: InkWell( child: Icon(Icons.remove_red_eye, size: 35), onTap: () {}, ), ), ), ), Container( margin: EdgeInsets.fromLTRB(5, 0, 10, 0), child: Text( "CEPLİ DOKULU CEKET \n 799 TL", textAlign: TextAlign.center, style: Constants.kadinBuyuk, ), ), ], ), Column( //***********************************İMAGE 10-11****************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/10.webp"))); }, child: Hero( tag: "images/10.webp", child: Container( margin: EdgeInsets.fromLTRB(0, 20, 30, 0), width: 200, height: 250, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/10.webp", ), fit: BoxFit.fill)), child: Container( height: 50, width: 40, margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35)), ), ), ), Container( margin: EdgeInsets.fromLTRB(0, 0, 30, 0), child: Text( "CEPLİ DOKULU CEKET \n 799 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/11.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(80, 30, 0, 0), width: 200, height: 300, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/11.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35), ), ), ), Container( margin: EdgeInsets.fromLTRB(80, 0, 0, 0), child: Text( "BEYAZ CEPLİ DOKULU CEKET \n 799 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), ], ), Column( //************************İMAGE12***************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/12.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(20, 150, 20, 0), width: 250, height: 350, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/12.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 190, 260, ), child: InkWell( child: Icon(Icons.remove_red_eye, size: 35), onTap: () {}, ), ), ), ), Container( margin: EdgeInsets.fromLTRB(5, 0, 10, 0), child: Text( "CEPLİ DOKULU CEKET \n 799 TL", textAlign: TextAlign.center, style: Constants.kadinBuyuk, ), ), ], ), Column( //***********************************İMAGE 13-14****************** children: [ InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/13.webp"))); }, child: Hero( tag: "images/13.webp", child: Container( margin: EdgeInsets.fromLTRB(0, 20, 30, 0), width: 200, height: 250, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/13.webp", ), fit: BoxFit.fill)), child: Container( height: 50, width: 40, margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35)), ), ), ), Container( margin: EdgeInsets.fromLTRB(0, 0, 30, 0), child: Text( "YÜN VE ALPAKA KARIŞIMLI \nTRİKO ELBİSE\n 499 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), InkWell( onTap: () { debugPrint("Resme Basıldı"); Navigator.of(context).push(MaterialPageRoute( builder: (context) => Detay(imgPath: "images/14.webp"))); }, child: Container( margin: EdgeInsets.fromLTRB(80, 30, 0, 0), width: 200, height: 300, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), image: DecorationImage( image: AssetImage( "images/14.webp", ), fit: BoxFit.fill)), child: Container( margin: EdgeInsets.fromLTRB( 0, 0, 130, 180, ), child: Icon(Icons.remove_red_eye, size: 35), ), ), ), Container( margin: EdgeInsets.fromLTRB(80, 0, 0, 0), child: Text( "METALİK İPLİKLİ ÖRGÜ ELBİSE \n 599 TL", textAlign: TextAlign.center, style: Constants.kadin, ), ), ], ), ]), ); }), )); })); } }
0
mirrored_repositories/COCO_UI
mirrored_repositories/COCO_UI/lib/main.dart
import 'package:flutter/material.dart'; import 'package:store_ui/User%20InterFace/user_login.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Countrol4', debugShowCheckedModeBanner: false, home: UserLogin(), ); } }
0
mirrored_repositories/COCO_UI/lib
mirrored_repositories/COCO_UI/lib/const/splash.dart
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp(home: MyApp())); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); Future.delayed(Duration(seconds: 3), () { Navigator.push(context, MaterialPageRoute(builder: (context) => MyApp())); }); } @override Widget build(BuildContext context) { return Scaffold( body: Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage("images/splashscreen.png"), fit: BoxFit.cover)), ), ); } }
0
mirrored_repositories/COCO_UI/lib
mirrored_repositories/COCO_UI/lib/const/constant.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class Constants { static TextStyle ao = (const TextStyle( fontFamily: "monster", color: Colors.white, )); static TextStyle detail = (const TextStyle( fontFamily: "monster", color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold)); static TextStyle oa = (const TextStyle( fontFamily: "monster", color: Colors.black, fontWeight: FontWeight.bold)); static Text destek = (const Text( "Destek ve İletişim", style: TextStyle(color: Colors.blue, fontFamily: "monster"), )); static Text cikis = (const Text( "Çıkış", style: TextStyle(color: Colors.blue, fontFamily: "monster"), )); static TextStyle kadin = (const TextStyle( fontFamily: "monster", color: Colors.black, fontSize: 14)); static TextStyle kadinBuyuk = (const TextStyle( fontFamily: "monster", color: Colors.black, fontSize: 14)); }
0
mirrored_repositories/COCO_UI/lib
mirrored_repositories/COCO_UI/lib/User InterFace/user_login.dart
import 'package:flutter/material.dart'; import 'package:store_ui/User%20InterFace/sign_page.dart'; import 'package:store_ui/const/constant.dart'; import 'package:store_ui/store_main_page.dart'; class UserLogin extends StatefulWidget { const UserLogin({Key? key}) : super(key: key); @override _UserLoginState createState() => _UserLoginState(); } class _UserLoginState extends State<UserLogin> { @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return SafeArea( left: true, right: true, bottom: true, top: true, child: Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Colors.orange[50], body: Stack( children: [ Container( margin: const EdgeInsets.fromLTRB(0, 0, 0, 350), decoration: const BoxDecoration( image: DecorationImage(image: AssetImage("images/coco.png"))), ), const Positioned( left: 15, right: 15, bottom: 330, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "mail@example.com", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), const Positioned( left: 15, right: 15, bottom: 270, child: TextField( obscureText: true, enableSuggestions: false, autocorrect: false, textAlign: TextAlign.start, decoration: InputDecoration( counterStyle: TextStyle(color: Colors.black), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Password", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), Positioned( left: 0, right: 265, bottom: 230, child: TextButton( style: TextButton.styleFrom( elevation: 0, primary: Colors.black, ), onPressed: () {}, child: const Text( "Forget Password?", style: TextStyle(fontSize: 12, color: Colors.blue), ))), Positioned( left: 15, right: 15, bottom: 150, child: Container( decoration: BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular(15.0), ), child: TextButton( style: const ButtonStyle(), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const StoreMainPage(), )); }, child: Text( "LOGIN", style: Constants.oa, ), ), )), Positioned( left: 15, right: 15, bottom: 85, child: Container( decoration: BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular(15.0), ), child: TextButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const SignPage(), )); }, child: Text( "SIGN UP", style: Constants.oa, ), ), )) ], ), ), ); }); } }
0
mirrored_repositories/COCO_UI/lib
mirrored_repositories/COCO_UI/lib/User InterFace/sign_page.dart
import 'package:flutter/material.dart'; import 'package:store_ui/const/constant.dart'; import 'package:store_ui/store_main_page.dart'; class SignPage extends StatefulWidget { const SignPage({Key? key}) : super(key: key); @override _SignPageState createState() => _SignPageState(); } class _SignPageState extends State<SignPage> { @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Colors.orange[50], body: Stack( children: [ Positioned( left: 15, right: 15, bottom: 650, child: Container( width: 15, margin: const EdgeInsets.fromLTRB(15, 15, 15, 15), child: const Text( "COCO", textAlign: TextAlign.center, style: TextStyle( fontFamily: "monster", fontSize: 50, fontWeight: FontWeight.bold), ), ), ), Positioned( left: 15, right: 15, bottom: 450, child: Container( width: 15, margin: const EdgeInsets.fromLTRB(15, 15, 15, 15), child: const Text( "SIGN UP", textAlign: TextAlign.center, style: TextStyle( fontFamily: "monster", fontSize: 20, fontWeight: FontWeight.bold), ), ), ), const Positioned( left: 15, right: 15, bottom: 400, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( counterStyle: TextStyle(color: Colors.black), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Name", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), const Positioned( left: 15, right: 15, bottom: 350, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( counterStyle: TextStyle(color: Colors.black), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Surname", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), const Positioned( left: 15, right: 15, bottom: 300, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( counterStyle: TextStyle(color: Colors.black), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Mail@example.com", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), const Positioned( left: 15, right: 15, bottom: 150, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Security Question", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), const Positioned( left: 15, right: 15, bottom: 200, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Again Password", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), const Positioned( left: 15, right: 15, bottom: 250, child: TextField( textAlign: TextAlign.start, decoration: InputDecoration( counterStyle: TextStyle(color: Colors.black), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.black), ), hintText: "Password", labelStyle: TextStyle(color: Color(0xFF424242))), ), ), Positioned( left: 15, right: 15, bottom: 70, child: Container( decoration: BoxDecoration( border: Border.all(), borderRadius: BorderRadius.circular(15.0), ), child: TextButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const StoreMainPage(), )); }, child: Text( "SIGN UP", style: Constants.oa, ), ), )) ], ), ); } }
0
mirrored_repositories/COCO_UI/lib
mirrored_repositories/COCO_UI/lib/ListViewChilderens/detay_sayfasi.dart
// ignore_for_file: prefer_typing_uninitialized_variables import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:store_ui/const/constant.dart'; // ignore: must_be_immutable class Detay extends StatefulWidget { var imgPath; Detay({Key? key, this.imgPath}) : super(key: key); @override _DetayState createState() => _DetayState(); } class _DetayState extends State<Detay> { @override Widget build(BuildContext context) { return Scaffold( body: Stack(children: [ Hero( tag: widget.imgPath, child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, decoration: BoxDecoration( image: DecorationImage( image: AssetImage(widget.imgPath), fit: BoxFit.cover, )), ), ), Positioned( left: 15, right: 15, bottom: 15, child: Container( width: 85, height: 85, decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(10))), child: Row( children: [ const SizedBox( width: 50, height: 90, child: Image( fit: BoxFit.cover, image: AssetImage( "images/coco.png", ), )), Text( "COCO", style: Constants.detail, ), Container( margin: const EdgeInsets.fromLTRB(170, 0, 0, 0), child: const Icon(Icons.favorite), ), Container( margin: const EdgeInsets.fromLTRB(15, 0, 0, 0), child: const Icon(Icons.card_giftcard), ), ], ), )) ]), ); } }
0
mirrored_repositories/COCO_UI
mirrored_repositories/COCO_UI/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:store_ui/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/yt-furnitureapp-ui
mirrored_repositories/yt-furnitureapp-ui/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:yt_trvael_app_ui/deatilsPage.dart'; void main()=>runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: new ThemeData( brightness: Brightness.light, ), home: HomePage(), ); } } class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.blue[800], body: new Container( padding: const EdgeInsets.only(top:50), child: new Column( children: [ new Container( padding: const EdgeInsets.all(30), child: new Column( children: [ new Row( mainAxisAlignment : MainAxisAlignment.spaceBetween, children: [ new Text("Dashboard",style: GoogleFonts.poppins( fontSize: 25, color: Colors.white, )), new SvgPicture.asset("assets/icons/notification.svg"), ], ), new Padding(padding: const EdgeInsets.only(top: 30),), new Container( decoration: new BoxDecoration( color: Colors.blue[100], borderRadius: BorderRadius.all(Radius.circular(15)) ), child: new TextFormField( decoration: new InputDecoration( prefixIcon: new Icon(Icons.search,color: Colors.white,size: 30,), contentPadding: const EdgeInsets.all(10), hintText: "Search", hintStyle: GoogleFonts.poppins(fontSize: 22,color: Colors.white), focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, ), ), ), new Padding(padding: const EdgeInsets.only(top: 30)), new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Container( height: 35, width: 80, decoration: new BoxDecoration( color: Colors.blue[100], borderRadius: BorderRadius.all(Radius.circular(10)), ), child: new TextFormField( decoration: new InputDecoration( hintText: "All", hintStyle: GoogleFonts.poppins(fontSize:16,color: Colors.white), focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, contentPadding: const EdgeInsets.symmetric(horizontal: 28,vertical: 10) ), ), ), new Text("Sofa",style: GoogleFonts.poppins(fontSize: 16,color: Colors.white),), new Text("Park Bench",style: GoogleFonts.poppins(fontSize: 16,color: Colors.white),), new Text("Armchair",style: GoogleFonts.poppins(fontSize: 16,color: Colors.white),) ], ), //new Padding(padding: const EdgeInsets.only(top: 40)), ], ), ), new Stack( children: [ new Container( //margin: const EdgeInsets.only(top:10), //padding: const EdgeInsets.all(30), height: 500, width: 720, decoration: new BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(42), topRight: Radius.circular(42), ) ), child: new Container( //margin: const EdgeInsets.only(top:10), child: new SingleChildScrollView( child: new Column( mainAxisAlignment: MainAxisAlignment.start, children: [ new Card( margin: const EdgeInsets.all(30), shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(15))), shadowColor: Colors.black54, color: Colors.white, elevation: 8, child: new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ new Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(vertical: 15)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text("Classic Leather",style: GoogleFonts.poppins(fontSize: 20,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.only(top:4)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text("Arm Chair",style: GoogleFonts.poppins(fontSize: 20,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.symmetric(vertical: 20)), new Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Container( alignment: Alignment.center, height: 45, width: 80, decoration: new BoxDecoration( color: Colors.amberAccent[700], borderRadius: BorderRadius.only( topRight: Radius.circular(15), bottomLeft: Radius.circular(15) ) ), child: new Column( children: [ new Padding(padding: const EdgeInsets.only(top: 5)), new Text("56\$",style: GoogleFonts.poppins(fontSize: 20,color:Colors.white,fontWeight: FontWeight.bold)), ], ) ) ], ) ], ), new Image.asset("assets/images/Item_1.png",fit: BoxFit.fill,) ], ), ), new GestureDetector( child: new Card( margin: const EdgeInsets.all(30), shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(15))), shadowColor: Colors.black54, color: Colors.white, elevation: 8, child: new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ new Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(vertical: 15)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text("Poppy Plastic",style: GoogleFonts.poppins(fontSize: 20,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.only(top:4)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text("Tub Chair",style: GoogleFonts.poppins(fontSize: 20,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.symmetric(vertical: 20)), new Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Container( alignment: Alignment.center, height: 45, width: 80, decoration: new BoxDecoration( color: Colors.amberAccent[700], borderRadius: BorderRadius.only( topRight: Radius.circular(15), bottomLeft: Radius.circular(15) ) ), child: new Column( children: [ new Padding(padding: const EdgeInsets.only(top: 5)), new Text("56\$",style: GoogleFonts.poppins(fontSize: 20,color:Colors.white,fontWeight: FontWeight.bold)), ], ) ) ], ) ], ), new Image.asset("assets/images/Item_2.png",fit: BoxFit.fill,) ], ), ), onTap: (){ Navigator.push(context, MaterialPageRoute(builder: (BuildContext context)=>DetailsPage())); }, ), new Card( margin: const EdgeInsets.all(30), shape: new RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(15))), shadowColor: Colors.black54, color: Colors.white, elevation: 8, child: new Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ new Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(vertical: 15)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text("Bar Stool",style: GoogleFonts.poppins(fontSize: 20,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.only(top:4)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text("Chair",style: GoogleFonts.poppins(fontSize: 20,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.symmetric(vertical: 20)), new Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Container( alignment: Alignment.center, height: 45, width: 80, decoration: new BoxDecoration( color: Colors.amberAccent[700], borderRadius: BorderRadius.only( topRight: Radius.circular(15), bottomLeft: Radius.circular(15) ) ), child: new Column( children: [ new Padding(padding: const EdgeInsets.only(top: 5)), new Text("56\$",style: GoogleFonts.poppins(fontSize: 20,color:Colors.white,fontWeight: FontWeight.bold)), ], ) ) ], ) ], ), new Image.asset("assets/images/Item_3.png",fit: BoxFit.fill,) ], ), ), ], ), ), ), ) ], ), ], ) ), ); } } /* */
0
mirrored_repositories/yt-furnitureapp-ui
mirrored_repositories/yt-furnitureapp-ui/lib/deatilsPage.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:google_fonts/google_fonts.dart'; class DetailsPage extends StatefulWidget { @override _DetailsPageState createState() => _DetailsPageState(); } class _DetailsPageState extends State<DetailsPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: new AppBar( elevation: 0, backgroundColor: Colors.white, leading: new Row( children: [ new IconButton(icon: new SvgPicture.asset("assets/icons/back.svg"), onPressed: (){ Navigator.pop(context); }), ], ), actions: [ new IconButton(icon: new SvgPicture.asset("assets/icons/cart_with_item.svg"), onPressed: (){}), ], title: new Text("BACK",style: GoogleFonts.poppins(fontSize: 20,color: Colors.black)), ), backgroundColor: Colors.blue[800], body: new Column( children: [ new Container( height: 550, width: 720, decoration: new BoxDecoration( color: Colors.white, borderRadius: new BorderRadius.only( bottomRight: new Radius.circular(25), bottomLeft: new Radius.circular(25) ) ), child: new Column( children: [ new Image.asset("assets/images/Item_2.png",height: 250,fit: BoxFit.fitHeight,), new Padding(padding: const EdgeInsets.only(top: 30)), new Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new CircleAvatar( backgroundColor: Colors.grey[600], radius: 14, ), new CircleAvatar( backgroundColor: Colors.red[600], radius: 14, ), new CircleAvatar( backgroundColor: Colors.blue[600], radius: 14, ), ], ), new Padding(padding: const EdgeInsets.only(top: 30)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 20)), new Text("Poppy Plastic",style: GoogleFonts.poppins(fontSize: 22,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), new Padding(padding: const EdgeInsets.only(top:4)), new Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ //new Padding(padding: const EdgeInsets.symmetric(horizontal: 5)), new Text(" Tub Chair",style: GoogleFonts.poppins(fontSize: 22,color: Colors.grey[700],fontWeight: FontWeight.bold),), ], ), ], ), new Padding(padding: const EdgeInsets.only(top: 30),), new Row( children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 20)), new Text("\$56",style: GoogleFonts.poppins(fontSize: 22,color: Colors.blue[800],fontWeight: FontWeight.bold)) ], ), new Column( children: [ new Container( padding: const EdgeInsets.all(20), child: new Text("lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum",style: GoogleFonts.poppins(fontSize: 18,color: Colors.grey[600])), ) ], ) ], ), ), new Padding(padding: const EdgeInsets.only(top: 40)), new Container( padding: const EdgeInsets.all(13), height: 50, width: 320, decoration: new BoxDecoration( color: Colors.yellow, borderRadius: BorderRadius.all(Radius.circular(25)) ), child: new Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ new Padding(padding: const EdgeInsets.symmetric(horizontal: 5,vertical: 5),), new SvgPicture.asset("assets/icons/chat.svg",height: 18,), new Padding(padding: const EdgeInsets.symmetric(horizontal: 3),), new Text("Chat",style: GoogleFonts.poppins(fontSize: 18,color:Colors.white)), new Padding(padding: const EdgeInsets.symmetric(horizontal: 35),), new SvgPicture.asset("assets/icons/shopping-bag.svg",height: 18,), new Padding(padding: const EdgeInsets.symmetric(horizontal: 3),), new Text("Add to cart",style: GoogleFonts.poppins(fontSize: 18,color:Colors.white)), ], ), ) ], ) ); } }
0
mirrored_repositories/yt-furnitureapp-ui
mirrored_repositories/yt-furnitureapp-ui/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:yt_trvael_app_ui/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/My-first-FlutterApp
mirrored_repositories/My-first-FlutterApp/lib/main.dart
import 'package:flutter/material.dart'; import './pages/landing_page.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( debugShowCheckedModeBanner: false, title: "My first flutter app", home: new LandingPage()); } }
0
mirrored_repositories/My-first-FlutterApp/lib
mirrored_repositories/My-first-FlutterApp/lib/pages/landing_page.dart
import 'package:flutter/material.dart'; import '../utils/random_words.dart'; class LandingPage extends StatelessWidget { int counter = 0; @override Widget build(BuildContext context) { return new Material( color: Colors.greenAccent, child: new InkWell( onTap: () => print('hello :\t' + (counter++).toString()), child: Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text("Name For", style: new TextStyle( color: Colors.white, fontSize: 50.0, fontWeight: FontWeight.bold)), new Text("Apna", style: new TextStyle( color: Colors.white, fontSize: 50.0, fontWeight: FontWeight.bold)), new Text("StartUp", style: new TextStyle( color: Colors.yellow, fontStyle: FontStyle.italic, fontSize: 60.0, fontWeight: FontWeight.bold)), new RandomWords() ], ), )), ); } }
0
mirrored_repositories/My-first-FlutterApp/lib
mirrored_repositories/My-first-FlutterApp/lib/utils/random_words.dart
import 'package:flutter/material.dart'; import 'package:english_words/english_words.dart'; class RandomWords extends StatefulWidget { @override RandomWordsStates createState() { return new RandomWordsStates(); } @override Widget build(BuildContext context) { return Container(); } } class RandomWordsStates extends State<RandomWords> { //todo implelment build method @override Widget build(BuildContext context) { final List<WordPair> wordPair = <WordPair>[]; final _biggerFont = new TextStyle(fontSize: 18.0); return new Text(wordPair.asPascalCase, style: new TextStyle( color: Colors.purpleAccent, fontStyle: FontStyle.normal, fontSize: 60.0, fontWeight: FontWeight.bold)); } }
0
mirrored_repositories/My-first-FlutterApp
mirrored_repositories/My-first-FlutterApp/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:tral_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/mobile-orders/flutter/app
mirrored_repositories/mobile-orders/flutter/app/lib/preset_store.dart
import 'dart:convert'; import 'dart:math'; import './providers/product.dart'; import './screens/checkout_screen.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import './providers/auth.dart'; import './providers/cart.dart'; import './providers/orders.dart'; import './providers/products.dart'; import './screens/auth_screen.dart'; import './screens/cart_screen.dart'; import './screens/edit_product_screen.dart'; import './screens/orders_screen.dart'; import './screens/product_detail.dart'; import './screens/products_overview_screen.dart'; import './screens/splash_screen.dart'; import './screens/user_products_screen.dart'; import 'package:provider/provider.dart'; void main() { runApp(MobileOrdersApp(null, false)); } class MobileOrdersApp extends StatefulWidget { static String? title = 'Mobile Orders'; final dynamic content; final bool onlyEditor; MobileOrdersApp(this.content, this.onlyEditor); @override _MobileOrdersAppState createState() => _MobileOrdersAppState(content); } class _MobileOrdersAppState extends State<MobileOrdersApp> { dynamic _content; _MobileOrdersAppState(this._content); Future<dynamic> loadContentFromAssets() async { String data = await DefaultAssetBundle.of(context).loadString("assets/store.glowbom"); return json.decode(data); } var _expired = false; @override void initState() { super.initState(); if (_content == null) { loadContentFromAssets().then( (value) => setState(() { _content = value; List<Product> products = List<Product>.empty(growable: true); List<dynamic> loadedProducts = value['products']; for (int index = 0; index < loadedProducts.length; index++) { Product product = Product( description: loadedProducts[index]['description'], id: loadedProducts[index]['id'], title: loadedProducts[index]['title'], price: double.tryParse(loadedProducts[index]['price'].toString()), imageUrl: loadedProducts[index]['imageUrl'], isFavorite: loadedProducts[index]['isFavorite'], ); products.add(product); } value['products'] = products; }), ); } } int tintValue(int value, double factor) => max(0, min((value + ((255 - value) * factor)).round(), 255)); Color tintColor(Color color, double factor) => Color.fromRGBO( tintValue(color.red, factor), tintValue(color.green, factor), tintValue(color.blue, factor), 1); int shadeValue(int value, double factor) => max(0, min(value - (value * factor).round(), 255)); Color shadeColor(Color color, double factor) => Color.fromRGBO( shadeValue(color.red, factor), shadeValue(color.green, factor), shadeValue(color.blue, factor), 1); MaterialColor generateMaterialColor(Color color) { return MaterialColor(color.value, { 50: tintColor(color, 0.9), 100: tintColor(color, 0.8), 200: tintColor(color, 0.6), 300: tintColor(color, 0.4), 400: tintColor(color, 0.2), 500: color, 600: shadeColor(color, 0.1), 700: shadeColor(color, 0.2), 800: shadeColor(color, 0.3), 900: shadeColor(color, 0.4), }); } @override Widget build(BuildContext context) { MobileOrdersApp.title = _content != null ? _content['title'] : 'Mobile Orders'; return MultiProvider( providers: [ ChangeNotifierProvider( create: (ctx) => Auth(), ), ChangeNotifierProxyProvider<Auth, Products?>( create: (ctx) => null, update: (ctx, auth, previousProducts) => Products( auth.token, auth.userId, _content != null ? _content['products'] : Products.defaultProducts, ), ), ChangeNotifierProvider( create: (ctx) => Cart(), ), ChangeNotifierProxyProvider<Auth, Orders?>( create: (ctx) => null, update: (ctx, auth, previousOrders) => Orders( auth.token, auth.userId, previousOrders == null ? [] : previousOrders.orders, ), ) ], child: Consumer<Auth>( builder: (ctx, auth, _) => MaterialApp( title: MobileOrdersApp.title!, theme: ThemeData( primarySwatch: _content != null ? (_content['main_color'] == 'Blue' ? Colors.blue : _content['main_color'] == 'Green' ? Colors.green : _content['main_color'] == 'Red' ? Colors.red : _content['main_color'] == 'Grey' ? Colors.grey : _content['main_color'] == 'White' ? generateMaterialColor(Colors.white) : _content['main_color'] == 'Black' ? generateMaterialColor(Colors.black) : Colors.purple) : Colors.purple, //accentColor: Colors.deepOrange, textTheme: GoogleFonts.latoTextTheme( Theme.of(context).textTheme, ), ), home: _expired ? Scaffold( body: Center( child: Padding( padding: EdgeInsets.all(20), child: Text('The preview is no longer available.'), ), ), ) : widget.onlyEditor ? UserProductsScreen(widget.onlyEditor) : auth.isAuth ? ProductsOverviewScreen() : FutureBuilder( future: auth.tryAutoLogin(), builder: (ctx, authResultSnapshot) => authResultSnapshot.connectionState == ConnectionState.waiting ? SplashScreen() : AuthScreen(), ), routes: { ProductDetailScreen.routeName: (ctx) => ProductDetailScreen(), CartScreen.routeName: (ctx) => CartScreen(), OrdersScreen.routeName: (ctx) => OrdersScreen(), UserProductsScreen.routeName: (ctx) => UserProductsScreen(widget.onlyEditor), EditProductScreen.routeName: (ctx) => EditProductScreen(), AuthScreen.routeName: (ctx) => AuthScreen(), CheckoutScreen.routeName: (ctx) => CheckoutScreen( () {}, _content != null ? _content['show_number_result'] : false, _content != null ? _content['show_percentage_result'] : false, _content != null ? _content['voice'] : false, _content != null ? _content['conclusion'] : 'Thank you! Please enter your shipping information:', _content != null ? _content['start_over'] : '', '', _content != null && (_content as Map<String, dynamic>) .containsKey('payment_link') ? _content['payment_link'] : '', ), }, ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app
mirrored_repositories/mobile-orders/flutter/app/lib/main.dart
import 'package:flutter/material.dart'; import './preset_store.dart'; void main() => runApp(MobileOrdersApp(null, false));
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/products_grid.dart
import 'package:flutter/material.dart'; import '../providers/products.dart'; import '../widgets/product_item.dart'; import 'package:provider/provider.dart'; class ProductsGrid extends StatelessWidget { final bool showOnlyFavorites; ProductsGrid(this.showOnlyFavorites); @override Widget build(BuildContext context) { final productsData = Provider.of<Products>(context); final products = showOnlyFavorites ? productsData.favoriteItems : productsData.items; return Center( child: Container( constraints: BoxConstraints(minWidth: 100, maxWidth: 640), child: GridView.builder( padding: const EdgeInsets.all(10.0), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 3 / 2, crossAxisSpacing: 10, mainAxisSpacing: 10, ), itemBuilder: (ctx, i) => ChangeNotifierProvider.value( value: products[i], child: ProductItem(), ), itemCount: products.length, ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/cart_item.dart
import 'package:flutter/material.dart'; import '../providers/cart.dart'; import 'package:provider/provider.dart'; class CartItem extends StatelessWidget { final String? id; final String? productId; final double? price; final int? quantity; final String? title; CartItem( this.id, this.productId, this.price, this.quantity, this.title, ); @override Widget build(BuildContext context) { return Dismissible( key: ValueKey(id), background: Container( color: Theme.of(context).colorScheme.error, child: Icon( Icons.delete, color: Colors.white, size: 40, ), alignment: Alignment.centerRight, padding: EdgeInsets.only(right: 20), margin: EdgeInsets.symmetric( horizontal: 15, vertical: 4, ), ), direction: DismissDirection.endToStart, confirmDismiss: (direction) { return showDialog( context: context, builder: (ctx) => AlertDialog( title: Text('Are you sure?'), content: Text( 'Do you want to remove the item from the cart?', ), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(false), child: Text('No')), TextButton( onPressed: () => Navigator.of(ctx).pop(true), child: Text('Yes')), ], ), ); }, onDismissed: (direction) { Provider.of<Cart>(context, listen: false).removeItem(productId); }, child: Card( margin: EdgeInsets.symmetric( horizontal: 15, vertical: 4, ), child: Padding( padding: EdgeInsets.all(8), child: ListTile( leading: CircleAvatar( child: Padding( padding: EdgeInsets.all(5), child: FittedBox( child: Text( '\$$price', ), ), ), ), title: Text(title!), subtitle: Text('Total: \$${(price! * quantity!)}'), trailing: Text('$quantity x'), ), ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/order_item.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import '../providers/orders.dart' as orders; class OrderItem extends StatefulWidget { final orders.OrderItem order; OrderItem(this.order); @override _OrderItemState createState() => _OrderItemState(); } class _OrderItemState extends State<OrderItem> { bool _expanded = false; @override Widget build(BuildContext context) { return Card( margin: EdgeInsets.all(10), child: Column(children: [ ListTile( title: Text('\$${widget.order.amount!.toStringAsFixed(2)}'), subtitle: Text( DateFormat('MM/dd/yyyy hh:mm').format(widget.order.dateTime), ), trailing: IconButton( icon: Icon( _expanded ? Icons.expand_less : Icons.expand_more, ), onPressed: () { setState(() { _expanded = !_expanded; }); }, ), ), if (_expanded) Container( padding: EdgeInsets.symmetric(horizontal: 15, vertical: 4), height: min(widget.order.products.length * 20.0 + 24, 100), child: ListView( children: widget.order.products .map((e) => Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( e.title!, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), Text( '${e.quantity}x \$${e.price}', style: TextStyle( fontSize: 18, color: Colors.grey, ), ), ], )) .toList(), ), ) ]), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/user_product_item.dart
import 'package:flutter/material.dart'; import '../providers/products.dart'; import '../screens/edit_product_screen.dart'; import 'package:provider/provider.dart'; class UserProductItem extends StatelessWidget { final String? id; final String? title; final String? imageUrl; UserProductItem(this.id, this.title, this.imageUrl); @override Widget build(BuildContext context) { return ListTile( title: Text(title!), leading: CircleAvatar( backgroundImage: NetworkImage(imageUrl!), ), trailing: Container( width: 100, child: Row( children: [ IconButton( icon: Icon(Icons.edit), onPressed: () { Navigator.of(context).pushNamed(EditProductScreen.routeName, arguments: id); }, color: Theme.of(context).primaryColor, ), IconButton( icon: Icon(Icons.delete), onPressed: () { Provider.of<Products>(context, listen: false).deleteProduct(id); }, color: Theme.of(context).colorScheme.error, ), ], ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/badge.dart
import 'package:flutter/material.dart'; class CustomBadge extends StatelessWidget { const CustomBadge({ Key? key, required this.child, required this.value, this.color, }) : super(key: key); final Widget? child; final String value; final Color? color; @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, children: [ child!, Positioned( right: 8, top: 8, child: Container( padding: EdgeInsets.all(2.0), // color: Theme.of(context).accentColor, decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: color != null ? color : Theme.of(context).primaryColor, ), constraints: BoxConstraints( minWidth: 16, minHeight: 16, ), child: Text( value, textAlign: TextAlign.center, style: TextStyle( fontSize: 10, ), ), ), ) ], ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/app_drawer.dart
import 'package:flutter/material.dart'; import '../preset_store.dart'; import '../providers/auth.dart'; import '../screens/orders_screen.dart'; import 'package:provider/provider.dart'; class AppDrawer extends StatelessWidget { @override Widget build(BuildContext context) { return Drawer( child: Column(children: [ AppBar( title: Text(MobileOrdersApp.title!), automaticallyImplyLeading: false, ), Divider(), ListTile( leading: Icon(Icons.shop), title: Text('Shop'), onTap: () { Navigator.of(context).pushReplacementNamed('/'); }, ), Divider(), ListTile( leading: Icon(Icons.payment), title: Text('Orders'), onTap: () { Navigator.of(context).pushReplacementNamed(OrdersScreen.routeName); }, ), /*Divider(), ListTile( leading: Icon(Icons.edit), title: Text('Manage Products'), onTap: () { Navigator.of(context) .pushReplacementNamed(UserProductsScreen.routeName); }, ),*/ Divider(), if (!Provider.of<Auth>(context, listen: false).isAuth) ListTile( leading: Icon(Icons.exit_to_app), title: Text('Logout'), onTap: () { Navigator.of(context).pop(); Navigator.of(context).pushReplacementNamed('/'); Provider.of<Auth>(context, listen: false).logout(); }, ), ]), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/widgets/product_item.dart
import 'package:flutter/material.dart'; import '../providers/auth.dart'; import '../providers/cart.dart'; import '../providers/product.dart'; import '../screens/product_detail.dart'; import 'package:provider/provider.dart'; class ProductItem extends StatelessWidget { @override Widget build(BuildContext context) { final product = Provider.of<Product>(context, listen: false); final cart = Provider.of<Cart>(context, listen: false); final authData = Provider.of<Auth>(context, listen: false); return ClipRRect( borderRadius: BorderRadius.circular(10), child: GridTile( child: GestureDetector( onTap: () { Navigator.of(context).pushNamed( ProductDetailScreen.routeName, arguments: product.id, ); }, child: Image.network( product.imageUrl!, fit: BoxFit.cover, ), ), footer: GridTileBar( backgroundColor: Colors.black87, leading: Consumer<Product>( builder: (ctx, product, _) => IconButton( icon: Icon( product.isFavorite! ? Icons.favorite : Icons.favorite_border), onPressed: () { product.toggleFavoriteStatus(authData.token, authData.userId); }, color: Colors.white70, ), ), title: Text( product.title!, textAlign: TextAlign.center, ), trailing: IconButton( icon: Icon(Icons.shopping_cart), onPressed: () { cart.addItem(product.id, product.price, product.title); ScaffoldMessenger.of(context).hideCurrentSnackBar(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Added item to cart!'), duration: Duration(seconds: 2), action: SnackBarAction( label: 'UNDO', onPressed: () { cart.removeSigleItem(product.id); }), ), ); }, color: Colors.white70, ), ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/model/http_exception.dart
class HttpException implements Exception { final String? message; HttpException(this.message); @override String toString() { return message!; } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/checkout_screen.dart
import 'package:url_launcher/url_launcher_string.dart'; import '../providers/cart.dart'; import '../providers/orders.dart'; import '../widgets/app_drawer.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:provider/provider.dart'; class CheckoutScreen extends StatefulWidget { static const routeName = '/checkout'; final bool? showPhone; final bool? showName; final bool? showAddress; final String? message; final String? url; final String order; final String? paymentLink; final Function checkoutFunction; CheckoutScreen(this.checkoutFunction, this.showPhone, this.showName, this.showAddress, this.message, this.url, this.order, this.paymentLink); @override _CheckoutState createState() => _CheckoutState(); } class _CheckoutState extends State<CheckoutScreen> { final _formKey = GlobalKey<FormState>(); String? _userEmail = ''; String? _userName = ''; String? _address = ''; String? _phone = ''; var _submitted = false; _launchLink(link) async { if (await canLaunchUrlString(link)) { await launchUrlString(link); } else { throw 'Could not launch $link'; } } void _trySubmit() async { final isValid = _formKey.currentState!.validate(); FocusScope.of(context).unfocus(); if (isValid) { _formKey.currentState!.save(); Orders ordersData = Provider.of<Orders>(context, listen: false); String orderString = ''; double price = 0.0; if (ordersData.orders.length > 0) { OrderItem orderItem = ordersData.orders[ordersData.orders.length - 1]; orderString += orderItem.dateTime.toIso8601String() + ', '; orderString += orderItem.amount.toString() + ', '; for (int i = 0; i < orderItem.products.length; i++) { CartItem product = orderItem.products[i]; orderString += product.title! + ', '; orderString += product.quantity.toString() + ', '; orderString += product.price.toString() + ', '; price += product.price! * product.quantity!; } } final url = widget.url; if (url != null && url.contains('http')) { http .get(Uri.parse( '$url?data=$_userEmail;$_userName;$_address;$_phone;$orderString')) .then((value) => print(value.body)); } setState(() { _submitted = true; if (widget.paymentLink != null && widget.paymentLink != '') { _launchLink(widget.paymentLink!.startsWith('http') ? '${widget.paymentLink}/$price' : 'https://${widget.paymentLink}/$price'); } }); widget.checkoutFunction(); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Shipping'), ), drawer: AppDrawer(), body: Center( child: Container( constraints: new BoxConstraints( maxWidth: 360.0, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( _submitted ? 'Thank you!' : widget.message!, style: TextStyle( fontSize: 21, ), textAlign: TextAlign.left, ), ), Padding( padding: EdgeInsets.all(16), child: Form( key: _formKey, child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ // showScore is name if (!_submitted && widget.showName!) TextFormField( key: ValueKey('username'), autocorrect: true, textCapitalization: TextCapitalization.words, enableSuggestions: false, validator: (value) { if (value!.isEmpty) { return 'Please enter at least 1 character.'; } return null; }, decoration: InputDecoration( labelText: 'Name', ), onSaved: (value) { _userName = value; }, ), if (!_submitted) TextFormField( key: ValueKey('email'), autocorrect: false, textCapitalization: TextCapitalization.none, enableSuggestions: false, validator: (value) { if (value!.isEmpty || !value.contains('@')) { return 'Please enter a valid email address.'; } return null; }, keyboardType: TextInputType.emailAddress, decoration: InputDecoration( labelText: 'Email address', ), onSaved: (value) { _userEmail = value; }, ), if (!_submitted && widget.showAddress!) TextFormField( key: ValueKey('address'), autocorrect: true, textCapitalization: TextCapitalization.words, enableSuggestions: false, validator: (value) { if (value!.isEmpty) { return 'Please enter at least 1 character.'; } return null; }, decoration: InputDecoration( labelText: 'Shipping address', ), onSaved: (value) { _address = value; }, ), // showResult is name if (!_submitted && widget.showPhone!) TextFormField( key: ValueKey('phone'), validator: (value) { if (value!.isEmpty || value.length < 3) { return 'Please enter at least 3 characters.'; } return null; }, decoration: InputDecoration( labelText: 'Phone', ), keyboardType: TextInputType.number, onSaved: (value) { _phone = value; }, onFieldSubmitted: (value) { _trySubmit(); }, ), SizedBox(height: 12), if (!_submitted) TextButton( child: Text( 'Place your order', style: TextStyle( color: Theme.of(context).primaryColor, ), ), onPressed: _trySubmit, ), ], ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/cart_screen.dart
import '../screens/checkout_screen.dart'; import 'package:flutter/material.dart'; import '../providers/cart.dart' show Cart; import '../providers/orders.dart'; import 'package:provider/provider.dart'; import '../widgets/cart_item.dart'; class CartScreen extends StatelessWidget { static const routeName = '/cart'; @override Widget build(BuildContext context) { final cart = Provider.of<Cart>(context); return Scaffold( appBar: AppBar( title: Text('Your Cart'), ), body: Center( child: Container( constraints: BoxConstraints(minWidth: 100, maxWidth: 640), child: Column(children: <Widget>[ Card( margin: EdgeInsets.all(15), child: Padding( padding: EdgeInsets.all(8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'Total', style: TextStyle( fontSize: 20, ), ), Spacer(), Chip( label: Text( '\$${cart.totalAmount.toStringAsFixed(2)}', style: TextStyle(color: Colors.white), ), backgroundColor: Theme.of(context).primaryColor, ), OrderButton(cart: cart), ], ), ), ), SizedBox( height: 10, ), Expanded( child: ListView.builder( itemBuilder: (ctx, i) => CartItem( cart.items.values.toList()[i].id, cart.items.keys.toList()[i], cart.items.values.toList()[i].price, cart.items.values.toList()[i].quantity, cart.items.values.toList()[i].title, ), itemCount: cart.items.length, ), ), ]), ), ), ); } } class OrderButton extends StatefulWidget { const OrderButton({ Key? key, required this.cart, }) : super(key: key); final Cart cart; @override _OrderButtonState createState() => _OrderButtonState(); } class _OrderButtonState extends State<OrderButton> { var _isLoading = false; @override Widget build(BuildContext context) { return TextButton( onPressed: (widget.cart.totalAmount <= 0 || _isLoading) ? null : () async { setState(() { _isLoading = true; }); await Provider.of<Orders>( context, listen: false, ).addOrder( widget.cart.items.values.toList(), widget.cart.totalAmount, ); setState(() { _isLoading = false; }); widget.cart.clear(); Navigator.of(context).pushNamed(CheckoutScreen.routeName); }, child: _isLoading ? CircularProgressIndicator() : Text('ORDER NOW'), style: TextButton.styleFrom( foregroundColor: Theme.of(context).primaryColor, // Text Color (Foreground color) ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/products_overview_screen.dart
import 'package:flutter/material.dart'; import '../providers/cart.dart'; import '../providers/products.dart'; import '../widgets/app_drawer.dart'; import '../widgets/badge.dart'; import '../widgets/products_grid.dart'; import 'package:provider/provider.dart'; import 'cart_screen.dart'; enum FilterOptions { Favorites, All } class ProductsOverviewScreen extends StatefulWidget { @override _ProductsOverviewScreenState createState() => _ProductsOverviewScreenState(); } class _ProductsOverviewScreenState extends State<ProductsOverviewScreen> { var _showOnlyFavorites = false; var _isInit = true; var _isLoading = false; @override void didChangeDependencies() { if (_isInit) { setState(() { _isLoading = true; }); Provider.of<Products>(context, listen: false) .fetchAndSetProducts() .then((value) { setState(() { _isLoading = false; }); }); _isInit = false; } super.didChangeDependencies(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Shop'), actions: <Widget>[ PopupMenuButton( onSelected: (FilterOptions selectedValue) { setState(() { if (selectedValue == FilterOptions.Favorites) { _showOnlyFavorites = true; } else { _showOnlyFavorites = false; } }); }, icon: Icon( Icons.more_vert, ), itemBuilder: (_) => [ PopupMenuItem( child: Text('Only Favorites'), value: FilterOptions.Favorites, ), PopupMenuItem( child: Text('Show All'), value: FilterOptions.All, ), ], ), Consumer<Cart>( builder: (_, cart, child) => CustomBadge( child: child, value: cart.itemsCount.toString(), ), child: IconButton( icon: Icon( Icons.shopping_cart, ), onPressed: () { Navigator.of(context).pushNamed(CartScreen.routeName); }, ), ), ], ), drawer: AppDrawer(), body: _isLoading ? Center( child: CircularProgressIndicator(), ) : ProductsGrid(_showOnlyFavorites), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/user_products_screen.dart
import 'package:flutter/material.dart'; import '../providers/products.dart'; import '../widgets/app_drawer.dart'; import '../widgets/user_product_item.dart'; import 'package:provider/provider.dart'; import 'edit_product_screen.dart'; class UserProductsScreen extends StatelessWidget { static const routeName = '/user-products'; final bool onlyEditor; UserProductsScreen(this.onlyEditor); Future<void> _refreshProducts(BuildContext context) async { await Provider.of<Products>(context, listen: false).fetchAndSetProducts(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Your Products'), actions: [ IconButton( icon: Icon(Icons.add), onPressed: () { Navigator.of(context).pushNamed(EditProductScreen.routeName); }, ), ], ), drawer: onlyEditor ? null : AppDrawer(), body: FutureBuilder( future: _refreshProducts(context), builder: (ctx, snapshot) => snapshot.connectionState == ConnectionState.waiting ? Center( child: CircularProgressIndicator(), ) : RefreshIndicator( onRefresh: () => _refreshProducts(context), child: Consumer<Products>( builder: (ctx, productsData, _) => Padding( padding: EdgeInsets.all(8), child: ListView.builder( itemBuilder: (_, i) => Column( children: [ UserProductItem( productsData.items[i]!.id, productsData.items[i]!.title, productsData.items[i]!.imageUrl, ), Divider(), ], ), itemCount: productsData.items.length, ), ), ), ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/edit_product_screen.dart
import 'package:flutter/material.dart'; import '../providers/product.dart'; import '../providers/products.dart'; import 'package:provider/provider.dart'; class EditProductScreen extends StatefulWidget { static const routeName = '/edit-product'; @override _EditProductScreenState createState() => _EditProductScreenState(); } class _EditProductScreenState extends State<EditProductScreen> { final _priceFocusNode = FocusNode(); final _descriptionFocusNode = FocusNode(); final _imageUrlController = TextEditingController(); final _imageUrlFocusNode = FocusNode(); final _form = GlobalKey<FormState>(); Product? _editedProduct = Product( id: null, title: '', description: '', price: 0, imageUrl: '', ); @override void initState() { _imageUrlFocusNode.addListener(_updateImageUrl); super.initState(); } var _isLoading = false; var _isInit = true; var _initValues = { 'title': '', 'description': '', 'price': '', 'imageUrl': '', }; @override void didChangeDependencies() { if (_isInit) { final productId = ModalRoute.of(context)!.settings.arguments as String?; if (productId != null) { _editedProduct = Provider.of<Products>(context, listen: false).findById(productId); _initValues = { 'title': _editedProduct!.title!, 'description': _editedProduct!.description!, 'price': _editedProduct!.price.toString(), 'imageUrl': '', }; _imageUrlController.text = _editedProduct!.imageUrl!; } _isInit = false; } super.didChangeDependencies(); } void _updateImageUrl() { if (!_imageUrlFocusNode.hasFocus) { final value = _imageUrlController.text; if (!value.startsWith('http') && !value.startsWith('https')) { return; } setState(() {}); } } @override void dispose() { _imageUrlFocusNode.removeListener(_updateImageUrl); _priceFocusNode.dispose(); _descriptionFocusNode.dispose(); _imageUrlController.dispose(); _imageUrlFocusNode.dispose(); super.dispose(); } Future<void> _saveForm() async { final isValid = _form.currentState!.validate(); if (!isValid) { return; } _form.currentState!.save(); setState(() { _isLoading = true; }); if (_editedProduct!.id != null) { await Provider.of<Products>(context, listen: false).updateProduct( _editedProduct!.id, _editedProduct, ); setState(() { _isLoading = false; }); Navigator.of(context).pop(); } else { try { await Provider.of<Products>(context, listen: false) .addProduct(_editedProduct); } catch (error) { await showDialog<Null>( context: context, builder: (ctx) => AlertDialog( title: Text('An error occurred!'), content: Text('Something went wrong.'), actions: [ TextButton( onPressed: () { Navigator.of(ctx).pop(); }, child: Text('Okay'), ) ], ), ); } finally { setState(() { _isLoading = false; }); Navigator.of(context).pop(); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Edit Product'), actions: [ IconButton( icon: Icon(Icons.save), onPressed: _saveForm, ), ], ), body: _isLoading ? Center( child: CircularProgressIndicator(), ) : Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _form, child: ListView( children: [ TextFormField( initialValue: _initValues['title'], decoration: InputDecoration(labelText: 'Title'), textInputAction: TextInputAction.next, onFieldSubmitted: (_) { FocusScope.of(context).requestFocus(_priceFocusNode); }, validator: (value) { if (value!.isEmpty) { return 'Plaese provide a value.'; } return null; }, onSaved: (value) { _editedProduct = Product( id: _editedProduct!.id, isFavorite: _editedProduct!.isFavorite, title: value, description: _editedProduct!.description, price: _editedProduct!.price, imageUrl: _editedProduct!.imageUrl, ); }, ), TextFormField( initialValue: _initValues['price'], decoration: InputDecoration(labelText: 'Price'), textInputAction: TextInputAction.next, keyboardType: TextInputType.number, focusNode: _priceFocusNode, onFieldSubmitted: (_) { FocusScope.of(context) .requestFocus(_descriptionFocusNode); }, validator: (value) { if (value!.isEmpty) { return 'Plaese provide a price.'; } if (double.tryParse(value) == null) { return 'Please enter a valid number.'; } if (double.tryParse(value)! <= 0) { return 'Please enter a number greater than zero.'; } return null; }, onSaved: (value) { _editedProduct = Product( id: _editedProduct!.id, isFavorite: _editedProduct!.isFavorite, title: _editedProduct!.title, description: _editedProduct!.description, price: double.parse(value!), imageUrl: _editedProduct!.imageUrl, ); }, ), TextFormField( initialValue: _initValues['description'], decoration: InputDecoration(labelText: 'Description'), maxLines: 3, keyboardType: TextInputType.multiline, focusNode: _descriptionFocusNode, validator: (value) { if (value!.isEmpty) { return 'Plaese provide a description.'; } if (value.length < 10) { return 'Should be at least 10 characters long.'; } return null; }, onSaved: (value) { _editedProduct = Product( id: _editedProduct!.id, isFavorite: _editedProduct!.isFavorite, title: _editedProduct!.title, description: value, price: _editedProduct!.price, imageUrl: _editedProduct!.imageUrl, ); }, ), Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Container( width: 100, height: 100, margin: EdgeInsets.only( top: 8, right: 10, ), decoration: BoxDecoration( border: Border.all( width: 1, color: Colors.grey, ), ), child: _imageUrlController.text.isEmpty ? Text('Enter a URL') : FittedBox( child: Image.network( _imageUrlController.text, fit: BoxFit.cover, ), ), ), Expanded( child: TextFormField( decoration: InputDecoration(labelText: 'Image URL'), keyboardType: TextInputType.url, textInputAction: TextInputAction.done, controller: _imageUrlController, focusNode: _imageUrlFocusNode, onFieldSubmitted: (_) { _saveForm(); }, validator: (value) { if (value!.isEmpty) { return 'Plaese provide an Image URL.'; } if (!value.startsWith('http') && !value.startsWith('https')) { return 'Please enter a valid URL.'; } return null; }, onSaved: (value) { _editedProduct = Product( id: _editedProduct!.id, isFavorite: _editedProduct!.isFavorite, title: _editedProduct!.title, description: _editedProduct!.description, price: _editedProduct!.price, imageUrl: value, ); }, ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/splash_screen.dart
import 'package:flutter/material.dart'; class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('Loading...'), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/product_detail.dart
import 'package:flutter/material.dart'; import '../providers/products.dart'; import 'package:provider/provider.dart'; class ProductDetailScreen extends StatelessWidget { static const routeName = '/product-detail'; @override Widget build(BuildContext context) { final productId = ModalRoute.of(context)!.settings.arguments as String?; final loadedProduct = Provider.of<Products>( context, listen: false, ).findById(productId)!; return Scaffold( appBar: AppBar( title: Text(loadedProduct.title!), ), body: SingleChildScrollView( child: Column( children: [ Container( constraints: BoxConstraints(minWidth: 100, maxWidth: 640), width: double.infinity, height: 300, child: Image.network( loadedProduct.imageUrl!, fit: BoxFit.cover, ), ), SizedBox( height: 19, ), Text( '\$${loadedProduct.price}', style: TextStyle( color: Colors.grey, fontSize: 20, ), ), SizedBox( height: 10, ), Container( padding: EdgeInsets.symmetric(horizontal: 10), width: double.infinity, child: Center( child: Container( constraints: BoxConstraints(minWidth: 100, maxWidth: 640), child: Text( loadedProduct.description!, textAlign: TextAlign.center, softWrap: true, ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/orders_screen.dart
import 'package:flutter/material.dart'; import '../providers/orders.dart' show Orders; import '../widgets/app_drawer.dart'; import '../widgets/order_item.dart'; import 'package:provider/provider.dart'; class OrdersScreen extends StatelessWidget { static const routeName = '/orders'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Your Orders'), ), drawer: AppDrawer(), body: FutureBuilder( future: Provider.of<Orders>(context, listen: false).fetchAndSetOrders(), builder: (ctx, dataSnapshot) { if (dataSnapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else { if (dataSnapshot.error != null) { return Center( child: Text('An error occurred'), ); } else { return Consumer<Orders>( builder: (ctx, orderData, child) => Center( child: Container( constraints: BoxConstraints(minWidth: 100, maxWidth: 640), child: ListView.builder( itemBuilder: (ctx, i) => OrderItem( orderData.orders[i], ), itemCount: orderData.orders.length, ), ), ), ); } } }, ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/screens/auth_screen.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import '../model/http_exception.dart'; import '../providers/auth.dart'; import 'package:provider/provider.dart'; enum AuthMode { Signup, Login } class AuthScreen extends StatelessWidget { static const routeName = '/auth'; @override Widget build(BuildContext context) { final deviceSize = MediaQuery.of(context).size; // final transformConfig = Matrix4.rotationZ(-8 * pi / 180); // transformConfig.translate(-10.0); return Scaffold( // resizeToAvoidBottomInset: false, body: Stack( children: <Widget>[ Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color.fromRGBO(215, 117, 255, 1).withOpacity(0.5), Color.fromRGBO(255, 188, 117, 1).withOpacity(0.9), ], begin: Alignment.topLeft, end: Alignment.bottomRight, stops: [0, 1], ), ), ), SingleChildScrollView( child: Container( height: deviceSize.height * 0.62, width: deviceSize.width, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Flexible( child: Container( margin: EdgeInsets.only(bottom: 20.0), padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 94.0), transform: Matrix4.rotationZ(-8 * pi / 180) ..translate(-10.0), // ..translate(-10.0), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Colors.deepOrange.shade900, boxShadow: [ BoxShadow( blurRadius: 8, color: Colors.black26, offset: Offset(0, 2), ) ], ), child: Text( 'Store', style: GoogleFonts.anton( textStyle: TextStyle( color: Colors.white, letterSpacing: .5, fontSize: 50, fontWeight: FontWeight.normal, ), ), ), ), ), Flexible( flex: deviceSize.width > 600 ? 2 : 1, child: AuthCard(), ), ], ), ), ), ], ), ); } } class AuthCard extends StatefulWidget { const AuthCard({ Key? key, }) : super(key: key); @override _AuthCardState createState() => _AuthCardState(); } class _AuthCardState extends State<AuthCard> with SingleTickerProviderStateMixin { final GlobalKey<FormState> _formKey = GlobalKey(); AuthMode _authMode = AuthMode.Login; Map<String, String?> _authData = { 'email': '', 'password': '', }; var _isLoading = false; final _passwordController = TextEditingController(); late AnimationController _controller; late Animation<Offset> _slideAnimation; late Animation<double> _opacityAnimation; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: Duration( milliseconds: 300, ), ); _slideAnimation = Tween<Offset>( begin: Offset( 0.0, -1.5, ), end: Offset( 0.0, 0.0, )).animate( CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn), ); //_heightAnimation.addListener( // () => setState(() {}), //); _opacityAnimation = Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation( parent: _controller, curve: Curves.easeIn, ), ); } @override void dispose() { super.dispose(); _controller.dispose(); } void _showErrorDialog(String message) { showDialog( context: context, builder: (ctx) => AlertDialog( title: Text( 'An Error Occurred!', ), content: Text(message), actions: [ TextButton( onPressed: () { Navigator.of(ctx).pop(); }, child: Text('Okay'), ), ], ), ); } Future<void> _submit() async { if (!_formKey.currentState!.validate()) { // Invalid! return; } _formKey.currentState!.save(); setState(() { _isLoading = true; }); try { if (_authMode == AuthMode.Login) { // Log user in await Provider.of<Auth>(context, listen: false).signin( _authData['email'], _authData['password'], ); } else { // Sign user up await Provider.of<Auth>(context, listen: false).signup( _authData['email'], _authData['password'], ); } } on HttpException catch (error) { var errorMessage = 'Authentication failed.'; if (error.message!.contains('EMAIL_EXISTS')) { errorMessage = 'This email address is already in use.'; } else if (error.message!.contains('INVALID_EMAIL')) { errorMessage = 'This is not a valid email address.'; } else if (error.message!.contains('WEAK_PASSWORD')) { errorMessage = 'This password is too weak.'; } else if (error.message!.contains('EMAIL_NOT_FOUND')) { errorMessage = 'Could not find a user with that email.'; } else if (error.message!.contains('INVALID_PASSWORD')) { errorMessage = 'Invalid password.'; } _showErrorDialog(errorMessage); } catch (error) { const errorMessage = 'Could not authenticate you. Please try again later.'; _showErrorDialog(errorMessage); } setState(() { _isLoading = false; }); } void _switchAuthMode() { if (_authMode == AuthMode.Login) { setState(() { _authMode = AuthMode.Signup; }); _controller.forward(); } else { setState(() { _authMode = AuthMode.Login; }); _controller.reverse(); } } @override Widget build(BuildContext context) { final deviceSize = MediaQuery.of(context).size; return Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), elevation: 8.0, child: AnimatedContainer( duration: Duration(milliseconds: 300), curve: Curves.easeIn, height: _authMode == AuthMode.Signup ? 320 : 260, //height: _heightAnimation.value.height, constraints: BoxConstraints( minHeight: _authMode == AuthMode.Signup ? 320 : 260, minWidth: 100, maxWidth: 420, ), width: deviceSize.width * 0.75, padding: EdgeInsets.all(16.0), child: Form( key: _formKey, child: SingleChildScrollView( child: Column( children: <Widget>[ TextFormField( decoration: InputDecoration(labelText: 'E-Mail'), keyboardType: TextInputType.emailAddress, validator: (value) { if (value!.isEmpty || !value.contains('@')) { return 'Invalid email!'; } return null; }, onSaved: (value) { _authData['email'] = value; }, ), TextFormField( decoration: InputDecoration(labelText: 'Password'), obscureText: true, controller: _passwordController, validator: (value) { if (value!.isEmpty || value.length < 5) { return 'Password is too short!'; } return null; }, onSaved: (value) { _authData['password'] = value; }, ), AnimatedContainer( constraints: BoxConstraints( minHeight: _authMode == AuthMode.Signup ? 60 : 0, maxHeight: _authMode == AuthMode.Signup ? 120 : 0), duration: Duration( milliseconds: 300, ), curve: Curves.easeIn, child: FadeTransition( opacity: _opacityAnimation, child: SlideTransition( position: _slideAnimation, child: TextFormField( enabled: _authMode == AuthMode.Signup, decoration: InputDecoration(labelText: 'Confirm Password'), obscureText: true, validator: _authMode == AuthMode.Signup ? (value) { if (value != _passwordController.text) { return 'Passwords do not match!'; } return null; } : null, ), ), ), ), SizedBox( height: 20, ), if (_isLoading) CircularProgressIndicator() else ElevatedButton( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 30.0, vertical: 8.0), child: Text( _authMode == AuthMode.Login ? 'LOGIN' : 'SIGN UP'), ), onPressed: _submit, style: ElevatedButton.styleFrom( foregroundColor: Theme.of(context) .primaryTextTheme .labelLarge! .color, backgroundColor: Theme.of(context).primaryColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), // Text Color (Foreground color) ), ), TextButton( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 30.0, vertical: 4), child: Text( '${_authMode == AuthMode.Login ? 'SIGNUP' : 'LOGIN'} INSTEAD'), ), onPressed: _switchAuthMode, style: TextButton.styleFrom( foregroundColor: Theme.of(context) .primaryColor, tapTargetSize: MaterialTapTargetSize.shrinkWrap, // Text Color (Foreground color) ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/providers/cart.dart
import 'package:flutter/material.dart'; class CartItem { final String? id; final String? title; final int? quantity; final double? price; CartItem({ required this.id, required this.title, required this.quantity, required this.price, }); } class Cart with ChangeNotifier { Map<String?, CartItem> _items = {}; Map<String?, CartItem> get items { return {..._items}; } int get itemsCount { return _items.length; } double get totalAmount { var total = 0.0; _items.forEach((key, value) { total += value.price! * value.quantity!; }); return total; } void addItem( String? productId, double? price, String? title, ) { if (_items.containsKey(productId)) { _items.update( productId, (value) => CartItem( id: value.id, title: value.title, price: value.price, quantity: value.quantity! + 1, ), ); } else { _items.putIfAbsent( productId, () => CartItem( id: DateTime.now().toString(), title: title, price: price, quantity: 1, ), ); } notifyListeners(); } void removeItem(String? productId) { _items.remove(productId); notifyListeners(); } void removeSigleItem(String? productId) { if (!_items.containsKey(productId)) { return; } if (_items[productId]!.quantity! > 1) { _items.update( productId, (value) => CartItem( id: value.id, title: value.title, quantity: value.quantity! - 1, price: value.price, ), ); } else { _items.remove(productId); } notifyListeners(); } void clear() { _items = {}; notifyListeners(); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/providers/auth.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:http/http.dart' as http; import '../model/http_exception.dart'; import 'package:shared_preferences/shared_preferences.dart'; class Auth with ChangeNotifier { static const _key = 'FIREBASE_WEB_API_KEY'; static const URL = 'FIREBASE_IO_URL'; String? _token; DateTime? _expiryDate; String? _userId; Timer? _authTimer; bool _authRequired = false; String? get userId { return _userId; } String? get token { if (_expiryDate != null && _expiryDate!.isAfter(DateTime.now()) && _token != null) { return _token; } return null; } bool get isAuth { if (!_authRequired) { return true; } return token != null; } Future<void> _authenticate( String? email, String? password, String urlSegment) async { final url = 'https://identitytoolkit.googleapis.com/v1/accounts:$urlSegment?key=$_key'; try { final response = await http.post( Uri.parse(url), body: json.encode({ 'email': email, 'password': password, 'returnSecureToken': true, }), ); final responseData = json.decode(response.body); if (responseData['error'] != null) { throw HttpException(responseData['error']['message']); } _token = responseData['idToken']; _userId = responseData['localId']; _expiryDate = DateTime.now().add( Duration( seconds: int.parse( responseData['expiresIn'], ), ), ); _autoLogout(); notifyListeners(); final prefs = await SharedPreferences.getInstance(); final userData = json.encode( { 'token': _token, 'userId': _userId, 'expiryDate': _expiryDate!.toIso8601String(), }, ); prefs.setString('userData', userData); } catch (error) { throw error; } } Future<bool> tryAutoLogin() async { final prefs = await SharedPreferences.getInstance(); if (!prefs.containsKey('userData')) { return false; } final extractedUserData = json.decode(prefs.getString('userData')!) as Map<String, Object>; final expiryDate = DateTime.parse(extractedUserData['expiryDate'] as String); if (expiryDate.isBefore(DateTime.now())) { return false; } _token = extractedUserData['token'] as String?; _expiryDate = expiryDate; _userId = extractedUserData['userId'] as String?; notifyListeners(); _autoLogout(); return true; } Future<void> signup(String? email, String? password) async { return _authenticate(email, password, 'signUp'); } Future<void> signin(String? email, String? password) async { return _authenticate(email, password, 'signInWithPassword'); } Future<void> logout() async { _token = null; _userId = null; _expiryDate = null; if (_authTimer != null) { _authTimer!.cancel(); } notifyListeners(); final prefs = await SharedPreferences.getInstance(); prefs.clear(); } void _autoLogout() { if (_authTimer != null) { _authTimer!.cancel(); } final timerToExpiry = _expiryDate!.difference(DateTime.now()).inSeconds; _authTimer = Timer(Duration(seconds: timerToExpiry), logout); } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/providers/orders.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import './cart.dart'; import 'auth.dart'; class OrderItem { final String? id; final double? amount; final List<CartItem> products; final DateTime dateTime; OrderItem({ required this.id, required this.amount, required this.products, required this.dateTime, }); } class Orders with ChangeNotifier { List<OrderItem> _orders = []; final String? authToken; final String? userId; Orders(this.authToken, this.userId, this._orders); List<OrderItem> get orders { return [..._orders]; } Future<void> fetchAndSetOrders() async { if (authToken == null) { return; } final url = Auth.URL + '/orders/$userId.json?auth=$authToken'; try { final response = await http.get(Uri.parse(url)); final extractedData = json.decode(response.body) as Map<String, dynamic>?; if (extractedData == null) { return; } final List<OrderItem> loadedOrders = []; extractedData.forEach((orderId, orderData) { loadedOrders.add( OrderItem( id: orderId, amount: orderData['amount'], dateTime: DateTime.parse( orderData['dateTime'], ), products: (orderData['products'] as List<dynamic>) .map((e) => CartItem( id: e['id'], title: e['title'], quantity: e['quantity'], price: e['price'], )) .toList(), ), ); }); _orders = loadedOrders.reversed.toList(); notifyListeners(); } catch (error) { //throw (error); } } Future<void> addOrder(List<CartItem> cartProducts, double total) async { final url = Auth.URL + '/orders/$userId.json?auth=$authToken'; final activeOrdersUrl = Auth.URL + '/orders/active.json?auth=$authToken'; final timestamp = DateTime.now(); try { if (authToken != null) { final response = await http.post( Uri.parse(url), body: json.encode({ 'amount': total, 'dateTime': timestamp.toIso8601String(), 'products': cartProducts .map((e) => { 'id': e.id, 'title': e.title, 'quantity': e.quantity, 'price': e.price, }) .toList(), }), ); _orders.insert( 0, OrderItem( id: json.decode(response.body)['name'], amount: total, dateTime: timestamp, products: cartProducts, ), ); } else { _orders.insert( 0, OrderItem( id: timestamp.toIso8601String(), amount: total, dateTime: timestamp, products: cartProducts, ), ); } notifyListeners(); if (authToken != null) { await http.post( Uri.parse(activeOrdersUrl), body: json.encode({ 'amount': total, 'dateTime': timestamp.toIso8601String(), 'userId': userId, 'products': cartProducts .map((e) => { 'id': e.id, 'title': e.title, 'quantity': e.quantity, 'price': e.price, }) .toList(), }), ); } } catch (error) { //throw error; } } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/providers/product.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'auth.dart'; class Product with ChangeNotifier { final String? id; final String? title; final String? description; final double? price; final String? imageUrl; bool? isFavorite; Product({ required this.id, required this.title, required this.description, required this.price, required this.imageUrl, this.isFavorite = false, }); Map<String, dynamic> toJson() { return { 'id': id, 'title': title, 'description': description, 'price': price, 'imageUrl': imageUrl, 'isFavorite': isFavorite, }; } Future<void> toggleFavoriteStatus(String? token, String? userId) async { final oldStatus = isFavorite; isFavorite = !isFavorite!; notifyListeners(); if (token != null) { final url = Auth.URL + '/userFavorites/$userId/$id.json?auth=$token'; try { final response = await http.put( Uri.parse(url), body: json.encode( isFavorite, ), ); if (response.statusCode >= 400) { isFavorite = oldStatus; notifyListeners(); } } catch (error) { isFavorite = oldStatus; notifyListeners(); print(error); } } } }
0
mirrored_repositories/mobile-orders/flutter/app/lib
mirrored_repositories/mobile-orders/flutter/app/lib/providers/products.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import '../model/http_exception.dart'; import '../providers/product.dart'; import 'package:http/http.dart' as http; import 'auth.dart'; class Products with ChangeNotifier { static List<Product?> defaultProducts = [ /*Product( id: 'p1', title: 'Chair', description: 'The chair combines comfort with bold contemporary forms.', price: 29.99, imageUrl: 'https://glowbom.netlify.app/v1.1.3/img/presets/store/chair-small.jpg', ), Product( id: 'p2', title: 'Couch', description: 'This is the most comfortable couch ever.', price: 59.99, imageUrl: 'https://glowbom.netlify.app/v1.1.3/img/presets/store/couch-small.jpg', ), Product( id: 'p3', title: 'Table', description: 'Perfect for family meals and dinner parties.', price: 19.99, imageUrl: 'https://glowbom.netlify.app/v1.1.3/img/presets/store/table-small.jpg', ), Product( id: 'p4', title: 'Bed', description: 'It works with all mattresses.', price: 49.99, imageUrl: 'https://glowbom.netlify.app/v1.1.3/img/presets/store/bed-small.jpg', ),*/ ]; List<Product?>? _items = defaultProducts; static List<Product?> get copyDefaultProducts { return [...defaultProducts]; } List<Product?> get items { return [..._items!]; } List<Product?> get favoriteItems { return _items!.where((element) => element!.isFavorite!).toList(); } Product? findById(String? id) { return _items!.firstWhere((prod) => prod!.id == id); } final String? authToken; final String? userId; Products(this.authToken, this.userId, this._items); Future<void> fetchAndSetProducts([bool filterByUser = false]) async { // In order to filter by userId on the server side // 1. url = Auth.URL + '/products.json?auth=$authToken&orderBy="creatorId"&equalTo="$userId"'; // 2. set index on Firebase Rules // "products": { // ".indexOn": ["creatorId"] // } if (authToken == null) { return; } String filterString = filterByUser ? '&orderBy="creatorId"&equalTo="$userId"' : ''; var url = Auth.URL + '/products.json?auth=$authToken$filterString'; try { final response = await http.get(Uri.parse(url)); final extractedData = json.decode(response.body) as Map<String, dynamic>?; if (extractedData == null) { return; } url = Auth.URL + '/userFavorites/$userId.json?auth=$authToken'; final favoriteResponse = await http.get(Uri.parse(url)); final favoriteData = json.decode(favoriteResponse.body) as Map<String, dynamic>?; final List<Product?> loadedProducts = []; extractedData.forEach((prodId, prodData) { loadedProducts.add( Product( id: prodId, title: prodData['title'], description: prodData['description'], price: prodData['price'], imageUrl: prodData['imageUrl'], isFavorite: favoriteData == null ? false : favoriteData[prodId] ?? false, ), ); }); _items = loadedProducts; notifyListeners(); } catch (error) { throw (error); } } Future<void> addProduct(Product? value) async { if (authToken != null) { final url = Auth.URL + '/products.json?auth=$authToken'; try { final response = await http.post( Uri.parse(url), body: json.encode({ 'title': value!.title, 'description': value.description, 'price': value.price, 'imageUrl': value.imageUrl, 'creatorId': userId, }), ); final newProduct = Product( id: json.decode(response.body)['name'], title: value.title, description: value.description, price: value.price, imageUrl: value.imageUrl, ); _items!.add(newProduct); notifyListeners(); } catch (error) { throw error; } } else { final newProduct = Product( id: DateTime.now().toIso8601String(), title: value!.title, description: value.description, price: value.price, imageUrl: value.imageUrl, ); _items!.add(newProduct); notifyListeners(); } } Future<void> updateProduct(String? id, Product? value) async { final prodIndex = _items!.indexWhere((element) => element!.id == id); if (prodIndex >= 0) { if (authToken != null) { final url = Auth.URL + '/products/$id.json?auth=$authToken'; await http.patch( Uri.parse(url), body: json.encode({ 'title': value!.title, 'description': value.description, 'price': value.price, 'imageUrl': value.imageUrl, }), ); } _items![prodIndex] = value; notifyListeners(); } } Future<void> deleteProduct(String? id) async { final url = Auth.URL + '/products/$id.json?auth=$authToken'; final existingProductIndex = _items!.indexWhere((element) => element!.id == id); var existingProduct = _items![existingProductIndex]; _items!.removeAt(existingProductIndex); notifyListeners(); if (authToken != null) { try { final response = await http.delete(Uri.parse(url)); if (response.statusCode >= 400) { throw HttpException('Could not delete product.'); } existingProduct = null; } catch (error) { _items!.insert(existingProductIndex, existingProduct); notifyListeners(); } } } }
0
mirrored_repositories/mobile-orders/flutter/app
mirrored_repositories/mobile-orders/flutter/app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // 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/CMS
mirrored_repositories/CMS/lib/routes.dart
import 'package:cms/screens/add-class-work.dart'; import 'package:cms/screens/classwork.dart'; import 'package:cms/screens/forgot-password.dart'; import 'package:cms/screens/group-info.dart'; import 'package:cms/screens/onboarding-screen.dart'; import 'package:cms/screens/profile-settings.dart'; import 'package:cms/screens/add-group.dart'; import 'package:cms/screens/add-image.dart'; import 'package:cms/screens/group-screen.dart'; import 'package:cms/screens/image-resource.dart'; import 'package:cms/screens/login.dart'; import 'package:cms/screens/register.dart'; import 'package:cms/screens/teacher-profile-update.dart'; import 'package:cms/screens/teacher-profile.dart'; import 'package:cms/screens/video.resource.dart'; import 'package:cms/screens/welcome-page.dart'; import 'package:cms/student-screens/quiz.dart'; import 'package:cms/student-screens/student-group-screen.dart'; import 'package:cms/student-screens/student-image-resources.dart'; import 'package:cms/student-screens/student-multi-profile.dart'; import 'package:cms/student-screens/student-resources.dart'; import 'package:cms/student-screens/student-video-resources.dart'; import 'package:cms/student-screens/teacher-profile-2.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:cms/components/task-data.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'screens/add-video.dart'; import 'screens/chat-screen.dart'; import 'screens/login-varification.dart'; import 'screens/logreg-page.dart'; import 'screens/resource.dart'; import 'screens/teacher-edit-profile.dart'; import 'student-screens/join-group.dart'; import 'student-screens/student-login-verification.dart'; import 'student-screens/student-login.dart'; import 'student-screens/student-profile-update.dart'; import 'student-screens/student-profile.dart'; import 'student-screens/student-register.dart'; import 'student-screens/student-verification.dart'; import 'screens/subgroup-screen.dart'; import 'screens/varification.dart'; import 'student-screens/stundet-edit-profile.dart'; import 'package:shared_preferences/shared_preferences.dart'; class Routes extends StatefulWidget { const Routes({Key? key}) : super(key: key); @override _RoutesState createState() => _RoutesState(); } class _RoutesState extends State<Routes> { String currentPage = OnBoardingScreen.id; @override void initState() { // TODO: implement initState super.initState(); getStart(); } void getStart()async{ final _auth = FirebaseAuth.instance; final user = _auth.currentUser; if(user!=null){ List<String> splitted = user.displayName!.split(' '); if(splitted[splitted.length-1] != "student"){ currentPage = Groups.id; } else{ currentPage = StudentGroupScreen.id; } await Future.delayed(Duration(milliseconds: 1000),(){ Provider.of<TaskData>(context,listen: false).getUser(); }); } SharedPreferences prefs = await SharedPreferences.getInstance(); bool _seen = (prefs.getBool('seen') ?? false); if (_seen == false){ await prefs.setBool('seen', true); currentPage = OnBoardingScreen.id; } } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, initialRoute: currentPage, routes: { WelcomePage.id: (context) => WelcomePage(), OnBoardingScreen.id: (context) => OnBoardingScreen(), LogRegPage.id: (context) => LogRegPage(), Login.id: (context) => Login(), ForgotPassword.id: (context) => ForgotPassword(), Register.id: (context) => const Register(), Varification.id: (context) => Varification(), LoginVarification.id: (context) => LoginVarification(), TeacherProfileUpdate.id: (context) => TeacherProfileUpdate(), TeacherProfile.id: (context) => TeacherProfile(), TeacherEditProfile.id:(context) => TeacherEditProfile(), AddGroup.id: (context) => AddGroup(), SubGroups.id: (context) => SubGroups(), ChatScreen.id: (context) => ChatScreen(), Groups.id: (context) => Groups(), GroupInfo.id:(context) => GroupInfo(), Resources.id: (context) => Resources(), ImageResources.id: (context) => ImageResources(), AddImage.id:(context) => AddImage(), VideoResources.id: (context) => VideoResources(), AddVideo.id: (context) => AddVideo(), Classwork.id: (context) => Classwork(), AddClassWork.id: (context) => AddClassWork(), ProfileSettings.id: (context) => ProfileSettings(), StudentLogin.id: (context) => StudentLogin(), StudentRegister.id: (context) => StudentRegister(), StudentGroupScreen.id: (context) => StudentGroupScreen(), StudentVerification.id: (context) => StudentVerification(), StudentLoginVerification.id: (context) => StudentLoginVerification(), StudentProfileUpdate.id: (context) => StudentProfileUpdate(), StudentProfile.id: (context) => StudentProfile(), StudentMultiProfile.id: (context) => StudentMultiProfile(), StudentEditProfile.id: (context) => StudentEditProfile(), StudentResources.id:(context) => StudentResources(), StudentImageResources.id: (context) => StudentImageResources(), StudentVideoResources.id: (context) => StudentVideoResources(), TeacherProfile2.id:(context) => TeacherProfile2(), JoinGroup.id: (context) => JoinGroup(), Quiz.id:(context) => Quiz(), }, ); } }
0
mirrored_repositories/CMS
mirrored_repositories/CMS/lib/main.dart
import 'package:cms/components/task-data.dart'; import 'package:cms/routes.dart'; import 'package:cms/screens/group-screen.dart'; import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:provider/provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return ChangeNotifierProvider( create: (context) => TaskData(), child:const Routes(), ); } }
0
mirrored_repositories/CMS/lib
mirrored_repositories/CMS/lib/components/multi-dropdown-field.dart
import 'dart:core'; import 'package:flutter/material.dart'; import 'package:multi_select_flutter/chip_display/multi_select_chip_display.dart'; import 'package:multi_select_flutter/dialog/multi_select_dialog_field.dart'; import 'package:multi_select_flutter/util/multi_select_item.dart'; import 'package:multi_select_flutter/util/multi_select_list_type.dart'; class MultiDropdownField extends StatelessWidget { const MultiDropdownField(this.title,this.dropdownValue, this.items,this.onChangedCallback); final title; final String dropdownValue; final List<String> items; final Function(List<dynamic>)onChangedCallback; @override Widget build(BuildContext context) { return MultiSelectDialogField( items: items .map((e) => MultiSelectItem(e, e)) .toList(), listType: MultiSelectListType.LIST, checkColor: Colors.white, selectedColor: Color(0xFF13192F), title: Text(title), onConfirm: onChangedCallback, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(15)), border: Border.all( color: Color(0xFF13192F), width: 2, ), ), buttonText: Text( dropdownValue, style: TextStyle( color: Color(0xFF13192F), fontSize: 16, ), ), buttonIcon: Icon(Icons.keyboard_arrow_down), chipDisplay: MultiSelectChipDisplay.none(), ); } }
0
mirrored_repositories/CMS/lib
mirrored_repositories/CMS/lib/components/custom-drawer.dart
import 'package:cms/components/task-data.dart'; import 'package:cms/screens/group-screen.dart'; import 'package:cms/screens/subgroup-screen.dart'; import 'package:cms/screens/teacher-profile.dart'; import 'package:cms/screens/welcome-page.dart'; import 'package:cms/student-screens/student-group-screen.dart'; import 'package:cms/student-screens/student-profile.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../screens/profile-settings.dart'; class CustomDrawer extends StatelessWidget { @override Widget build(BuildContext context) { bool stud = Provider.of<TaskData>(context).isStudent; return Drawer( backgroundColor: Colors.white, child: ListView( padding: EdgeInsets.zero, children: <Widget>[ DrawerHeader( padding: EdgeInsets.only(top: 0,bottom: 0,left: 15.0), decoration: BoxDecoration( color: Color(0xFF13192F)), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: [ CircleAvatar( radius: 42.0, backgroundColor: Colors.white, child: CircleAvatar( backgroundColor: Colors.white, backgroundImage: Provider.of<TaskData>( context) .userPhoto == '' ? NetworkImage('https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png') : NetworkImage(Provider.of< TaskData>(context) .userPhoto), radius: 40.0, ), ), const SizedBox( height: 10.0, ), Text( Provider.of<TaskData>(context).userName, style: const TextStyle( color: Colors.white, fontSize: 24, backgroundColor: Color(0xFF13192F), ), ), ], ), ), Container( decoration: const BoxDecoration(color: Colors.white), child: Column( children: [ GestureDetector( child: const ListTile( leading: Icon(Icons.group), title: Text('Groups'), ), onTap: (){ String nextPage; stud ? nextPage = StudentGroupScreen.id : nextPage = Groups.id; Navigator.pushNamed(context,nextPage); }, ), GestureDetector( child: const ListTile( leading: Icon(Icons.account_circle), title: Text('Profile'), ), onTap: (){ String nextPage; stud ? nextPage = StudentProfile.id : nextPage = TeacherProfile.id; Navigator.pushNamed(context, nextPage); }, ), GestureDetector( child: const ListTile( leading: Icon(Icons.settings), title: Text('Settings'), ), onTap: (){ Navigator.pushNamed(context, ProfileSettings.id); }, ), GestureDetector( child: const ListTile( leading: Icon(Icons.logout), title: Text('Logout'), ), onTap: () { Provider.of<TaskData>(context, listen: false).logOut(); Navigator.pushNamed(context, WelcomePage.id); }) ], ), ), ], ), ); } }
0