repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/adoptini-app/lib/auth/domain
mirrored_repositories/adoptini-app/lib/auth/domain/usecases/start_app_usecase.dart
import 'package:adoptini_app/auth/data/models/user_model.dart'; import 'package:adoptini_app/auth/domain/repositories/base_auth_repo.dart'; import 'package:injectable/injectable.dart'; @injectable class StartAppUsecase { final BaseAuthRepo _authRepository; StartAppUsecase( this._authRepository, ); Future<UserModel?> call() async { final user = await _authRepository.getUserData(); if (user == null) return null; return user; } }
0
mirrored_repositories/adoptini-app/lib/auth/domain
mirrored_repositories/adoptini-app/lib/auth/domain/usecases/register_usecase.dart
import 'package:adoptini_app/auth/data/datasources/location_service.dart'; import 'package:adoptini_app/auth/data/models/user_model.dart'; import 'package:adoptini_app/auth/domain/repositories/base_auth_repo.dart'; import 'package:adoptini_app/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:injectable/injectable.dart'; import 'package:isar/isar.dart'; @Injectable() class RegisterUsecase { final BaseAuthRepo _authRepository; final BaseLocationService _locationService; RegisterUsecase(this._authRepository, this._locationService); Future<UserModel> call(String name, String email, String password) async { final locationData = await _locationService.getLocation(); if (locationData.city.isNotEmpty) { final city = locationData.city; final country = locationData.country; const uid = Isar.autoIncrement; final userModel = UserModel( id: uid, uid: uid.toString(), name: name, email: email, longitude: locationData.longitude, latitude: locationData.latitude, city: city, country: country, ); final myUser =await _authRepository.registerUser(user: userModel, password: password); return myUser; } else { throw Exception(LocaleKeys.failed_to_save_user.tr()); } } }
0
mirrored_repositories/adoptini-app/lib/auth/domain
mirrored_repositories/adoptini-app/lib/auth/domain/usecases/logout_usecase.dart
import 'package:adoptini_app/auth/domain/repositories/base_auth_repo.dart'; import 'package:injectable/injectable.dart'; @injectable class LogoutUseCase { final BaseAuthRepo _authRepository; LogoutUseCase(this._authRepository); Future<void> call() async { return _authRepository.logout(); } }
0
mirrored_repositories/adoptini-app/lib/auth/domain
mirrored_repositories/adoptini-app/lib/auth/domain/usecases/login_usecase.dart
import 'package:adoptini_app/auth/data/models/user_model.dart'; import 'package:adoptini_app/auth/domain/repositories/base_auth_repo.dart'; import 'package:injectable/injectable.dart'; @Injectable() class LoginUsecase { final BaseAuthRepo _authRepository; LoginUsecase(this._authRepository); Future<UserModel> call(String email, String password) async { return await _authRepository.login(email: email, password: password); } }
0
mirrored_repositories/adoptini-app/lib/auth/domain
mirrored_repositories/adoptini-app/lib/auth/domain/usecases/update_user_usercase.dart
import 'package:adoptini_app/auth/data/models/user_model.dart'; import 'package:adoptini_app/auth/domain/repositories/base_auth_repo.dart'; import 'package:injectable/injectable.dart'; @Injectable() class UpdateUserUsecase { final BaseAuthRepo _authRepository; UpdateUserUsecase(this._authRepository); Future<void> call(UserModel currentUser) async { await _authRepository.updateUser(currentUser: currentUser); } }
0
mirrored_repositories/adoptini-app/lib/auth/domain
mirrored_repositories/adoptini-app/lib/auth/domain/usecases/update_user_location_usecase.dart
import 'package:adoptini_app/auth/domain/repositories/base_auth_repo.dart'; import 'package:adoptini_app/generated/locale_keys.g.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:geolocator/geolocator.dart'; import 'package:injectable/injectable.dart'; @injectable class UpdateUserLocationUsecase { final BaseAuthRepo _authRepository; UpdateUserLocationUsecase( this._authRepository, ); Future<void> call(String uid) async { bool serviceEnabled; LocationPermission permission; serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { return Future.error(LocaleKeys.location_disabled); } permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { return Future.error(LocaleKeys.location_permission_denied.tr()); } } if (permission == LocationPermission.deniedForever) { return Future.error(LocaleKeys.location_permission_denied_permanetly.tr()); } Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, ); final lat = position.latitude; final lng = position.longitude; await _authRepository.updateUserLocation(uid: uid, lng: lng, lat: lat); } }
0
mirrored_repositories/adoptini-app/lib
mirrored_repositories/adoptini-app/lib/utils/register_module.dart
import 'package:adoptini_app/auth/data/models/user_model.dart'; import 'package:adoptini_app/core/settings/data/models/settings_model.dart'; import 'package:injectable/injectable.dart'; import 'package:isar/isar.dart'; import 'package:path_provider/path_provider.dart'; @module abstract class RegisterModule { @preResolve Future<Isar> get isar async { var instance = Isar.getInstance('LocalDb'); if (instance == null) { final dir = await getApplicationSupportDirectory(); instance = await Isar.open( [ UserModelSchema, SettingsModelSchema, ], directory: dir.path, name: 'LocalDb', ); } return instance; } }
0
mirrored_repositories/adoptini-app/lib
mirrored_repositories/adoptini-app/lib/utils/package_info_wrapper.dart
import 'package:package_info_plus/package_info_plus.dart'; class PackageInfoWrapper { PackageInfoWrapper._(); static final PackageInfoWrapper _instance = PackageInfoWrapper._(); static PackageInfoWrapper get instance { return _instance; } PackageInfo? _packageInfo; Future<PackageInfo> init() async { return _packageInfo ??= await PackageInfo.fromPlatform(); } String get appName { if (_packageInfo == null) { throw Exception('PackageInfoWrapper not initialized'); } return _packageInfo!.appName; } String get packageName { if (_packageInfo == null) { throw Exception('PackageInfoWrapper not initialized'); } return _packageInfo!.packageName; } String get version { if (_packageInfo == null) { throw Exception('PackageInfoWrapper not initialized'); } return _packageInfo!.version; } String get buildNumber { if (_packageInfo == null) { throw Exception('PackageInfoWrapper not initialized'); } return _packageInfo!.buildNumber; } }
0
mirrored_repositories/adoptini-app/lib
mirrored_repositories/adoptini-app/lib/utils/utils.dart
import 'dart:math'; import 'package:adoptini_app/common/enums.dart'; import 'package:flutter/material.dart'; Locale languageToLocales(Languages? language) { switch (language) { case Languages.english: return const Locale('en'); case Languages.french: return const Locale('fr'); case Languages.arabic: return const Locale('ar'); default: return const Locale('en'); } } String generateRandomString(int len) { var r = Random(); String randomString = String.fromCharCodes(List.generate(len, (index) => r.nextInt(33) + 89)); return randomString; }
0
mirrored_repositories/adoptini-app/lib
mirrored_repositories/adoptini-app/lib/utils/extensions.dart
extension StringExtension on String { String capitalize() { return "${this[0].toUpperCase()}${substring(1)}"; } } extension NumberRounding on double { double toPrecision(int precision) { return double.parse((this).toStringAsFixed(precision)).toDouble(); } }
0
mirrored_repositories/adoptini-app
mirrored_repositories/adoptini-app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:adoptini_app/app.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const App()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/dependancy_injection.dart
import 'package:get_it/get_it.dart'; import 'package:internet_connection_checker/internet_connection_checker.dart'; import 'package:shopack_user/core/network/payment_api_provider_impl.dart'; import 'package:shopack_user/core/theme/bloc/theme_bloc.dart'; import 'package:shopack_user/features/cart/data/datasource/placesAPI.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cart_bloc.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cubit/address_cubit.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import 'package:shopack_user/features/favorite/presentation/bloc/favourite_bloc.dart'; import 'package:shopack_user/features/payment/data/datasources/payment_datasource.dart'; import 'package:shopack_user/features/payment/data/repositrories/payment_repository_impl.dart'; import 'package:shopack_user/features/payment/domain/repositories/payment_repository.dart'; import 'package:shopack_user/features/payment/domain/usecases/createNewOrder_Usecase.dart'; import 'package:shopack_user/features/payment/domain/usecases/getAllOrders.dart'; import 'package:shopack_user/features/payment/domain/usecases/requestAuth_Usecase.dart'; import 'package:shopack_user/features/payment/presentation/bloc/order_bloc.dart'; import 'package:shopack_user/features/payment/presentation/bloc/payment_bloc.dart'; import 'package:shopack_user/features/shop/domain/usecases/getAllReviews.dart'; import 'core/network/api_provider.dart'; import 'core/network/api_provider_impl.dart'; import 'core/network/network_info.dart'; import 'core/network/paymentApiProvider.dart'; import 'features/forgotpass&verifyemail/data/datasources/forgotpassword_datasource.dart'; import 'features/forgotpass&verifyemail/data/repositories/forgotpassword_repositoryimpl.dart'; import 'features/forgotpass&verifyemail/domain/repositories/forgotpassword_repository.dart'; import 'features/forgotpass&verifyemail/domain/usecases/forgotpassword_usecase.dart'; import 'features/forgotpass&verifyemail/presentation/forgotpass&verifyemail_bloc/forgotpass&verifyemail_bloc.dart'; import 'features/home/presentation/bloc/BottomNavigationBar_bloc.dart'; import 'features/login/data/datasources/login_datasource.dart'; import 'features/login/data/repositories/login_repostory_impl.dart'; import 'features/login/domin/repositories/login_repository.dart'; import 'features/login/domin/usecases/login_usecase.dart'; import 'features/login/presentation/bloc/login_bloc.dart'; import 'features/payment/domain/usecases/requestOrder_Usecase.dart'; import 'features/payment/domain/usecases/requestPayment_Usecase.dart'; import 'features/profile/data/datasources/profile_remote_datasource.dart'; import 'features/profile/data/repositories/profile_repository_impl.dart'; import 'features/profile/domain/repositories/profile_repository.dart'; import 'features/profile/domain/usecases/getUserDetail.dart'; import 'features/profile/domain/usecases/updatePassword.dart'; import 'features/profile/domain/usecases/updateProfile.dart'; import 'features/profile/presentation/bloc/profile_bloc.dart'; import 'features/profile/presentation/bloc/update_password_bloc.dart'; import 'features/register/data/datasources/register_datasource.dart'; import 'features/register/data/repositories/register_repository_impl.dart'; import 'features/register/domain/repositories/register_repository.dart'; import 'features/register/domain/usecases/register_usecase.dart'; import 'features/register/presentation/bloc/register_bloc.dart'; import 'features/setpassword/data/datasources/Resetpassword_datasource.dart'; import 'features/setpassword/data/repositories/resetpassword_repositoryimpl.dart'; import 'features/setpassword/domain/repositories/resetPassword_repository.dart'; import 'features/setpassword/domain/usecases/resetpassword_usecase.dart'; import 'features/setpassword/presentation/bloc/reset_password_bloc.dart'; import 'features/shop/data/datasources/products_datasource.dart'; import 'features/shop/data/repositories/products_repositoryimpl.dart'; import 'features/shop/domain/repositories/product_repository.dart'; import 'features/shop/domain/usecases/getAllProducts_usecase.dart'; import 'features/shop/domain/usecases/getSpecificProduct.dart'; import 'features/shop/domain/usecases/sendReview_usecase.dart'; import 'features/shop/presentation/bloc/products_bloc.dart'; import 'features/shop/presentation/bloc/send_review_bloc.dart'; GetIt injector = GetIt.instance; Future<void> init() async { //BLoC injector.registerFactory(() => LoginBloc(injector())); injector.registerFactory(() => RegisterBloc(injector())); injector.registerFactory(() => ForgetpasswordAndeVerifyEmailBloc(injector())); injector.registerFactory(() => ResetPasswordBloc(injector())); injector.registerFactory(() => BottomNavigationBarBloc()); injector.registerFactory(() => ProductsBloc(injector(), injector())); injector.registerFactory(() => ProfileBloc(injector(), injector())); injector.registerFactory(() => UpdatePasswordBloc(injector())); injector.registerFactory(() => SendReviewBloc(injector(), injector())); injector.registerFactory(() => FavouriteBloc()); injector.registerFactory(() => CartBloc()); injector.registerFactory(() => ThemeBloc()); injector.registerFactory(() => AddressCubit(injector(), injector())); injector.registerFactory(() => LocationBloc(injector(), injector())); injector .registerFactory(() => PaymentBloc(injector(), injector(), injector())); injector.registerFactory(() => OrderBloc(injector(), injector())); //Usecase injector.registerLazySingleton(() => LoginUsecase(injector())); injector.registerLazySingleton(() => RegisterUsecase(injector())); injector.registerLazySingleton(() => ForgotPassUsecase(injector())); injector.registerLazySingleton(() => ResetPasswordUseCase(injector())); injector.registerLazySingleton(() => GetAllProductsUsecase(injector())); injector.registerLazySingleton(() => GetSpecificProductUseCase(injector())); injector.registerLazySingleton(() => GetUserDetails(injector())); injector.registerLazySingleton(() => UpdateUserDetailUsecase(injector())); injector.registerLazySingleton(() => UpdatePasswordUsecase(injector())); injector.registerLazySingleton(() => GetReviewsUsecase(injector())); injector.registerLazySingleton(() => SendReviewUsecase(injector())); injector.registerLazySingleton(() => RequestAuthUsecase(injector())); injector.registerLazySingleton(() => RequestOrderUsecase(injector())); injector.registerLazySingleton(() => RequestPaymentUsecase(injector())); injector.registerLazySingleton(() => CreateNewOrderUsecase(injector())); injector.registerLazySingleton(() => GetAllOrderesUsecase(injector())); //Repository injector.registerLazySingleton<LoginBaseRepository>( () => LoginRepositoryImpl(injector(), injector())); injector.registerLazySingleton<RegisterBaseRepository>( () => RegisterRepositoryImpl(injector(), injector())); injector.registerLazySingleton<ForgotPasswordRepo>( () => ForgotPasswordRepoImpl(injector(), injector())); injector.registerLazySingleton<ResetPasswordRepository>( () => ResetPasswordRepositoryImpl(injector(), injector())); injector.registerLazySingleton<ProductRepository>( () => ProductsRepositoryImpl(injector(), injector())); injector.registerLazySingleton<ProfileRepository>( () => ProfileRepositoryImpl(injector(), injector())); injector.registerLazySingleton<PaymentRepository>( () => PaymentRepositoryImpl(injector(), injector())); //DataSource injector.registerLazySingleton<LoginDatasource>( () => LoginDatasourceImpl(injector())); injector.registerLazySingleton<RegisterBaseDatasource>( () => RegisterDataSourceImpl(injector())); injector.registerLazySingleton<ForgetPasswordDataSource>( () => ForgetPasswordDataSourceImpl(injector())); injector.registerLazySingleton<ResetPasswordDatasource>( () => ResetPasswordDataSourceImpl(injector())); injector.registerLazySingleton<ProductsDatasource>( () => ProductsDatasourceImpl(injector())); injector.registerLazySingleton<ProfileDatasource>( () => ProfileDataSourceImpl(injector())); injector .registerLazySingleton<PlacesDataSource>(() => PlacesDatasourceImpl()); injector.registerLazySingleton<PaymentDataSource>( () => PaymentDataSourceImpl(injector(), injector())); //---Core---// //API Provider injector.registerLazySingleton<APIProvider>(() => APIProviderImpl()); injector.registerLazySingleton<PaymentAPIProvider>( () => PaymentAPIProviderImpl()); //Network Info injector .registerLazySingleton<NetworkInfo>(() => NetworkInfoImpl(injector())); //InternetConnectionChecker injector.registerLazySingleton(() => InternetConnectionChecker()); //SharedPreference //injector.registerLazySingleton<PreferenceHelper>(() => PreferenceHelper()); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:hive_flutter/adapters.dart'; import 'package:shopack_user/core/theme/bloc/theme_bloc.dart'; import 'package:shopack_user/core/utilities/endpoints.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cart_bloc.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cubit/address_cubit.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import 'package:shopack_user/features/payment/presentation/bloc/order_bloc.dart'; import 'core/local/shared_preference.dart'; import 'core/theme/theme_service.dart'; import 'dependancy_injection.dart'; import 'features/cart/data/datasource/local_datasource.dart'; import 'features/favorite/presentation/bloc/favourite_bloc.dart'; import 'features/home/presentation/bloc/BottomNavigationBar_bloc.dart'; import 'features/payment/presentation/bloc/payment_bloc.dart'; import 'features/profile/data/datasources/profile_local_datasource.dart'; import 'features/profile/presentation/bloc/update_password_bloc.dart'; import 'features/setpassword/presentation/bloc/reset_password_bloc.dart'; import 'features/shop/presentation/bloc/products_bloc.dart'; import 'features/shop/presentation/bloc/send_review_bloc.dart'; import 'core/utilities/router.dart'; import 'core/utilities/routes.dart'; import 'features/login/presentation/bloc/login_bloc.dart'; import 'features/profile/presentation/bloc/profile_bloc.dart'; import 'features/register/presentation/bloc/register_bloc.dart'; import 'features/forgotpass&verifyemail/presentation/forgotpass&verifyemail_bloc/forgotpass&verifyemail_bloc.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await init(); await PreferenceHelper.init(); await Hive.initFlutter(); await CacheManager().init(); await CartLocalDataSourceManager().init(); await ThemeDatabaseService.checkDatabaseExists(); await dotenv.load(fileName: ".env"); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (context) => injector<LoginBloc>(), ), BlocProvider( create: (context) => injector<RegisterBloc>(), ), BlocProvider( create: (context) => injector<ForgetpasswordAndeVerifyEmailBloc>(), ), BlocProvider( create: (context) => injector<ResetPasswordBloc>(), ), BlocProvider( create: (context) => injector<BottomNavigationBarBloc>(), ), BlocProvider( create: (context) => injector<ProductsBloc>(), ), BlocProvider( create: (context) => injector<ProfileBloc>(), ), BlocProvider( create: (context) => injector<UpdatePasswordBloc>(), ), BlocProvider( create: (context) => injector<SendReviewBloc>(), ), BlocProvider( create: (context) => injector<FavouriteBloc>(), ), BlocProvider( create: (context) => injector<CartBloc>()..add(CartStarted()), ), BlocProvider( create: (context) => injector<LocationBloc>(), ), BlocProvider( create: (context) => injector<AddressCubit>(), ), BlocProvider( create: (context) => injector<PaymentBloc>(), ), BlocProvider( create: (context) => injector<OrderBloc>(), ), BlocProvider( create: (context) => injector<ThemeBloc>(), ), ], child: BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { isSkipedOnBoarding = PreferenceHelper.getDataFromSharedPreference( key: 'IsSkippedOnBoarding'); return MaterialApp( debugShowCheckedModeBanner: false, theme: state.themeData, onGenerateRoute: onGenerate, initialRoute: isSkipedOnBoarding != null ? AppRoutes.splash : AppRoutes.onBoarding, ); }, ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data/models/suggession_model.dart
class PlacesModel { final String status; final List<Suggestion> suggestions; PlacesModel(this.status, this.suggestions); factory PlacesModel.fromJson(Map<String, dynamic> json) { return PlacesModel( json['status'], List<Suggestion>.from( json['predictions'].map((x) => Suggestion.fromJson(x))), ); } } class Suggestion { final String placeId; final String description; Suggestion( this.placeId, this.description, ); factory Suggestion.fromJson(Map<String, dynamic> json) { return Suggestion(json["place_id"], json["description"]); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data/models/placedetail_model.dart
class PlaceDetail { final Result result; PlaceDetail(this.result); factory PlaceDetail.fromJson(Map<String, dynamic> json) => PlaceDetail( Result.fromJson(json['result']) , ); } class Result { final Geometry geometry; Result(this.geometry); factory Result.fromJson(Map<String, dynamic> json) => Result( Geometry.fromJson(json['geometry']) , ); } class Geometry { final Location location; Geometry(this.location); factory Geometry.fromJson(Map<String, dynamic> json) => Geometry( Location.fromJson(json['location']), ); } class Location { final double lat; final double lng; Location(this.lat, this.lng); factory Location.fromJson(Map<String, dynamic> json) => Location(json['lat'], json['lng']); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data/models/cart_model.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'cart_model.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class CartProductAdapter extends TypeAdapter<CartProduct> { @override final int typeId = 4; @override CartProduct read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return CartProduct( id: fields[0] as String, name: fields[1] as String, description: fields[2] as String, price: fields[3] as int, ratings: fields[4] as num, productImage: fields[5] as String, category: fields[6] as String, stock: fields[7] as int, numOfReviews: fields[8] as int, user: fields[9] as String, isFavourite: fields[10] as bool, amount: fields[11] as num, ); } @override void write(BinaryWriter writer, CartProduct obj) { writer ..writeByte(12) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.description) ..writeByte(3) ..write(obj.price) ..writeByte(4) ..write(obj.ratings) ..writeByte(5) ..write(obj.productImage) ..writeByte(6) ..write(obj.category) ..writeByte(7) ..write(obj.stock) ..writeByte(8) ..write(obj.numOfReviews) ..writeByte(9) ..write(obj.user) ..writeByte(10) ..write(obj.isFavourite) ..writeByte(11) ..write(obj.amount); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is CartProductAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data/models/cart_model.dart
import 'package:hive/hive.dart'; part 'cart_model.g.dart'; @HiveType(typeId: 4) class CartProduct{ @HiveField(0) final String id; @HiveField(1) final String name; @HiveField(2) final String description; @HiveField(3) final int price; @HiveField(4) final num ratings; @HiveField(5) final String productImage; @HiveField(6) final String category; @HiveField(7) final int stock; @HiveField(8) final int numOfReviews; @HiveField(9) final String user; @HiveField(10) bool isFavourite =false; @HiveField(11) num amount =1; CartProduct({ required this.id, required this.name, required this.description, required this.price, required this.ratings, required this.productImage, required this.category, required this.stock, required this.numOfReviews, required this.user, this.isFavourite= false, this.amount=0, }); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data/datasource/local_datasource.dart
import 'package:hive/hive.dart'; import '../../../../core/local/cache_manager.dart'; import '../models/cart_model.dart'; class CartLocalDataSourceManager implements CacheManagerBase<CartProduct> { @override Future<void> init() async { registerAdapter(); await Hive.openBox<CartProduct>("product-cahce"); } @override Future<void> addItem(CartProduct item) async { await Hive.box("product-cahce").add(item); } @override CartProduct? getItem(String key) { return Hive.box("product-cahce").get( key, ); } @override Future<void> putItem(CartProduct item) async { await Hive.box("product-cahce").put("product-cahce", item); } @override Future<void> clearAll() async { await Hive.box("product-cahce").clear(); } @override void registerAdapter() { if (!Hive.isAdapterRegistered(4)) { Hive.registerAdapter(CartProductAdapter()); } } @override Future<void> clearAt(int id) async { await Hive.box("product-cahce").deleteAt(id); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/data/datasource/placesAPI.dart
import 'package:dio/dio.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:shopack_user/core/utilities/endpoints.dart'; import 'package:shopack_user/features/cart/data/models/placedetail_model.dart'; import '../models/suggession_model.dart'; abstract class PlacesDataSource { Future<List<Suggestion>> fetchSuggestions( String query, BuildContext context, ); Future<PlaceDetail> getPlaceDetailFromId( String placeId, BuildContext context, ); } class PlacesDatasourceImpl implements PlacesDataSource { static String sessionToken = ''; static String apiKey = dotenv.env['MAP_API_KEY']!; final dio = Dio(); @override Future<List<Suggestion>> fetchSuggestions( String query, BuildContext context) async { final response = await dio.get( '$placesAutocompeleteUrlPath?input=$query&sessiontoken=$sessionToken&types=establishment&language=ar|en&key=$apiKey'); return PlacesModel.fromJson(response.data).suggestions; } @override Future<PlaceDetail> getPlaceDetailFromId( String placeId, BuildContext context) async { final response = await dio.get( '$placesUrlPath?place_id=$placeId&fields=geometry&key=$apiKey&sessiontoken=$sessionToken'); return PlaceDetail.fromJson(response.data); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/views/checkout.dart
import 'package:fl_country_code_picker/fl_country_code_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:shopack_user/core/colors/colors.dart'; import 'package:shopack_user/core/utilities/mediaquery.dart'; import 'package:shopack_user/core/utilities/strings.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cart_bloc.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import 'package:shopack_user/features/cart/presentation/widgets/deliverymethod_card.dart'; import 'package:shopack_user/features/cart/presentation/widgets/mappreview.dart'; import 'package:shopack_user/features/login/presentation/widgets/alert_snackbar.dart'; import 'package:shopack_user/features/login/presentation/widgets/maintextformfield.dart'; import 'package:shopack_user/features/payment/presentation/bloc/order_bloc.dart'; import 'package:shopack_user/features/profile/presentation/bloc/profile_bloc.dart'; import 'package:uuid/uuid.dart'; import '../../../../core/utilities/routes.dart'; import '../../../payment/presentation/bloc/payment_bloc.dart'; class AddNewAddressView extends StatefulWidget { const AddNewAddressView({super.key}); @override State<AddNewAddressView> createState() => _AddNewAddressViewState(); } class _AddNewAddressViewState extends State<AddNewAddressView> { final TextEditingController firstNameController = TextEditingController(); final TextEditingController lastNameController = TextEditingController(); final TextEditingController addressController = TextEditingController(); final TextEditingController emailController = TextEditingController(); final TextEditingController phoneController = TextEditingController(); final formKey = GlobalKey<FormState>(); var countryPicker = const FlCountryCodePicker(); CountryCode? countryFlag = const CountryCode(name: 'Egypt', code: 'EG', dialCode: '+20'); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, automaticallyImplyLeading: false, leading: IconButton( icon: const Icon(Icons.arrow_back_ios_new), onPressed: () { Navigator.pop(context); }, ), title: Text( AppStrings.checkout, style: Theme.of(context).textTheme.headline6, ), ), floatingActionButton: SizedBox( width: kWidth(context) / 1.12, height: kHeight(context) / 14, child: BlocListener<OrderBloc, OrderState>( listener: (context, state) { if (state is CreateOrderLoaded) { showSnackbar(state.data.message, context, ColorManager.green); } }, child: BlocConsumer<PaymentBloc, PaymentState>( listener: (context, state) { if (state is PaymentRequestFinished) { Navigator.pushNamed(context, AppRoutes.payment); } }, builder: (context, state) { return state is Paymentloading || state is CreateOrderLoading ? const Center(child: CircularProgressIndicator()) : FloatingActionButton.extended( backgroundColor: ColorManager.orangeLight, elevation: 8, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(50)), onPressed: () { if (formKey.currentState!.validate()) { BlocProvider.of<PaymentBloc>(context).add( RequestPayment( BlocProvider.of<PaymentBloc>(context) .PAYMOB_FIRST_TOKEN, (BlocProvider.of<CartBloc>(context) .totalAmount * 100 + BlocProvider.of<LocationBloc>(context) .delivery * 100) .toString(), BlocProvider.of<PaymentBloc>(context).ORDER_ID, firstNameController.text, lastNameController.text, phoneController.text, emailController.text, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .street!, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .locality!, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .country!, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .subAdministrativeArea!, dotenv.env['INTEGRATION_ID_CARD']!), ); BlocProvider.of<OrderBloc>(context).add( CreateNewOrder( BlocProvider.of<CartBloc>(context) .totalAmount .toInt(), BlocProvider.of<LocationBloc>(context).delivery, BlocProvider.of<CartBloc>(context) .totalAmount .toInt() + BlocProvider.of<LocationBloc>(context) .delivery, phoneController.text, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .postalCode!, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .street!, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .locality!, BlocProvider.of<LocationBloc>(context) .currentAddress![0] .country!, "succeeded", const Uuid().v4(), BlocProvider.of<LocationBloc>(context) .currentAddress![0] .administrativeArea!, BlocProvider.of<CartBloc>(context).orderItems ), ); } }, label: Text( AppStrings.submitOrder.toUpperCase(), )); }, ), ), ), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: SingleChildScrollView( child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( AppStrings.currentLocation, style: Theme.of(context).textTheme.titleMedium, ), ElevatedButton.icon( onPressed: () { Navigator.pushNamed(context, AppRoutes.mapview); }, icon: const Icon(Icons.add), label: const Text(AppStrings.addNew), ), ], ), BlocBuilder<LocationBloc, LocationState>( builder: (context, state) { final bloc = BlocProvider.of<LocationBloc>(context); if (state is MapLoadingState) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: kHeight(context) / 8, ), const Center(child: CircularProgressIndicator()), ], ); } else if (state is MapLoadedState || state is MapSelectedPosition || state is SelectMethodState) { addressController.text = BlocProvider.of<LocationBloc>(context) .currentAddressDetails!; firstNameController.text = BlocProvider.of<ProfileBloc>(context) .userName .split(' ') .first; lastNameController.text = BlocProvider.of<ProfileBloc>(context) .userName .split(' ') .last; emailController.text = BlocProvider.of<ProfileBloc>(context).userEmail; return Form( key: formKey, child: Column( children: [ MapPreview(bloc: bloc), Padding( padding: const EdgeInsets.symmetric(vertical: 15), child: Row( children: [ Text( AppStrings.deliveryAddress, style: Theme.of(context).textTheme.headline6, ), ], ), ), MainTFF( max: 1, labelText: AppStrings.addressLine, controller: addressController, validate: (value) { if (value!.isEmpty) { return AppStrings.emptyaddress; } return null; }, isPassword: false, borderRadius: 15, inputType: TextInputType.text), const SizedBox( height: 20, ), MainTFF( max: 1, labelText: AppStrings.firstname, controller: firstNameController, validate: (value) { if (value!.isEmpty) { return AppStrings.nameEmpty; } return null; }, isPassword: false, borderRadius: 15, inputType: TextInputType.text), const SizedBox( height: 20, ), MainTFF( max: 1, labelText: AppStrings.lastname, controller: lastNameController, validate: (value) { if (value!.isEmpty) { return AppStrings.nameEmpty; } return null; }, isPassword: false, borderRadius: 15, inputType: TextInputType.text), const SizedBox( height: 20, ), MainTFF( max: 1, labelText: AppStrings.email, controller: emailController, validate: (value) { if (value!.isEmpty) { return AppStrings.emptyEmail; } return null; }, isPassword: false, borderRadius: 15, inputType: TextInputType.emailAddress), const SizedBox( height: 20, ), MainTFF( validate: (value) { if (value!.isEmpty) { return AppStrings.phoneRequired; } else if (value.length < 10) { return AppStrings.phonemust; } return null; }, controller: phoneController, inputType: TextInputType.number, labelText: AppStrings.phone, max: 1, isPassword: false, hintText: AppStrings.enterphone, prefix: Container( padding: const EdgeInsets.symmetric( horizontal: 5, vertical: 3), margin: const EdgeInsets.symmetric(horizontal: 3), child: Row(mainAxisSize: MainAxisSize.min, children: [ InkWell( onTap: () async { var temp = countryFlag; var flag = await countryPicker.showPicker( context: context); flag ??= temp; setState(() { countryFlag = flag; }); }, child: Row( children: [ Container( child: countryFlag != null ? countryFlag!.flagImage : const SizedBox(), ), const SizedBox( width: 30, child: Icon( Icons.arrow_drop_down, ), ), ], ), ), ]), ), borderRadius: 15, ), const SizedBox( height: 20, ), Row( children: [ Text( AppStrings.deliveryMethod, style: Theme.of(context).textTheme.headline6, ), ], ), const SizedBox( height: 20, ), SizedBox( height: kHeight(context) / 6.5, child: ListView.builder( clipBehavior: Clip.antiAlias, scrollDirection: Axis.horizontal, itemCount: 3, itemBuilder: (context, index) => DeliveryMethodCard( index: index, ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( AppStrings.order, style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: ColorManager.grey), ), Text( '${BlocProvider.of<CartBloc>(context).totalAmount} \$', style: Theme.of(context).textTheme.headline6), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( AppStrings.delivery, style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: ColorManager.grey), ), Text( '${BlocProvider.of<LocationBloc>(context).delivery} \$', style: Theme.of(context).textTheme.headline6), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( AppStrings.summery, style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: ColorManager.grey), ), Text( '${BlocProvider.of<CartBloc>(context).totalAmount + BlocProvider.of<LocationBloc>(context).delivery} \$', style: Theme.of(context).textTheme.headline6), ], ), ), SizedBox( height: kHeight(context) / 12, ) ], ), ); } else if (state is MapErrorState) { return Center(child: Text(state.message)); } else { return const SizedBox(); } }, ), ]), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/views/cart.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:lottie/lottie.dart'; import 'package:shopack_user/core/utilities/routes.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cart_bloc.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import 'package:shopack_user/features/cart/presentation/widgets/cart_item.dart'; import 'package:shopack_user/features/login/presentation/widgets/alert_snackbar.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../../payment/presentation/bloc/payment_bloc.dart'; class CartView extends StatefulWidget { const CartView({super.key}); @override State<CartView> createState() => _CartViewState(); } class _CartViewState extends State<CartView> { @override void initState() { BlocProvider.of<LocationBloc>(context).add(GetCurrentLocation()); BlocProvider.of<PaymentBloc>(context) .add(RequestAuth(dotenv.env['PAYMENT_API_KEY']!)); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, centerTitle: true, title: Text( AppStrings.mybag, style: Theme.of(context).textTheme.headline6, )), floatingActionButton: BlocProvider.of<CartBloc>(context).cartItems.isEmpty ? const SizedBox() : SizedBox( width: kWidth(context) / 1.12, height: kHeight(context) / 14, child: FloatingActionButton.extended( backgroundColor: ColorManager.orangeLight, elevation: 8, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(50)), onPressed: () { if (BlocProvider.of<CartBloc>(context) .cartItems .isNotEmpty) { Navigator.pushNamed(context, AppRoutes.checkout); BlocProvider.of<PaymentBloc>(context).add( RequestOrder( BlocProvider.of<PaymentBloc>(context).PAYMOB_FIRST_TOKEN, (BlocProvider.of<CartBloc>(context).totalAmount + BlocProvider.of<LocationBloc>(context).delivery) .toString(), ), ); } else { showSnackbar(AppStrings.emptybag, context, Colors.red); } }, label: BlocConsumer<CartBloc, CartState>( listener: (context, state) { if (state is AddToCartState) { showSnackbar( AppStrings.addedToCart, context, Colors.green); } }, builder: (context, state) { return Text( AppStrings.addToCart.toUpperCase(), ); }, ),), ), body: Column( children: [ Expanded( child: BlocBuilder<CartBloc, CartState>( builder: (context, state) { if (state is CartLoading) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: kHeight(context) / 10, width: kWidth(context) / 10, child: const CircularProgressIndicator()), ], ), ], ); } if (state is CartLoaded) { if (state.items.isEmpty) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Center(child: LottieBuilder.asset('assets/images/empty.json')), ), Padding( padding: const EdgeInsets.all(8.0), child: Text(AppStrings.notCart,style: Theme.of(context).textTheme.titleMedium,), ), ], ); } return Column( children: [ Expanded( child: ListView.builder( padding: const EdgeInsets.symmetric(vertical: 22), itemCount: state.items.length, itemBuilder: (context, index) { return CatItem( item: state.items[index], index: index, ); }, ), ), SafeArea( top: false, child: Container( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 22), width: double.infinity, child: BlocBuilder<CartBloc, CartState>( builder: (context, state) { if (state is CartLoaded) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "${state.items.length} items", style: const TextStyle( fontSize: 14, fontWeight: FontWeight.w500, color: ColorManager.orangeLight, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "${AppStrings.totalAmount}: ", style: Theme.of(context) .textTheme .headline6! .copyWith( color: ColorManager.grey), ), FittedBox( child: Text( '${BlocProvider.of<CartBloc>(context).totalAmount} \$', style: Theme.of(context) .textTheme .headline6, ), ) ], ) ], ); } return const SizedBox(); }, ), ), ), SizedBox( height: kHeight(context) / 12, ) ], ); } return const SizedBox(); }, ), ), ], ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/views/map_screen.dart
// ignore_for_file: use_build_context_synchronously import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:geolocator/geolocator.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:shopack_user/core/utilities/strings.dart'; import 'package:shopack_user/features/cart/data/datasource/placesAPI.dart'; import 'package:shopack_user/features/cart/presentation/bloc/cubit/address_cubit.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import 'package:flutter_typeahead/flutter_typeahead.dart'; import 'package:uuid/uuid.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../login/presentation/widgets/alert_snackbar.dart'; import '../../data/models/suggession_model.dart'; class MapView extends StatelessWidget { const MapView({super.key}); @override Widget build(BuildContext context) { TextEditingController controller = TextEditingController(); return Scaffold( appBar: AppBar( centerTitle: true, automaticallyImplyLeading: false, leading: IconButton( icon: const Icon(Icons.arrow_back_ios_new), onPressed: () { Navigator.pop(context); }, ), title: Text( AppStrings.selectnewaddress, style: Theme.of(context).textTheme.headline6, ), ), body: BlocConsumer<LocationBloc, LocationState>( listener: (context, state) { final bloc = BlocProvider.of<LocationBloc>(context); if (state is MapSelectedPosition) { showSnackbar( "The selected area is : ${bloc.currentAddressDetails}", context, ColorManager.white); } }, builder: (context, state) { final bloc = BlocProvider.of<LocationBloc>(context); if (state is MapLoadingState) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: kHeight(context) / 8, ), const Center(child: CircularProgressIndicator()), ], ); } else if (state is MapLoadedState || state is MapSelectedPosition || state is SelectMethodState) { return Stack( children: [ SizedBox( width: kWidth(context), height: kHeight(context), child: GoogleMap( initialCameraPosition: bloc.initialTarget!, onMapCreated: (controller) { bloc.googleMapController = controller; }, markers: { Marker( markerId: const MarkerId('1'), icon: BitmapDescriptor.defaultMarkerWithHue( BitmapDescriptor.hueRed), position: bloc.myCurrentPosition != null ? LatLng(bloc.myCurrentPosition!.latitude, bloc.myCurrentPosition!.longitude) : const LatLng(0.0, 0.0), ), }, onTap: (tapped) async { bloc.add(SelectPosition(latLng: tapped)); }, ), ), Positioned( left: 20, right: 20, top: 20, child: TextField( controller: bloc.searchController, readOnly: true, onTap: () { PlacesDatasourceImpl.sessionToken = const Uuid().v4(); showDialog( builder: (context) { return Padding( padding: EdgeInsets.symmetric( vertical: kHeight(context) / 10, horizontal: 20), child: Column(children: [ Material( color: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), child: TypeAheadField( textFieldConfiguration: TextFieldConfiguration( controller: controller, textInputAction: TextInputAction.search, autofocus: true, textCapitalization: TextCapitalization.words, keyboardType: TextInputType.streetAddress, decoration: InputDecoration( hintText: AppStrings.searchlocation, border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide( style: BorderStyle.none, width: 0), ), hintStyle: Theme.of(context) .textTheme .headline2! .copyWith( fontSize: 15, color: Theme.of(context).disabledColor, ), ), style: Theme.of(context) .textTheme .headline2! .copyWith( color: Theme.of(context) .textTheme .bodyText1! .color, fontSize: 18, ), ), errorBuilder: (context, error) => const SizedBox(), suggestionsCallback: (pattern) async { return BlocProvider.of<AddressCubit>( context) .searchLocation( controller.text, context); }, itemBuilder: (context, Suggestion suggestion) { return Padding( padding: const EdgeInsets.all(8.0), child: Row(children: [ const Icon(Icons.location_on), Expanded( child: Text(suggestion.description, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .headline2! .copyWith( color: Theme.of(context) .textTheme .bodyText1! .color, fontSize: 16, )), ), ]), ); }, onSuggestionSelected: (Suggestion suggestion) async { await BlocProvider.of<AddressCubit>(context) .getLocation( suggestion.placeId, context); LatLng? latLng = BlocProvider.of<AddressCubit>(context) .location; if (latLng != null) { bloc.myCurrentPosition = Position( longitude: latLng.longitude, latitude: latLng.latitude, timestamp: null, accuracy: 0.0, altitude: 0.0, heading: 0.0, speed: 0.0, speedAccuracy: 0.0); bloc.googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: latLng, zoom: 15, ), ), ); } bloc.searchController.text = suggestion.description; Navigator.pop(context); }, ), ) ]), ); }, context: context, ); }, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: Colors.transparent)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: Colors.transparent)), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: Colors.transparent)), hintText: AppStrings.searchlocation, hintStyle: const TextStyle( color: Color(0xFF535353), ), suffixIcon: const SizedBox(), ), ), ), ], ); } else if (state is MapErrorState) { return Center(child: Text(state.message)); } else { return const SizedBox( child: Text("data"), ); } }, ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/widgets/mappreview.dart
import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:shopack_user/core/colors/colors.dart'; import 'package:shopack_user/core/utilities/routes.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import '../../../../core/utilities/mediaquery.dart'; class MapPreview extends StatelessWidget { final LocationBloc bloc; const MapPreview({super.key, required this.bloc}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 10), child: SizedBox( height: kHeight(context) / 4, width: MediaQuery.of(context).size.width, child: ClipRRect( borderRadius: BorderRadius.circular(15), child: Stack( clipBehavior: Clip.none, children: [ GoogleMap( minMaxZoomPreference: const MinMaxZoomPreference(0, 16), mapType: MapType.normal, initialCameraPosition: bloc.initialTarget!, zoomControlsEnabled: false, compassEnabled: false, indoorViewEnabled: true, mapToolbarEnabled: false, ), Container( width: kWidth(context), alignment: Alignment.center, height: kHeight(context), child: const Icon( Icons.location_on, color: ColorManager.orangeLight, size: 35, )), Positioned( bottom: 10, right: 0, child: InkWell( onTap: () { bloc.add(GetCurrentLocation()); }, child: Container( width: 30, height: 30, margin: const EdgeInsets.only(right: 20), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: ColorManager.white, ), child: const Icon( Icons.my_location, color: ColorManager.orangeLight, size: 20, ), ), ), ), Positioned( top: 10, right: 0, child: InkWell( onTap: () { Navigator.pushNamed(context, AppRoutes.mapview); }, child: Container( width: 30, height: 30, margin: const EdgeInsets.only(right: 20), decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: ColorManager.white, ), child: const Icon( Icons.fullscreen, color: ColorManager.orangeLight, size: 20, ), ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/widgets/permissiondialog.dart
// ignore_for_file: use_build_context_synchronously import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; class PermissionDialog extends StatelessWidget { const PermissionDialog({super.key}); @override Widget build(BuildContext context) { return Dialog( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), child: Padding( padding: const EdgeInsets.all(10), child: SizedBox( width: 300, child: Column(mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.add_location_alt_rounded, color: Theme.of(context).primaryColor, size: 100), const SizedBox(height:15), const Text( 'you_denied_location_permission', textAlign: TextAlign.center, ), const SizedBox(height: 15), Row(children: [ Expanded( child: TextButton( style: TextButton.styleFrom( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10), side: BorderSide(width: 2, color: Theme.of(context).primaryColor)), minimumSize: const Size(1, 50), ), child: const Text('no'), onPressed: () => Navigator.pop(context), ), ), const SizedBox(width: 7), Expanded(child: TextButton(onPressed: () async { await Geolocator.openAppSettings(); Navigator.pop(context); }, child: const Text('yes')), ) ]), ]), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/widgets/deliverymethod_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:shopack_user/features/cart/presentation/bloc/location_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; class DeliveryMethodCard extends StatefulWidget { final int index; const DeliveryMethodCard({ super.key, required this.index, }); @override State<DeliveryMethodCard> createState() => _DeliveryMethodCardState(); } class _DeliveryMethodCardState extends State<DeliveryMethodCard> { int currentIndex = 0; List<Map<String, dynamic>> deliveryMethods = [ { 'image': 'assets/images/fedex.png', 'title': '2-3 Days', }, { 'image': 'assets/images/dhl.png', 'title': '1-3 Days', }, { 'image': 'assets/images/aramex.png', 'title': '2-5 Days', }, ]; @override Widget build(BuildContext context) { return Stack(children: [ InkWell( onTap: () { BlocProvider.of<LocationBloc>(context).add(SelectMethod(widget.index)); }, child: Container( margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), decoration: BoxDecoration( color: ColorManager.white, borderRadius: BorderRadius.circular(10), boxShadow: kElevationToShadow[4]), child: Column( children: [ SizedBox( width: kWidth(context) / 2.5, height: kHeight(context) / 10, child: Image.asset( deliveryMethods[widget.index]['image']!, fit: BoxFit.fitWidth, ), ), FittedBox(child: Text(deliveryMethods[widget.index]['title']!)) ], ), ), ), Positioned( right: 15, top: 10, child: BlocProvider.of<LocationBloc>(context).currentIndex==widget.index ? SizedBox( width: 40, height: 30, child: Image.asset('assets/images/valid.png'), ) : const SizedBox()), ]); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/widgets/cart_item.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:shopack_user/features/cart/data/models/cart_model.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../../login/presentation/widgets/alert_snackbar.dart'; import '../bloc/cart_bloc.dart'; class CatItem extends StatelessWidget { final CartProduct item; final int index; const CatItem({super.key, required this.item, required this.index}); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5), child: Container( clipBehavior: Clip.antiAlias, width: kWidth(context), height: kHeight(context) / 6, decoration: BoxDecoration( color: ColorManager.white, borderRadius: BorderRadius.circular(10), boxShadow: kElevationToShadow[3]), child: Row( children: [ SizedBox( width: kWidth(context) * 0.25, child: Image.network( item.productImage, ), ), Expanded( child: Column( children: [ Row( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: kWidth(context) * 0.5, child: Text( item.name, style: Theme.of(context).textTheme.bodyLarge!.copyWith(color: ColorManager.dark,), overflow: TextOverflow.ellipsis, maxLines: 1, ), ), Text( item.category, style: Theme.of(context).textTheme.bodySmall!.copyWith(color: ColorManager.dark,) ) ], ), BlocListener<CartBloc, CartState>( listener: (context, state) { if (state is RemoveFromCart) { showSnackbar(AppStrings.removeFromCart, context, Colors.green); } }, child: IconButton( onPressed: () async { BlocProvider.of<CartBloc>(context) .add(RemoveFromCart(index)); }, icon: const Icon( Icons.clear, color: ColorManager.grey, ), ), ), ], ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ SizedBox( width: kWidth(context) * .4, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( decoration: BoxDecoration( shape: BoxShape.circle, boxShadow: kElevationToShadow[4]), child: CircleAvatar( backgroundColor: ColorManager.white, radius: 20.0, child: Material( color: Colors.transparent, child: InkWell( onTap: () { BlocProvider.of<CartBloc>(context).add(DecrementCount(item)); }, child: const Icon( Icons.remove, size: 20.0, color: ColorManager.grey, ), ), ), )), Text( '${item.amount}', style: Theme.of(context).textTheme.headline6!.copyWith(color: ColorManager.dark,), ), Container( decoration: BoxDecoration( shape: BoxShape.circle, boxShadow: kElevationToShadow[4]), child: CircleAvatar( backgroundColor: ColorManager.white, radius: 20.0, child: Material( color: Colors.transparent, child: InkWell( onTap: () { BlocProvider.of<CartBloc>(context).add(IncrementCount(item)); }, child: const Icon( Icons.add, size: 20.0, color: ColorManager.grey, ), ), ), )), ], ), ), Text( '${item.price} \$', style: Theme.of(context).textTheme.headline6, ) ], ), ) ], )) ], ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/location_state.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first part of 'location_bloc.dart'; abstract class LocationState extends Equatable { const LocationState(); @override List<Object> get props => []; } class LocationInitial extends LocationState {} class MapLoadingState extends LocationState {} class MapLoadedState extends LocationState {} class MapSelectedPosition extends LocationState { final List<Placemark> currentAddress; const MapSelectedPosition(this.currentAddress); } class MapErrorState extends LocationState { final String message; const MapErrorState(this.message); } class SelectMethodState extends LocationState{ }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/location_event.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first part of 'location_bloc.dart'; abstract class LocationEvent extends Equatable { const LocationEvent(); @override List<Object> get props => []; } class CheckPermission extends LocationEvent { final BuildContext context; const CheckPermission(this.context); } class GetCurrentLocation extends LocationEvent {} class SelectPosition extends LocationEvent { final LatLng latLng; const SelectPosition({ required this.latLng, }); } class SearchLocation extends LocationEvent { final String query; const SearchLocation({ required this.query, }); } class SelectMethod extends LocationEvent { final int index; const SelectMethod( this.index); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/cart_event.dart
part of 'cart_bloc.dart'; abstract class CartEvent extends Equatable { const CartEvent(); @override List<Object> get props => []; } class CartStarted extends CartEvent{ } class AddToCart extends CartEvent { final ProductEntity product; const AddToCart(this.product); } class RemoveFromCart extends CartEvent { final int id; const RemoveFromCart(this.id); } class IncrementCount extends CartEvent { final CartProduct cartProduct; const IncrementCount(this.cartProduct); } class DecrementCount extends CartEvent { final CartProduct cartProduct; const DecrementCount(this.cartProduct); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/location_bloc.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:geocoding/geocoding.dart'; import 'package:geolocator/geolocator.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:shopack_user/core/error/error_handler.dart'; import 'package:shopack_user/core/network/network_info.dart'; import 'package:shopack_user/core/utilities/strings.dart'; import 'package:shopack_user/features/cart/data/datasource/placesAPI.dart'; import '../widgets/permissiondialog.dart'; part 'location_event.dart'; part 'location_state.dart'; class LocationBloc extends Bloc<LocationEvent, LocationState> { List<Map<String, dynamic>> deliveryMethods = [ { 'image': 'assets/images/fedex.png', 'title': '2-3 Days', 'isSelected': true, }, { 'image': 'assets/images/dhl.png', 'title': '1-3 Days', 'isSelected': false, }, { 'image': 'assets/images/aramex.png', 'title': '2-5 Days', 'isSelected': false, }, ]; final PlacesDataSource placesDataSource; String? currentAddressDetails; Position? myCurrentPosition; CameraPosition? initialTarget; int delivery = 0; int currentIndex = -1; List<Placemark>? currentAddress; late GoogleMapController googleMapController; TextEditingController searchController = TextEditingController(); final NetworkInfo networkInfo; LocationBloc( this.placesDataSource, this.networkInfo, ) : super(LocationInitial()) { on<CheckPermission>((event, emit) async { LocationPermission permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); } else if (permission == LocationPermission.deniedForever) { showDialog( context: event.context, barrierDismissible: false, builder: (context) => const PermissionDialog()); } }); on<GetCurrentLocation>((event, emit) async { if (await networkInfo.isConnected) { try { emit(MapLoadingState()); myCurrentPosition = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); initialTarget = CameraPosition( target: LatLng( myCurrentPosition!.latitude, myCurrentPosition!.longitude), zoom: 16); emit(MapLoadedState()); currentAddress = await GeocodingPlatform.instance .placemarkFromCoordinates( myCurrentPosition!.latitude, myCurrentPosition!.longitude); currentAddressDetails = "${currentAddress![0].street} ${currentAddress![0].name!} ${currentAddress![0].administrativeArea!} - ${currentAddress![0].country!}"; emit(MapSelectedPosition(currentAddress!)); } catch (error) { emit(MapErrorState(ErrorHandler.handle(error).failure.message)); } } else { ErrorHandler.handle(AppStrings.noInternetError); } }); on<SelectPosition>((event, emit) async { if (await networkInfo.isConnected) { try { emit(MapLoadingState()); searchController.text = ''; myCurrentPosition = Position( longitude: event.latLng.longitude, latitude: event.latLng.latitude, timestamp: null, accuracy: 0.0, altitude: 0.0, heading: 0.0, speed: 0.0, speedAccuracy: 0.0); googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng( myCurrentPosition!.latitude, myCurrentPosition!.longitude), zoom: 15, ), ), ); emit(MapLoadedState()); currentAddress = await GeocodingPlatform.instance .placemarkFromCoordinates( myCurrentPosition!.latitude, myCurrentPosition!.longitude); currentAddressDetails = "${currentAddress![0].street} ${currentAddress![0].name!} ${currentAddress![0].administrativeArea!} - ${currentAddress![0].country!}"; emit(MapSelectedPosition(currentAddress!)); } catch (error) { emit(MapErrorState(ErrorHandler.handle(error).failure.message)); } } else { ErrorHandler.handle(AppStrings.noInternetError); } }); on<SelectMethod>((event, emit) { emit(MapLoadingState()); currentIndex = event.index; switch (event.index) { case 0: delivery = 15; break; case 1: delivery = 20; break; case 2: delivery = 10; break; default: } emit(SelectMethodState()); }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/cart_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:shopack_user/features/shop/domain/entities/products_entity.dart'; import '../../data/models/cart_model.dart'; part 'cart_event.dart'; part 'cart_state.dart'; class CartBloc extends Bloc<CartEvent, CartState> { List<CartProduct> cartItems = []; List<Map<String, dynamic>> orderItems = []; num totalAmount = 0; final Box<CartProduct> itemBox = Hive.box<CartProduct>("product-cahce"); CartBloc() : super(CartInitial()) { on<CartStarted>((event, emit) { if (state is CartInitial) { emit(CartLoading()); emit(CartLoaded(cartItems)); } }); on<AddToCart>((event, emit) { emit(CartLoading()); CartProduct cartProduct = CartProduct( id: event.product.id, name: event.product.name, description: event.product.description, price: event.product.price, ratings: event.product.ratings, category: event.product.category, stock: event.product.stock, numOfReviews: event.product.numOfReviews, user: event.product.user, productImage: event.product.images.first.url, amount: event.product.qouantity); itemBox.add(cartProduct); Map<String, dynamic> orderitem = { "name": event.product.name, "image": event.product.images.first.url, "price": event.product.price, "quantity": event.product.qouantity }; orderItems.add(orderitem); List<CartProduct> list = itemBox.values.toList(); cartItems = list; totalAmount = 0; for (var element in list) { totalAmount = totalAmount + element.amount * element.price; } emit(AddToCartState()); emit(CartLoaded(list)); }); on<RemoveFromCart>((event, emit) async { emit(CartLoading()); await itemBox.deleteAt(event.id); List<CartProduct> list = itemBox.values.toList(); cartItems = list; totalAmount = 0; for (var element in list) { totalAmount = totalAmount + element.amount * element.price; } emit(CartLoaded(list)); }); on<IncrementCount>((event, emit) async { event.cartProduct.amount++; totalAmount = 0; totalAmount = totalAmount + event.cartProduct.amount * event.cartProduct.price; List<CartProduct> list = itemBox.values.toList(); cartItems = list; emit(IncrementCountState()); emit(CartLoaded(list)); }); on<DecrementCount>((event, emit) async { if (event.cartProduct.amount > 0) { event.cartProduct.amount--; totalAmount = 0; totalAmount = totalAmount + event.cartProduct.amount * event.cartProduct.price; List<CartProduct> list = itemBox.values.toList(); cartItems = list; emit(IncrementCountState()); emit(CartLoaded(list)); } }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/cart_state.dart
part of 'cart_bloc.dart'; abstract class CartState extends Equatable { const CartState(); @override List<Object> get props => []; } class CartInitial extends CartState {} class AddToCartState extends CartState {} class CartLoading extends CartState {} class CartLoaded extends CartState { final List items; const CartLoaded(this.items); } class IncrementCountState extends CartState { } class DecrementCountState extends CartState { }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/cubit/address_cubit.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/cupertino.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:shopack_user/core/network/network_info.dart'; import 'package:shopack_user/features/cart/data/datasource/placesAPI.dart'; import 'package:shopack_user/features/cart/data/models/placedetail_model.dart'; import '../../../data/models/suggession_model.dart'; part 'address_state.dart'; class AddressCubit extends Cubit<AddressState> { final NetworkInfo networkInfo; LatLng? location; final PlacesDataSource placesDataSource; AddressCubit(this.networkInfo, this.placesDataSource) : super(AddressInitial()); Future<List<Suggestion>> searchLocation( String query, BuildContext context) async { emit(SearchListLoadingState()); final data = await placesDataSource.fetchSuggestions(query, context); emit(SearchListLoadedState(places: data)); return data; } Future<PlaceDetail> getLocation( String placeId, BuildContext context, ) async { emit(GetLocationLoadingState()); final data = await placesDataSource.getPlaceDetailFromId(placeId, context); location = LatLng( data.result.geometry.location.lat, data.result.geometry.location.lng); emit(GetLocationLoadedState(location: data)); return data; } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/cart/presentation/bloc/cubit/address_state.dart
part of 'address_cubit.dart'; abstract class AddressState extends Equatable { const AddressState(); @override List<Object> get props => []; } class AddressInitial extends AddressState {} class SearchListLoadingState extends AddressState {} class SearchListLoadedState extends AddressState { final List<Suggestion> places; const SearchListLoadedState({ required this.places, }); } class SearchListErrorState extends AddressState { final String message; const SearchListErrorState({ required this.message, }); } class GetLocationLoadingState extends AddressState {} class GetLocationLoadedState extends AddressState { final PlaceDetail location; const GetLocationLoadedState({ required this.location, }); } class GetLocationErrorState extends AddressState { final String message; const GetLocationErrorState({ required this.message, }); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data/models/products_model.dart
import '../../domain/entities/products_entity.dart'; class ProductsModel extends ProductsEntity { const ProductsModel(super.success, super.products, super.filteredProductsCount); factory ProductsModel.fromJson(Map<String, dynamic> json) => ProductsModel( json['success'], List<ProductModel>.from( json['products'].map((x) => ProductModel.fromJson(x))), json['filteredProductsCount']); } class ProductModel extends ProductEntity { ProductModel( {required super.id, required super.name, required super.description, required super.price, required super.ratings, required super.images, required super.category, required super.stock, required super.numOfReviews, required super.user, required super.reviews, super.isFavourite}); factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel( id: json['_id'], name: json['name'], description: json['description'], price: json['price'], ratings: json['ratings'], images: List<ImageModel>.from( json['images'].map((x) => ImageModel.fromJson(x))), category: json['category'], stock: json['stock'], numOfReviews: json['numOfReviews'], user: json['user'], reviews: List<ReviewModel>.from( json['reviews'].map((x) => ReviewModel.fromJson(x))) ); } class ImageModel extends ImageEntity { const ImageModel(super.publicid, super.url); factory ImageModel.fromJson(Map<String, dynamic> json) => ImageModel(json['public_id'], json['url']); } class ReviewModel extends ReviewEntity { const ReviewModel(super.user, super.name,super.rating, super.comment,super.createdAt); factory ReviewModel.fromJson(Map<String, dynamic> json) => ReviewModel( json["user"] ?? "", json['name'] ?? "", json['rating']??0, json['comment'] ?? "", DateTime.parse(json['createdAt']) ); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data/models/response_model.dart
import '../../domain/entities/response_entity.dart'; class ResponseModel extends ResponseEntity { const ResponseModel(super.success, super.message); factory ResponseModel.fromJson(Map<String, dynamic> json) => ResponseModel(json['success'], json['message']); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data/models/reviews_model.dart
import '../../domain/entities/reviews_entity.dart'; class GetReviewsModel extends GetReviewsEntity { const GetReviewsModel(super.success, super.reviews); factory GetReviewsModel.fromJson(Map<String, dynamic> json) => GetReviewsModel( json['success'], List<GetReviewModel>.from( json['reviews'].map((x) => GetReviewModel.fromJson(x))), ); } class GetReviewModel extends GetReviewEntity { const GetReviewModel(super.user, super.name,super.rating, super.comment,super.createdAt); factory GetReviewModel.fromJson(Map<String, dynamic> json) => GetReviewModel( json["user"] ?? "", json['name'] ?? "", json['rating']??0, json['comment'] ?? "", DateTime.parse(json['createdAt']) ); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data/datasources/products_datasource.dart
import 'package:shopack_user/features/shop/data/models/reviews_model.dart'; import '../../../../core/local/shared_preference.dart'; import '../../../../core/network/api_provider.dart'; import '../../../../core/utilities/endpoints.dart'; import '../../domain/repositories/product_repository.dart'; import '../models/products_model.dart'; import '../models/response_model.dart'; abstract class ProductsDatasource { Future<ProductsModel> getAllProducts(); Future<ProductsModel> getSpecificProduct(GetProductParams params); Future<ResponseModel> sendReview(SendReviewParams params); Future<GetReviewsModel> getReviews(GetReviewsParams params); } class ProductsDatasourceImpl implements ProductsDatasource { final APIProvider apiProvider; ProductsDatasourceImpl(this.apiProvider); @override Future<ProductsModel> getAllProducts() async { final response = await apiProvider.get(endPoint: productsEndPoint); return ProductsModel.fromJson(response.data); } @override Future<ProductsModel> getSpecificProduct(GetProductParams params) async { final response = await apiProvider.get(endPoint: productsEndPoint, query: { "category": params.category, "price[gt]": params.minPrice, "price[lt]": params.maxPrice, "ratings[gt]": params.rate, "keyword": params.keyword, }); return ProductsModel.fromJson(response.data); } @override Future<ResponseModel> sendReview(SendReviewParams params) async { final response = await apiProvider.put( endPoint: getAllReviewsEndPoint, data: { 'productId': params.productId, 'comment': params.comment, 'rating': params.rating, }, token: PreferenceHelper.getDataFromSharedPreference(key: 'token') ?? ''); return ResponseModel.fromJson(response.data); } @override Future<GetReviewsModel> getReviews(GetReviewsParams params) async { final response = await apiProvider.get( endPoint: "$reviewEndPoint?id=${params.productId}", ); return GetReviewsModel.fromJson(response.data); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/data/repositories/products_repositoryimpl.dart
import 'package:dartz/dartz.dart'; import 'package:shopack_user/features/shop/domain/entities/reviews_entity.dart'; import '../../../../core/error/error_handler.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/network/network_info.dart'; import '../../../../core/utilities/strings.dart'; import '../../domain/entities/products_entity.dart'; import '../../domain/entities/response_entity.dart'; import '../../domain/repositories/product_repository.dart'; import '../datasources/products_datasource.dart'; class ProductsRepositoryImpl implements ProductRepository { final NetworkInfo networkInfo; final ProductsDatasource productsDatasource; ProductsRepositoryImpl(this.networkInfo, this.productsDatasource); @override Future<Either<Failure, ProductsEntity>> getAllProducts() async { if (await networkInfo.isConnected) { try { final data = await productsDatasource.getAllProducts(); return right(data); } catch (error) { return left(ErrorHandler.handle(error).failure); } } else { return const Left(OfflineFailure(AppStrings.noInternetError)); } } @override Future<Either<Failure, ProductsEntity>> getSpecificProduct( GetProductParams params) async { if (await networkInfo.isConnected) { try { final data = await productsDatasource.getSpecificProduct(params); return right(data); } catch (error) { return left(ErrorHandler.handle(error).failure); } } else { return left(const OfflineFailure(AppStrings.noInternetError)); } } @override Future<Either<Failure, ResponseEntity>> sendReview( SendReviewParams params) async { if (await networkInfo.isConnected) { try { final data = await productsDatasource.sendReview(params); return right(data); } catch (error) { print(error); return left(ErrorHandler.handle(error).failure); } } else { return left(const OfflineFailure(AppStrings.noInternetError)); } } @override Future<Either<Failure, GetReviewsEntity>> getReviews( GetReviewsParams params) async { if (await networkInfo.isConnected) { try { final data = await productsDatasource.getReviews(params); return right(data); } catch (error) { print(error); return left(ErrorHandler.handle(error).failure); } } else { return left(const OfflineFailure(AppStrings.noInternetError)); } } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/views/shop.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:lottie/lottie.dart'; import 'package:shopack_user/core/utilities/mediaquery.dart'; import 'package:shopack_user/core/utilities/strings.dart'; import '../../../../core/colors/colors.dart'; import '../../../home/presentation/view/product_details.dart'; import '../../../home/widgets/customGridView.dart'; import '../../../home/widgets/product_item.dart'; import '../bloc/products_bloc.dart'; import '../widgets/filter.dart'; import '../widgets/search.dart'; class ShopView extends StatelessWidget { const ShopView({super.key}); @override Widget build(BuildContext context) { int current = 0; return Scaffold( body: RefreshIndicator( onRefresh: () async { BlocProvider.of<ProductsBloc>(context).add(GetSpecificProduct( BlocProvider.of<ProductsBloc>(context).categories[current], '0', '100000', '-1', '')); }, child: SafeArea( child: BlocBuilder<ProductsBloc, ProductsState>( builder: (context, state) { final bloc = BlocProvider.of<ProductsBloc>(context); return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const FilterProduct(), Text( AppStrings.shop, style: Theme.of(context).textTheme.headline5, ), const SearchWidget() ], ), Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15), child: SizedBox( width: double.infinity, height: 60, child: ListView.builder( physics: const BouncingScrollPhysics(), itemCount: BlocProvider.of<ProductsBloc>(context) .categories .length, scrollDirection: Axis.horizontal, itemBuilder: (ctx, index) { return Column( children: [ GestureDetector( onTap: () { bloc.add(ChangeCatyegory(index)); bloc.add(GetSpecificProduct( bloc.categories[index], '0', '100000', '-1', '')); current = index; }, child: AnimatedContainer( duration: const Duration(milliseconds: 300), margin: const EdgeInsets.all(5), width: 80, height: 45, decoration: BoxDecoration( color: Colors.white70, borderRadius: bloc.current == index ? BorderRadius.circular(15) : BorderRadius.circular(10), border: bloc.current == index ? Border.all( color: ColorManager.orangeLight, width: 2) : null, ), child: Center( child: FittedBox( child: Text( bloc.categories[index], style: TextStyle( fontWeight: FontWeight.w500, color: bloc.current == index ? Colors.black : Colors.grey), ), ), ), ), ), ], ); }), ), ), BlocBuilder<ProductsBloc, ProductsState>( builder: (context, state) { if (state is FilterProductsLoadingState || state is SpecificProductsLoadingState) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: kHeight(context) / 3, ), const CircularProgressIndicator(), ], ); } else if (state is ProductsLoadedState) { final products = state.data.products; return Expanded( child: GridView.builder( padding: EdgeInsets.zero, itemCount: state.data.filteredProductsCount, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight( height: 330, crossAxisCount: 2), itemBuilder: (context, index) { return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProductDetails( product: products[index], products: products, index: index, ), )); }, child: Hero( tag: '$index', child: ProductItem(product: products[index]))); }, )); } else if (state is ProductsErrorState ) { return state.message == AppStrings.noInternetError ? Column( children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 14), child: Card(child: LottieBuilder.asset('assets/images/nointernet.json')), ), Card(child: Padding( padding: const EdgeInsets.all(8.0), child: Text(state.message), )) ], ) : Center(child: Text(state.message)); } else if (state is FilterProductsLoadedState) { final products = state.data.products; return Expanded( child: GridView.builder( padding: EdgeInsets.zero, itemCount: state.data.filteredProductsCount, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight( height: 330, crossAxisCount: 2), itemBuilder: (context, index) { return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProductDetails( product: products[index], products: products, index: index, ), )); }, child: Hero( tag: '$index', child: ProductItem(product: products[index]))); }, )); } else if (state is SpecificProductsLoadedState) { final products = state.data.products; return Expanded( child: GridView.builder( padding: EdgeInsets.zero, itemCount: state.data.filteredProductsCount, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCountAndFixedHeight( height: 330, crossAxisCount: 2), itemBuilder: (context, index) { return InkWell( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProductDetails( product: products[index], products: products, index: index, ), )); }, child: Hero( tag: '$index', child: ProductItem(product: products[index]))); }, )); } else if (state is SpecificProductsErrorState ) { return state.message == AppStrings.noInternetError ? Column( children: [ Padding( padding: const EdgeInsets.symmetric(vertical: 14,horizontal: 19), child: Card( clipBehavior: Clip.antiAlias, child: LottieBuilder.asset('assets/images/nointernet.json')), ), Card(child: Padding( padding: const EdgeInsets.all(8.0), child: Text(state.message), )) ], ) : Center(child: Text(state.message)); } else { return const SizedBox(); } }, ), ], ); }), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/views/reviews.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:intl/intl.dart'; import 'package:lottie/lottie.dart'; import 'package:shopack_user/features/shop/presentation/bloc/send_review_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../domain/entities/products_entity.dart'; import '../widgets/reviewsheet.dart'; class ReviewsView extends StatefulWidget { final ProductEntity product; const ReviewsView({super.key, required this.product}); @override State<ReviewsView> createState() => _ReviewsViewState(); } class _ReviewsViewState extends State<ReviewsView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios_new), ), title: Text(AppStrings.rateandreview, style: Theme.of(context).textTheme.headline6), ), floatingActionButton: SizedBox( width: kWidth(context) / 2.6, height: kHeight(context) / 14, child: FloatingActionButton.extended( backgroundColor: ColorManager.orangeLight, elevation: 8, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)), onPressed: () { showModalBottomSheet( isScrollControlled: true, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical( top: Radius.circular(35), ), ), context: context, builder: (BuildContext _) { return Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: ReviewSheet( id: widget.product.id, ), ); }); }, label: Row( children: [ const Icon(Icons.edit), const SizedBox( width: 5, ), SizedBox( width: kWidth(context) / 3.7, child: const FittedBox( child: Text( AppStrings.writereview, ), ), ), ], )), ), body: Stack(children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: BlocBuilder<SendReviewBloc, SendReviewState>( builder: (context, state) { if (state is GetAllReviewsLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is GetAllReviewsLoadedState) { return Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Column( children: [ Text(widget.product.ratings.toStringAsFixed(1), style: Theme.of(context).textTheme.headline6), Text( '${state.data.reviews!.length.toString()} ratings', style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: ColorManager.grey)), ], ), RatingBarIndicator( itemSize: 50.0, rating: widget.product.ratings.toDouble(), itemBuilder: (context, _) => const Icon( Icons.star, color: Colors.amber, ), direction: Axis.horizontal, ), ], ), Expanded( child: Center( child: state.data.reviews!.isEmpty ? Lottie.asset('assets/images/empty.json') : ListView.builder( itemCount: state.data.reviews!.length, itemBuilder: (context, index) { return Stack(children: [ SizedBox( height: kHeight(context) / 3.9, width: kWidth(context), ), Positioned( top: 25, left: 10, right: 10, child: SizedBox( width: kWidth(context), height: kHeight(context) / 4.5, child: Card( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(state.data .reviews![index].name!), Row( mainAxisAlignment: MainAxisAlignment .spaceBetween, children: [ RatingBarIndicator( itemSize: 20.0, rating: state.data.reviews![index].rating!.toDouble(), itemBuilder: (context, _) => const Icon( Icons.star, color: Colors.amber, ), direction: Axis.horizontal, ), Text( DateFormat.yMMMEd() .format(state .data .reviews![index] .createdAt!), style: Theme.of(context) .textTheme .bodyLarge! .copyWith( color: ColorManager .grey), ) ], ), const SizedBox( height: 10, ), Expanded( child: Text( maxLines: 7, overflow: TextOverflow.ellipsis, state.data.reviews![index] .comment!, textAlign: TextAlign.justify, ), ) ], ), )), ), ), const CircleAvatar( backgroundImage: AssetImage( 'assets/images/avatar.jpg'), ), ]); }, ))) ], ); } else if (state is GetAllReviewsErrorState) { return Center(child: Text(state.message)); } else { return const SizedBox(); } }, ), ), ]), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/widgets/review_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import 'package:intl/intl.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../domain/entities/products_entity.dart'; class ReviewCard extends StatelessWidget { final ProductEntity product; final int index; const ReviewCard({super.key, required this.product, required this.index}); @override Widget build(BuildContext context) { return Stack(children: [ SizedBox( height: kHeight(context) / 3.9, width: kWidth(context), ), Positioned( top: 25, left: 10, right: 10, child: SizedBox( width: kWidth(context), height: kHeight(context) / 4.5, child: Card( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(product.reviews![index].name!), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ RatingBarIndicator( itemSize: 20.0, rating: product.ratings.toDouble(), itemBuilder: (context, _) => const Icon( Icons.star, color: Colors.amber, ), direction: Axis.horizontal, ), Text( DateFormat.yMMMEd() .format(product.reviews![index].createdAt!), style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: ColorManager.grey), ) ], ), const SizedBox( height: 10, ), Expanded( child: Text( maxLines: 7, overflow: TextOverflow.ellipsis, product.reviews![index].comment!, textAlign: TextAlign.justify, ), ) ], ), )), ), ), const CircleAvatar( backgroundImage: AssetImage('assets/images/avatar.jpg'), ), ]); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/widgets/filter.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../../login/presentation/widgets/mainbutton.dart'; import '../bloc/products_bloc.dart'; class FilterProduct extends StatelessWidget { const FilterProduct({ super.key, }); @override Widget build(BuildContext context) { final bloc = BlocProvider.of<ProductsBloc>(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), child: Container( decoration: BoxDecoration( color: ColorManager.white, borderRadius: BorderRadius.circular(5), boxShadow: const [ BoxShadow( blurRadius: 5, color: ColorManager.grey, spreadRadius: 2, ) ], ), child: IconButton( onPressed: () { showModalBottomSheet( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical( top: Radius.circular(35), ), ), context: context, builder: (BuildContext _) { return SizedBox( height: kHeight(context) / 2.3, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ StatefulBuilder(builder: (_, setState) { return Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(AppStrings.filter, style: Theme.of(context) .textTheme .headline6), const SizedBox( height: 30, ), Text( AppStrings.price, style: Theme.of(context) .textTheme .titleMedium! .copyWith( color: ColorManager.grey, ), ), RangeSlider( activeColor: ColorManager.orangeLight, min: 5, max: 600, values: bloc.priceSelectRange, onChanged: (value) { setState(() { BlocProvider.of<ProductsBloc>(context) .priceSelectRange = value; }); }, divisions: 100, labels: RangeLabels( "${bloc.priceSelectRange.start.round().toString()}\$", "${bloc.priceSelectRange.end.round().toString()}\$", ), ), Text( AppStrings.rate, style: Theme.of(context) .textTheme .titleMedium! .copyWith( color: ColorManager.grey, ), ), const SizedBox( height: 5, ), Row( children: <Widget>[ Expanded( flex: bloc.rateValue.round() * 50, child: const SizedBox(), ), SizedBox( child: Text( 'Products Above ${(bloc.rateValue.round())} Stars', style: const TextStyle( color: ColorManager.grey), textAlign: TextAlign.center, ), ), Expanded( flex: 100 - bloc.rateValue.round(), child: const SizedBox(), ), ], ), Slider( min: 0, max: 4, activeColor: ColorManager.orangeLight, value: bloc.rateValue, onChanged: (v) { setState(() { bloc.rateValue = v; }); }, divisions:4, ), SizedBox( width: kWidth(context) / 2, child: BlocProvider.value( value: bloc, child: MainButton( text: AppStrings.apply, ontab: () { setState(() { bloc.add( GetFilterSpecificProduct( bloc.categories[ bloc.current], bloc.priceSelectRange .start .round() .toString(), bloc.priceSelectRange .end .round() .toString(), bloc.rateValue == 0 ? '-1' : bloc.rateValue .round() .toString(), '')); }); Navigator.pop(context); }, height: kHeight(context)/15), ), ), ], ); }), ], ), ), ); }); }, icon: const Icon(Icons.tune))), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/widgets/search.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../bloc/products_bloc.dart'; class SearchWidget extends StatefulWidget { const SearchWidget({super.key}); @override State<SearchWidget> createState() => _SearchWidgetState(); } class _SearchWidgetState extends State<SearchWidget> { @override Widget build(BuildContext context) { final formkey = GlobalKey<FormFieldState>(); final searchControler = TextEditingController(); final bloc = BlocProvider.of<ProductsBloc>(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), child: AnimatedContainer( width: bloc.searchFolded ? 50 : kWidth(context) * 0.6, duration: const Duration(milliseconds: 400), decoration: BoxDecoration( color: ColorManager.white, borderRadius: BorderRadius.circular(5), boxShadow: kElevationToShadow[6], ), child: Row( children: [ Expanded( child: bloc.searchFolded ? const SizedBox() : Form( key: formkey, child: TextFormField( controller: searchControler, decoration: InputDecoration( prefixIcon: IconButton( onPressed: () { bloc.add(GetFilterSpecificProduct( bloc.categories[bloc.current], '0', '100000', '-1', searchControler.text)); }, icon: const Icon(Icons.search)), hintText: 'Search', border: InputBorder.none), ), )), IconButton( onPressed: () { setState(() { bloc.searchFolded = !bloc.searchFolded; }); }, icon: bloc.searchFolded ? const Icon(Icons.search) : const Icon( Icons.close, color: ColorManager.grey, ), ) ], )), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/widgets/reviewsheet.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_rating_bar/flutter_rating_bar.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../../login/presentation/widgets/alert_snackbar.dart'; import '../../../login/presentation/widgets/mainbutton.dart'; import '../../../login/presentation/widgets/maintextformfield.dart'; import '../bloc/send_review_bloc.dart'; class ReviewSheet extends StatefulWidget { final String id; const ReviewSheet({super.key, required this.id}); @override State<ReviewSheet> createState() => _ReviewSheetState(); } class _ReviewSheetState extends State<ReviewSheet> { final TextEditingController reviewController = TextEditingController(); final formKey = GlobalKey<FormState>(); late num ratings; @override Widget build(BuildContext context) { return SizedBox( height: kHeight(context) / 1.9, child: Form( key: formKey, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: SingleChildScrollView( child: Column( children: [ const SizedBox( height: 20, ), Text( AppStrings.whatrate, style: Theme.of(context).textTheme.headline6, ), const SizedBox( height: 10, ), RatingBar( ratingWidget: RatingWidget( full: const Icon( Icons.star, color: Colors.amber, ), half: const Icon( Icons.star, ), empty: const Icon( Icons.star_border, color: ColorManager.grey, ), ), onRatingUpdate: (ratevalue) { setState(() { ratings = ratevalue; }); }, ), const SizedBox( height: 10, ), Text( AppStrings.plsshareopinion, style: Theme.of(context).textTheme.headline6, textAlign: TextAlign.center, ), const SizedBox( height: 10, ), MainTFF( max: 6, controller: reviewController, validate: (v) { return null; }, labelText: AppStrings.yourReview, isPassword: false, borderRadius: 15, inputType: TextInputType.text), const SizedBox( height: 20, ), BlocConsumer<SendReviewBloc, SendReviewState>( listener: (context, state) { if (state is SendReviewLoadedState && state.data.success) { showSnackbar(AppStrings.sendreviewsuccess, context, ColorManager.green); } else if (state is SendReviewLoadedState) { showSnackbar(state.data.message!, context, Colors.red); } else if (state is SendReviewErrorState) { showSnackbar(state.message, context, Colors.red); } }, builder: (context, state) { return state is SendReviewLoadingState ? const Center( child: CircularProgressIndicator(), ) : MainButton( text: AppStrings.sendReview, ontab: () { if (formKey.currentState!.validate()) { BlocProvider.of<SendReviewBloc>(context).add( SendReview(widget.id, reviewController.text, ratings)); Navigator.pop(context); } }, height: 40); }, ) ], ), ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/bloc/products_event.dart
part of 'products_bloc.dart'; abstract class ProductsEvent extends Equatable { const ProductsEvent(); @override List<Object> get props => []; } class GetAllProducts extends ProductsEvent {} class GetSpecificProduct extends ProductsEvent { final String category; final String minPrice; final String maxPrice; final String rate; final String keyword; const GetSpecificProduct( this.category, this.minPrice, this.maxPrice, this.rate, this.keyword, ); } class GetFilterSpecificProduct extends ProductsEvent { final String category; final String minPrice; final String maxPrice; final String rate; final String keyword; const GetFilterSpecificProduct( this.category, this.minPrice, this.maxPrice, this.rate, this.keyword, ); } class ChangeCatyegory extends ProductsEvent { final int index; const ChangeCatyegory(this.index); } class OpenSearch extends ProductsEvent {}
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/bloc/products_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import '../../../../core/usecase/usecase.dart'; import '../../domain/entities/products_entity.dart'; import '../../domain/usecases/getAllProducts_usecase.dart'; import '../../domain/usecases/getSpecificProduct.dart'; part 'products_event.dart'; part 'products_state.dart'; class ProductsBloc extends Bloc<ProductsEvent, ProductsState> { List<String> categories = [ "Clothes", "Shoes", "Electronics", "Smartphones", "Camera", "Sports", "Books", ]; int current = 0; RangeValues priceSelectRange = const RangeValues(200, 400); double rateValue = 0; bool searchFolded = true; final GetAllProductsUsecase getAllProductsUsecase; final GetSpecificProductUseCase getSpecificProductUseCase; ProductsBloc(this.getAllProductsUsecase, this.getSpecificProductUseCase) : super( AllProductsLoadingState(), ) { on<GetAllProducts>((event, emit) async { final failurOrSuccess = await getAllProductsUsecase(NoParams()); failurOrSuccess.fold( (failure) => emit(AllProductsErrorState(failure.message)), (success) => emit(AllProductsLoadedState(success))); }); on<GetSpecificProduct>((event, emit) async { emit(SpecificProductsLoadingState()); final failurOrSuccess = await getSpecificProductUseCase( GetProductUseCaseParams(event.category, event.minPrice, event.maxPrice, event.rate, event.keyword), ); failurOrSuccess.fold( (failure) => emit(SpecificProductsErrorState(failure.message)), (success) => emit(SpecificProductsLoadedState(success))); }); on<ChangeCatyegory>((event, emit) { current = event.index; emit(ChangeCategoryState()); }); on<GetFilterSpecificProduct>((event, emit) async { emit(FilterProductsLoadingState()); final failurOrSuccess = await getSpecificProductUseCase( GetProductUseCaseParams(event.category, event.minPrice, event.maxPrice, event.rate, event.keyword), ); failurOrSuccess.fold( (failure) => emit(ProductsErrorState(failure.message)), (success) => emit(FilterProductsLoadedState(success))); }); on<OpenSearch>((event, emit) { searchFolded = !searchFolded; emit(OpenSearchState()); }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/bloc/products_state.dart
part of 'products_bloc.dart'; abstract class ProductsState extends Equatable { const ProductsState(); @override List<Object> get props => []; } class AllProductsLoadingState extends ProductsState {} class AllProductsLoadedState extends ProductsState { final ProductsEntity data; const AllProductsLoadedState( this.data, ); } class AllProductsErrorState extends ProductsState { final String message; const AllProductsErrorState(this.message); } class ProductsLoadingState extends ProductsState {} class ProductsLoadedState extends ProductsState { final ProductsEntity data; const ProductsLoadedState( this.data, ); } class FilterProductsLoadingState extends ProductsState {} class FilterProductsLoadedState extends ProductsState { final ProductsEntity data; const FilterProductsLoadedState( this.data, ); } class ProductsErrorState extends ProductsState { final String message; const ProductsErrorState(this.message); } class SpecificProductsLoadingState extends ProductsState {} class SpecificProductsLoadedState extends ProductsState { final ProductsEntity data; const SpecificProductsLoadedState(this.data); } class SpecificProductsErrorState extends ProductsState { final String message; const SpecificProductsErrorState(this.message); } class ChangeCategoryState extends ProductsState {} class OpenSearchInitialState extends ProductsState {} class OpenSearchState extends ProductsState {}
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/bloc/send_review_event.dart
part of 'send_review_bloc.dart'; abstract class SendReviewEvent extends Equatable { const SendReviewEvent(); @override List<Object> get props => []; } class SendReview extends SendReviewEvent { final String productId; final String comment; final num rating; const SendReview(this.productId, this.comment, this.rating); } class GetReviews extends SendReviewEvent { final String productId; const GetReviews(this.productId); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/bloc/send_review_state.dart
part of 'send_review_bloc.dart'; abstract class SendReviewState extends Equatable { const SendReviewState(); @override List<Object> get props => []; } class SendReviewInitial extends SendReviewState {} class SendReviewLoadingState extends SendReviewState {} class SendReviewLoadedState extends SendReviewState { final ResponseEntity data; const SendReviewLoadedState(this.data); } class SendReviewErrorState extends SendReviewState { final String message; const SendReviewErrorState(this.message); } class GetAllReviewsLoadingState extends SendReviewState {} class GetAllReviewsLoadedState extends SendReviewState { final GetReviewsEntity data; const GetAllReviewsLoadedState(this.data); } class GetAllReviewsErrorState extends SendReviewState { final String message; const GetAllReviewsErrorState(this.message); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/presentation/bloc/send_review_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:shopack_user/features/shop/domain/entities/reviews_entity.dart'; import 'package:shopack_user/features/shop/domain/usecases/getAllReviews.dart'; import '../../domain/entities/response_entity.dart'; import '../../domain/usecases/sendReview_usecase.dart'; part 'send_review_event.dart'; part 'send_review_state.dart'; class SendReviewBloc extends Bloc<SendReviewEvent, SendReviewState> { final SendReviewUsecase sendReviewUsecase; final GetReviewsUsecase getReviewsUsecase; SendReviewBloc(this.sendReviewUsecase, this.getReviewsUsecase) : super(SendReviewInitial()) { on<SendReview>((event, emit) async { emit(SendReviewLoadingState()); final failurOrSuccess = await sendReviewUsecase( SendReviewUsecaseParams( event.productId, event.comment, event.rating, ), ); failurOrSuccess.fold( (failure) => emit(SendReviewErrorState(failure.message)), (success) { emit(SendReviewLoadedState(success)); add(GetReviews(event.productId)); }); }); on<GetReviews>((event, emit) async { emit(GetAllReviewsLoadingState()); final failurOrSuccess = await getReviewsUsecase(GetReviewsUsecaseParams(event.productId)); failurOrSuccess .fold((failure) => emit(GetAllReviewsErrorState(failure.message)), (success) { emit(GetAllReviewsLoadedState(success)); }); }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/entities/reviews_entity.dart
import 'package:equatable/equatable.dart'; class GetReviewsEntity extends Equatable { final bool success; final List<GetReviewEntity>? reviews; const GetReviewsEntity(this.success, this.reviews); @override List<Object?> get props => [success, reviews]; } class GetReviewEntity extends Equatable { final String? user; final String? name; final num? rating; final String? comment; final DateTime? createdAt; const GetReviewEntity( this.user, this.name, this.rating, this.comment, this.createdAt); @override List<Object?> get props => [user, name, rating, comment]; }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/entities/response_entity.dart
import 'package:equatable/equatable.dart'; class ResponseEntity extends Equatable { final bool success; final String? message; const ResponseEntity(this.success, this.message); @override List<Object?> get props => [success, message]; }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/entities/products_entity.dart
import 'package:equatable/equatable.dart'; class ProductsEntity extends Equatable { final bool success; final List<ProductEntity> products; final int filteredProductsCount; const ProductsEntity( this.success, this.products, this.filteredProductsCount, ); @override List<Object> get props => [success, products, filteredProductsCount]; } class ProductEntity extends Equatable { final String id; final String name; final String description; final int price; final num ratings; final List<ImageEntity> images; final String category; final int stock; final int numOfReviews; final String user; final List<ReviewEntity>? reviews; int qouantity = 1; bool isFavourite = false; ProductEntity({ required this.id, required this.name, required this.description, required this.price, required this.ratings, required this.images, required this.category, required this.stock, required this.numOfReviews, required this.user, required this.reviews, this.isFavourite = false, this.qouantity=1, }); @override List<Object?> get props { return [ id, name, description, price, ratings, images, category, stock, numOfReviews, user, reviews, isFavourite, ]; } } class ImageEntity extends Equatable { final String publicid; final String url; const ImageEntity(this.publicid, this.url); @override List<Object> get props => [publicid, url]; } class ReviewEntity extends Equatable { final String? user; final String? name; final num? rating; final String? comment; final DateTime? createdAt; const ReviewEntity( this.user, this.name, this.rating, this.comment, this.createdAt); @override List<Object?> get props => [user, name, rating, comment]; }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/repositories/product_repository.dart
import 'package:dartz/dartz.dart'; import 'package:shopack_user/features/shop/domain/entities/reviews_entity.dart'; import '../../../../core/error/failure.dart'; import '../entities/products_entity.dart'; import '../entities/response_entity.dart'; abstract class ProductRepository { Future<Either<Failure, ProductsEntity>> getAllProducts(); Future<Either<Failure, ProductsEntity>> getSpecificProduct( GetProductParams params); Future<Either<Failure, ResponseEntity>> sendReview(SendReviewParams params); Future<Either<Failure, GetReviewsEntity>> getReviews(GetReviewsParams params); } class GetProductParams { final String category; final String minPrice; final String maxPrice; final String rate; final String keyword; GetProductParams( this.category, this.minPrice, this.maxPrice, this.rate, this.keyword); } class SendReviewParams { final String productId; final String comment; final num rating; SendReviewParams(this.productId, this.comment, this.rating); } class GetReviewsParams { final String productId; GetReviewsParams(this.productId); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/usecases/getSpecificProduct.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/products_entity.dart'; import '../repositories/product_repository.dart'; class GetSpecificProductUseCase extends BaseUsecase<ProductsEntity, GetProductUseCaseParams> { final ProductRepository productRepository; GetSpecificProductUseCase(this.productRepository); @override Future<Either<Failure, ProductsEntity>> call( GetProductUseCaseParams params) async { return await productRepository.getSpecificProduct(GetProductParams( params.category, params.minPrice, params.maxPrice, params.rate, params.keyword)); } } class GetProductUseCaseParams { final String category; final String minPrice; final String maxPrice; final String rate; final String keyword; GetProductUseCaseParams( this.category, this.minPrice, this.maxPrice, this.rate, this.keyword); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/usecases/sendReview_usecase.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/response_entity.dart'; import '../repositories/product_repository.dart'; class SendReviewUsecase extends BaseUsecase<ResponseEntity, SendReviewUsecaseParams> { final ProductRepository productRepository; SendReviewUsecase(this.productRepository); @override Future<Either<Failure, ResponseEntity>> call(SendReviewUsecaseParams params) async { return await productRepository.sendReview(SendReviewParams(params.productId, params.comment, params.rating)); } } class SendReviewUsecaseParams { final String productId; final String comment; final num rating; SendReviewUsecaseParams(this.productId, this.comment, this.rating); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/usecases/getAllReviews.dart
import 'package:shopack_user/core/error/failure.dart'; import 'package:dartz/dartz.dart'; import 'package:shopack_user/core/usecase/usecase.dart'; import 'package:shopack_user/features/shop/domain/entities/reviews_entity.dart'; import '../repositories/product_repository.dart'; class GetReviewsUsecase extends BaseUsecase<GetReviewsEntity, GetReviewsUsecaseParams> { final ProductRepository productRepository; GetReviewsUsecase(this.productRepository); @override Future<Either<Failure, GetReviewsEntity>> call( GetReviewsUsecaseParams params) async { return await productRepository.getReviews(GetReviewsParams(params.productId)); } } class GetReviewsUsecaseParams { final String productId; GetReviewsUsecaseParams(this.productId); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/shop/domain/usecases/getAllProducts_usecase.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/products_entity.dart'; import '../repositories/product_repository.dart'; class GetAllProductsUsecase extends BaseUsecase<ProductsEntity,NoParams > { final ProductRepository productRepository; GetAllProductsUsecase(this.productRepository); @override Future<Either<Failure, ProductsEntity>> call(NoParams params) async { return await productRepository.getAllProducts(); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data/models/error_model.dart
class ErrorModel { bool? success; String? message; ErrorModel(this.message, this.success); factory ErrorModel.fromJson(Map<String, dynamic> json) => ErrorModel(json["message"], json['success']); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data/models/login_model.dart
import '../../domin/entities/login_entity.dart'; class LoginModel extends LoginEntity { const LoginModel( { super.id, super.name, super.email, super.message, super.role, super.createdAt, super.success, super.token}); factory LoginModel.fromJson(Map<String, dynamic> json) => LoginModel( id: json["_id"]??"", name: json["name"]??"", email: json["email"]??"", role: json["role"]??"", createdAt: DateTime.parse(json["createdAt"]??"2022-11-26T18:08:07.693Z") , token: json["token"]??"", success: json["success"]??true, message: json["message"]??"wellcome", ); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data/datasources/login_datasource.dart
import '../../../../core/network/api_provider.dart'; import '../../../../core/utilities/endpoints.dart'; import '../../domin/repositories/login_repository.dart'; import '../models/login_model.dart'; abstract class LoginDatasource { Future<LoginModel> login(LoginParams params); } class LoginDatasourceImpl implements LoginDatasource { final APIProvider apiProvider; LoginDatasourceImpl(this.apiProvider); @override Future<LoginModel> login(LoginParams params) async { final response = await apiProvider.post(endPoint: loginEndPoint, data: { "email": params.email, "password": params.password, }); return LoginModel.fromJson(response.data); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/data/repositories/login_repostory_impl.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/error_handler.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/network/network_info.dart'; import '../../../../core/utilities/strings.dart'; import '../../domin/entities/login_entity.dart'; import '../../domin/repositories/login_repository.dart'; import '../datasources/login_datasource.dart'; class LoginRepositoryImpl implements LoginBaseRepository { final LoginDatasource loginDatasource; final NetworkInfo networkInfo; LoginRepositoryImpl(this.loginDatasource, this.networkInfo); @override Future<Either<Failure, LoginEntity>> login(LoginParams params) async { if (await networkInfo.isConnected) { try { final response = await loginDatasource.login(params); return right(response); } catch (error) { print(error); return left(ErrorHandler.handle(error).failure); } } else { return const Left(OfflineFailure(AppStrings.noInternetError)); } } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/domin
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/domin/entities/login_entity.dart
import 'package:equatable/equatable.dart'; class LoginEntity extends Equatable { final String ? id; final String? name; final String? email; final String? role; final String ?message; final bool ?success; final DateTime ?createdAt; final String? token; const LoginEntity( { this.id, this.name, this.message, this.success, this.email, this.role, this.createdAt, this.token}); @override List<Object?> get props { return [ id, name, email, success, message, role, createdAt, token, ]; } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/domin
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/domin/repositories/login_repository.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../entities/login_entity.dart'; abstract class LoginBaseRepository { Future<Either<Failure, LoginEntity>> login(LoginParams params); } class LoginParams { final String email; final String password; LoginParams({required this.email, required this.password}); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/domin
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/domin/usecases/login_usecase.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/login_entity.dart'; import '../repositories/login_repository.dart'; class LoginUsecase extends BaseUsecase<LoginEntity, LoginUsecaseParams> { final LoginBaseRepository loginBaseRepository; LoginUsecase(this.loginBaseRepository); @override Future<Either<Failure, LoginEntity>> call(params) async { return await loginBaseRepository .login(LoginParams(email: params.email, password: params.password)); } } class LoginUsecaseParams { final String email; final String password; LoginUsecaseParams({required this.email, required this.password}); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/view/login.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/local/shared_preference.dart'; import '../../../../core/utilities/endpoints.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/routes.dart'; import '../../../../core/utilities/strings.dart'; import '../bloc/login_bloc.dart'; import '../widgets/alert_snackbar.dart'; import '../widgets/mainbutton.dart'; import '../widgets/maintextformfield.dart'; class LoginView extends StatefulWidget { const LoginView({super.key}); @override State<LoginView> createState() => _LoginViewState(); } class _LoginViewState extends State<LoginView> { final TextEditingController emailController = TextEditingController(); final TextEditingController passController = TextEditingController(); final formKey = GlobalKey<FormState>(); bool hidePass = true; @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Form( key: formKey, child: Column( children: [ SizedBox(height: kHeight(context) * 0.1), Row( children: [ Text( AppStrings.login, style: Theme.of(context).textTheme.headline4!.copyWith( fontWeight: FontWeight.bold, color: ColorManager.dark), ), ], ), SizedBox(height: kHeight(context) * 0.1), MainTFF( labelText: AppStrings.email, hintText: AppStrings.email, controller: emailController, validate: (value) { if (value!.isEmpty) { return AppStrings.emptyEmail; } else { if (!value.contains('@')) { return AppStrings.invalidEmail; } } return null; }, isPassword: false, borderRadius: 16, inputType: TextInputType.emailAddress), const SizedBox( height: 10, ), MainTFF( max: 1, labelText: AppStrings.password, hintText: AppStrings.password, controller: passController, validate: (value) { if (value!.isEmpty) { return AppStrings.passwordEmpty; } else { if (value.length < 6) { return AppStrings.passwordError; } } return null; }, isPassword: hidePass, suffix: IconButton( color: ColorManager.orangeLight, icon: hidePass ? const Icon(Icons.visibility_off) : const Icon(Icons.visibility), onPressed: () { setState(() { hidePass = !hidePass; }); }, ), borderRadius: 16, inputType: TextInputType.text), Align( alignment: Alignment.centerRight, child: TextButton( onPressed: () { Navigator.pushNamed( context, AppRoutes.forgotPassword); }, child: const Text(AppStrings.forgetPassword))), BlocConsumer<LoginBloc, LoginState>( listener: (context, state) { if (state is LoginFinishedState && state.data.success!) { PreferenceHelper.saveDataInSharedPreference( key: "token", value: state.data.token); showSnackbar(AppStrings.loginsuccess, context, ColorManager.green); PreferenceHelper.saveDataInSharedPreference( key: "IsLoggedIn", value: true); Navigator.pushReplacementNamed( context, AppRoutes.layout); } else if (state is LoginErrorState) { showSnackbar(state.message, context, Colors.red); } else if (state is LoginFinishedState) { showSnackbar(state.data.message!, context, Colors.red); } }, builder: (context, state) { return state is LoginLoadingState ? const CircularProgressIndicator() : MainButton( text: AppStrings.login.toUpperCase(), height: 50, ontab: () { if (formKey.currentState!.validate()) { BlocProvider.of<LoginBloc>(context).add( UserLogin(emailController.text, passController.text)); } }); }, ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(AppStrings.donthaveAccount, style: Theme.of(context).textTheme.labelLarge), TextButton( onPressed: () { Navigator.pushNamed(context, AppRoutes.register); }, child: const Text(AppStrings.register), ), Container( width: 20, height: 10, decoration: const BoxDecoration( image: DecorationImage( image: AssetImage("assets/images/arrow.png"))), ) ], ) ], ), ), ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/widgets/mainbutton.dart
import 'package:flutter/material.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; class MainButton extends StatelessWidget { final String text; final VoidCallback ontab; final double height; const MainButton( {Key? key, required this.text, required this.ontab, required this.height}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( width: kWidth(context), height: height, child: ElevatedButton( onPressed: ontab, child: Text( text, style: Theme.of(context) .textTheme .headline6! .copyWith(color: ColorManager.white,fontWeight: FontWeight.bold), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/widgets/alert_snackbar.dart
import 'package:flutter/material.dart'; showSnackbar(String message, context, Color color) { final snackbar = SnackBar( content: Text(message,style: const TextStyle(fontWeight: FontWeight.bold,color: Colors.black),), duration: const Duration(seconds: 2), backgroundColor: color, behavior: SnackBarBehavior.floating, ); ScaffoldMessenger.of(context).hideCurrentSnackBar(); ScaffoldMessenger.of(context).showSnackBar(snackbar); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/widgets/maintextformfield.dart
import 'package:flutter/material.dart'; class MainTFF extends StatelessWidget { const MainTFF({ Key? key, this.prefix, this.suffix, this.max, required this.controller, required this.validate, required this.isPassword, required this.borderRadius, this.readOnly, required this.inputType, this.hintText, this.labelText, this.textAlign, this.suffixPressed, }) : super(key: key); final Widget? prefix; final Widget? suffix; final TextEditingController controller; final bool isPassword; final double? borderRadius; final bool? readOnly; final int? max; final TextInputType inputType; final String? hintText; final String? labelText; final TextAlign? textAlign; final Function()? suffixPressed; final String? Function(String?)? validate; @override Widget build(BuildContext context) { return Material( elevation: 1.5, child: TextFormField( maxLines:max , obscureText: isPassword, keyboardType: inputType, controller: controller, validator: validate, decoration: InputDecoration( alignLabelWithHint: true, suffixIcon: suffix, prefixIcon: prefix, contentPadding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), label: Text(labelText!), border: const OutlineInputBorder(borderSide: BorderSide.none)), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/bloc/login_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import '../../domin/entities/login_entity.dart'; import '../../domin/usecases/login_usecase.dart'; part 'login_event.dart'; part 'login_state.dart'; class LoginBloc extends Bloc<LoginEvent, LoginState> { final LoginUsecase loginUsecase; LoginBloc( this.loginUsecase, ) : super(LoginInitialState()) { on<UserLogin>((event, emit) async { emit(LoginLoadingState()); final failureOrSuccess = await loginUsecase( LoginUsecaseParams(email: event.email, password: event.password)); failureOrSuccess.fold( (failure) => emit(LoginErrorState(failure.message)), (success) => emit(LoginFinishedState(data: success))); }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/bloc/login_state.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first part of 'login_bloc.dart'; abstract class LoginState extends Equatable { const LoginState(); @override List<Object> get props => []; } class LoginInitialState extends LoginState {} class LoginLoadingState extends LoginState {} class LoginFinishedState extends LoginState { final LoginEntity data; const LoginFinishedState({ required this.data, }); } class LoginErrorState extends LoginState { final String message; const LoginErrorState(this.message); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/login/presentation/bloc/login_event.dart
part of 'login_bloc.dart'; abstract class LoginEvent extends Equatable { const LoginEvent(); @override List<Object> get props => []; } class UserLogin extends LoginEvent { final String email; final String password; const UserLogin(this.email, this.password); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data/models/profile_model.dart
import 'package:shopack_user/features/profile/data/datasources/profile_local_datasource.dart'; import '../../domain/entities/profile_entity.dart'; class ProfileModel extends ProfileEntity { const ProfileModel(super.success, super.user, super.message); factory ProfileModel.fromJson(Map<String, dynamic> json) => ProfileModel( json['success'], json['user'] != null ? UserModel.fromJson(json['user']) : CacheManager().getItem("user-info")!.user, json['message'] ?? ''); } class UserModel extends UserEntity { const UserModel(super.id, super.name, super.email, super.avtar); factory UserModel.fromJson(Map<String, dynamic> json) => UserModel( json['_id'], json['name'], json['email'], json['avatar'] != null ? AvatarModel.fromJson(json['avatar']) : null); } class AvatarModel extends AvatarEntity { const AvatarModel(super.publicId, super.url); factory AvatarModel.fromJson(Map<String, dynamic> json) => AvatarModel(json['public_id'], json['url']); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data/datasources/profile_remote_datasource.dart
import '../../../../core/local/shared_preference.dart'; import '../../../../core/network/api_provider.dart'; import '../../../../core/utilities/endpoints.dart'; import '../../domain/repositories/profile_repository.dart'; import '../models/profile_model.dart'; abstract class ProfileDatasource { Future<ProfileModel> getUserDetails(); Future<ProfileModel> updateProfile(UpdateProfileParams params); Future<ProfileModel> updatePassword(UpdatePassParnms parnms); } class ProfileDataSourceImpl implements ProfileDatasource { final APIProvider apiProvider; ProfileDataSourceImpl(this.apiProvider); @override Future<ProfileModel> getUserDetails() async { final response = await apiProvider.get( endPoint: profileEndPoint, token: PreferenceHelper.getDataFromSharedPreference( key: 'token') ?? '', ); return ProfileModel.fromJson(response.data); } @override Future<ProfileModel> updateProfile(UpdateProfileParams params) async { final response = await apiProvider.put( endPoint: updateProfileEndPoint, data: { "avatar": params.avatar, "name": params.name, "email": params.email, }, token: PreferenceHelper.getDataFromSharedPreference( key: 'token') ?? '', ); return ProfileModel.fromJson(response.data); } @override Future<ProfileModel> updatePassword(UpdatePassParnms params) async { final response = await apiProvider.put( endPoint: updatePasswordEndPoint, data: { 'oldPassword': params.oldPassword, 'newPassword': params.newPassword, 'confirmPassword': params.confirmPassword, }, token: PreferenceHelper.getDataFromSharedPreference( key: 'token') ?? '', ); return ProfileModel.fromJson(response.data); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data/datasources/profile_local_datasource.dart
import 'package:hive_flutter/hive_flutter.dart'; import '../../../../core/local/cache_manager.dart'; import '../../domain/entities/profile_entity.dart'; class CacheManager implements CacheManagerBase<ProfileEntity> { @override Future<void> init() async { registerAdapter(); await Hive.openBox("profile-cahce"); } @override Future<void> addItem(ProfileEntity item) async { await Hive.box("profile-cahce").add(item); } @override void registerAdapter() { if (!Hive.isAdapterRegistered(1)) { Hive.registerAdapter(ProfileEntityAdapter()); Hive.registerAdapter(UserEntityAdapter()); Hive.registerAdapter(AvatarEntityAdapter()); } } @override ProfileEntity? getItem(String key) { return Hive.box("profile-cahce").get( key, ); } @override Future<void> putItem(ProfileEntity item) async { await Hive.box("profile-cahce").put("user-info", item); } @override Future<void> clearAll() async { await Hive.box("profile-cahce").clear(); } @override Future<void> clearAt(id) { throw UnimplementedError(); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/data/repositories/profile_repository_impl.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/error_handler.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/network/network_info.dart'; import '../../../../core/utilities/strings.dart'; import '../../domain/entities/profile_entity.dart'; import '../../domain/repositories/profile_repository.dart'; import '../datasources/profile_local_datasource.dart'; import '../datasources/profile_remote_datasource.dart'; class ProfileRepositoryImpl implements ProfileRepository { final ProfileDatasource profileDatasource; final NetworkInfo networkInfo; ProfileRepositoryImpl(this.profileDatasource, this.networkInfo); @override Future<Either<Failure, ProfileEntity>> getUserDetail() async { if (await networkInfo.isConnected) { try { final data = await profileDatasource.getUserDetails(); CacheManager().putItem(data); return right(data); } catch (error) { print(error); return left(ErrorHandler.handle(error).failure); } } else { final profile = CacheManager().getItem("user-info"); if (profile != null) return right(profile); return left(const OfflineFailure(AppStrings.noInternetError)); } } @override Future<Either<Failure, ProfileEntity>> updateProfile( UpdateProfileParams updateProfileParams) async { if (await networkInfo.isConnected) { try { final data = await profileDatasource.updateProfile(updateProfileParams); return right(data); } catch (error) { return left(ErrorHandler.handle(error).failure); } } else { return left(const OfflineFailure(AppStrings.noInternetError)); } } @override Future<Either<Failure, ProfileEntity>> updatePassword( UpdatePassParnms params) async { if (await networkInfo.isConnected) { try { final data = await profileDatasource.updatePassword(params); return right(data); } catch (error) { return left(ErrorHandler.handle(error).failure); } } else { return left(const OfflineFailure(AppStrings.noInternetError)); } } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/views/profile.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:lottie/lottie.dart'; import 'package:shopack_user/features/payment/presentation/bloc/order_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/local/shared_preference.dart'; import '../../../../core/theme/bloc/theme_bloc.dart'; import '../../../../core/theme/theme_data.dart'; import '../../../../core/theme/theme_service.dart'; import '../../../../core/utilities/enums.dart'; import '../../../../core/utilities/routes.dart'; import '../../../../core/utilities/strings.dart'; import '../bloc/profile_bloc.dart'; import '../widgets/listtile.dart'; class ProfileView extends StatelessWidget { const ProfileView({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ BlocBuilder<ThemeBloc, ThemeState>( builder: (context, state) { late AppTheme currentTheme; return IconButton( onPressed: () { if (state.themeData == appThemeData[AppTheme.lightTheme]) { currentTheme = AppTheme.values[1]; ThemeDatabaseService.putThemeSettings(1); } else { currentTheme = AppTheme.values[0]; ThemeDatabaseService.putThemeSettings(0); } context .read<ThemeBloc>() .add(ThemeChanged(theme: currentTheme)); }, icon: state.themeData == appThemeData[AppTheme.lightTheme] ? const Icon(Icons.sunny) : const Icon(Icons.mode_night), ); }, ), ], automaticallyImplyLeading: false, centerTitle: true, title: Text( AppStrings.myProfile, style: Theme.of(context).textTheme.headline6!.copyWith( fontWeight: FontWeight.bold, ), ), ), body: SafeArea( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8), child: BlocBuilder<ProfileBloc, ProfileState>( builder: (context, state) { if (state is ProfileLoadedState) { return SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox( height: 25, ), state.data.user!.avtar != null ? CircleAvatar( radius: 50, backgroundImage: NetworkImage(state.data.user!.avtar!.url), ) : const CircleAvatar( radius: 50, backgroundImage: NetworkImage( 'https://e7.pngegg.com/pngimages/799/987/png-clipart-computer-icons-avatar-icon-design-avatar-heroes-computer-wallpaper-thumbnail.png'), ), Padding( padding: const EdgeInsets.all(8.0), child: SizedBox( child: Column( children: [ Text( state.data.user!.name, style: Theme.of(context).textTheme.subtitle1, ), const SizedBox( height: 4, ), Text( state.data.user!.email, style: Theme.of(context) .textTheme .labelLarge! .copyWith(color: ColorManager.grey), ) ], ), ), ), const SizedBox( height: 8, ), MYListTile( title: AppStrings.editPersonalInfo, subtitle: AppStrings.edit, ontab: () { Navigator.pushNamed(context, AppRoutes.updateProfile, arguments: state.data.user); }, ), MYListTile( title: AppStrings.myOrders, subtitle: AppStrings.orders, ontab: () { BlocProvider.of<OrderBloc>(context).add(GetAllOrders()); Navigator.pushNamed(context, AppRoutes.orders); }, ), MYListTile( title: AppStrings.changePassword, subtitle: AppStrings.changePasswordsub, ontab: () { Navigator.pushNamed(context, AppRoutes.updatePassword); }, ), ListTile( onTap: () { Navigator.pushReplacementNamed( context, AppRoutes.login); PreferenceHelper.removeData(key: 'token'); }, title: Text( AppStrings.logout, style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: Colors.red), ), dense: true, trailing: const Icon( Icons.logout, size: 15, color: Colors.red, )) ], ), ); } else if (state is ProfileLoadingState) { return const Center(child: CircularProgressIndicator()); } else if (state is ProfileErrorState) { return state.message == AppStrings.noInternetError ? Column( children: [ Padding( padding: const EdgeInsets.symmetric( vertical: 20, horizontal: 16), child: Card( clipBehavior: Clip.antiAlias, child: LottieBuilder.asset( 'assets/images/nointernet.json')), ), Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Text(state.message), )) ], ) : Center(child: Text(state.message)); } else { return const SizedBox(); } }, ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/views/updateprofile.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../../login/presentation/widgets/alert_snackbar.dart'; import '../../../login/presentation/widgets/mainbutton.dart'; import '../../../login/presentation/widgets/maintextformfield.dart'; import '../../domain/entities/profile_entity.dart'; import '../bloc/profile_bloc.dart'; class UpdateProfileView extends StatefulWidget { final UserEntity user; const UpdateProfileView({super.key, required this.user}); @override State<UpdateProfileView> createState() => _UpdateProfileViewState(); } class _UpdateProfileViewState extends State<UpdateProfileView> { final formKey = GlobalKey<FormState>(); final TextEditingController emailController = TextEditingController(); final TextEditingController nameController = TextEditingController(); @override void initState() { emailController.text = widget.user.email; nameController.text = widget.user.name; super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, leading: IconButton( onPressed: () { BlocProvider.of<ProfileBloc>(context).add(GetProfile()); Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios)), title: Text( AppStrings.personalinfo, style: Theme.of(context).textTheme.headline6!.copyWith( fontWeight: FontWeight.bold, color: ColorManager.dark), ), ), body: SafeArea( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: Form( key: formKey, child: Column( children: [ SizedBox(height: kHeight(context) * 0.1), BlocBuilder<ProfileBloc, ProfileState>( builder: (context, state) { if (state is UploadImageState) { return Stack(children: [ SizedBox( width: kWidth(context) * .25, height: kHeight(context) * .14, ), CircleAvatar( radius: 50, backgroundImage: NetworkImage(state .image.secureUrl == null ? 'https://e7.pngegg.com/pngimages/799/987/png-clipart-computer-icons-avatar-icon-design-avatar-heroes-computer-wallpaper-thumbnail.png' : state.image.secureUrl!), ), Positioned( left: 2, bottom: 6, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, boxShadow: kElevationToShadow[6]), child: CircleAvatar( backgroundColor: ColorManager.white, radius: 15.0, child: InkWell( onTap: () { BlocProvider.of<ProfileBloc>(context) .add(UploadImage()); }, child: const Icon( Icons.camera_alt, size: 20.0, color: ColorManager.grey, ), ), ), ), ) ]); } else if (state is UploadImagesLoadingState || state is UpdateProfileLoadingState) { return const CircleAvatar( radius: 50, backgroundColor: ColorManager.grey, child: CircularProgressIndicator(), ); } else if (state is ProfileUpdateState) { return Stack(children: [ SizedBox( width: kWidth(context) * .25, height: kHeight(context) * .14, ), CircleAvatar( radius: 50, backgroundImage: NetworkImage(state .data.user!.avtar == null ? 'https://e7.pngegg.com/pngimages/799/987/png-clipart-computer-icons-avatar-icon-design-avatar-heroes-computer-wallpaper-thumbnail.png' : state.data.user!.avtar!.url), ), Positioned( left: 2, bottom: 6, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, boxShadow: kElevationToShadow[6]), child: CircleAvatar( backgroundColor: ColorManager.white, radius: 15.0, child: InkWell( onTap: () { BlocProvider.of<ProfileBloc>(context) .add(UploadImage()); }, child: const Icon( Icons.camera_alt, size: 20.0, color: ColorManager.grey, ), ), ), ), ) ]); } else { return Stack(children: [ SizedBox( width: kWidth(context) * .25, height: kHeight(context) * .14, ), CircleAvatar( radius: 50, backgroundImage: NetworkImage(widget.user.avtar == null ? 'https://e7.pngegg.com/pngimages/799/987/png-clipart-computer-icons-avatar-icon-design-avatar-heroes-computer-wallpaper-thumbnail.png' : widget.user.avtar!.url), ), Positioned( left: 2, bottom: 6, child: Container( decoration: BoxDecoration( shape: BoxShape.circle, boxShadow: kElevationToShadow[6]), child: CircleAvatar( backgroundColor: ColorManager.white, radius: 15.0, child: InkWell( onTap: () { BlocProvider.of<ProfileBloc>(context) .add(UploadImage()); }, child: const Icon( Icons.camera_alt, size: 20.0, color: ColorManager.grey, ), ), ), ), ) ]); } }, ), const SizedBox(height: 20), MainTFF( labelText: AppStrings.name, hintText: widget.user.name, controller: nameController, validate: (value) { if (value!.isEmpty) { return AppStrings.nameEmpty; } return null; }, borderRadius: 16, inputType: TextInputType.text, isPassword: false, ), const SizedBox( height: 10, ), MainTFF( labelText: AppStrings.email, hintText: widget.user.email, controller: emailController, validate: (value) { if (value!.isEmpty) { return AppStrings.emptyEmail; } else { if (!value.contains('@')) { return AppStrings.invalidEmail; } } return null; }, isPassword: false, borderRadius: 16, inputType: TextInputType.emailAddress), const SizedBox( height: 10, ), BlocConsumer<ProfileBloc, ProfileState>( listener: (context, state) { if (state is ProfileUpdateState && state.data.success) { showSnackbar(AppStrings.updateproflesuccess, context, ColorManager.green); } else if (state is UpdateProfileErrorState) { showSnackbar(state.message, context, Colors.red); } }, builder: (context, state) { return state is UpdateProfileLoadingState ? const CircularProgressIndicator() : MainButton( text: AppStrings.updateprofile.toUpperCase(), height: 50, ontab: () { if (formKey.currentState!.validate()) { BlocProvider.of<ProfileBloc>(context).add( UpdataProfileEvent( nameController.text, emailController.text, BlocProvider.of<ProfileBloc>(context) .response! .secureUrl!)); } }); }, ), const SizedBox( height: 20, ), ], ), ), ), ))); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/views/order_details.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:shopack_user/core/colors/colors.dart'; import '../../../../core/utilities/strings.dart'; import '../../../payment/domain/entities/all_orders_entity.dart'; import '../widgets/order_details_card.dart'; class OrderDetailsView extends StatelessWidget { final AllOrderEntity order; const OrderDetailsView({super.key, required this.order}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios)), title: Text( AppStrings.orderdetails, style: Theme.of(context).textTheme.headline6, ), ), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Order ID: ${order.id}', style: Theme.of(context).textTheme.labelSmall, ), const SizedBox( height: 8, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Items: ${order.orderItems.length}', style: Theme.of(context).textTheme.labelLarge!.copyWith( color: ColorManager.orangeLight, )), Row( children: [ const Icon(Icons.schedule), const SizedBox( width: 6, ), Text( DateFormat.yMMMEd().format(order.paidAt), style: Theme.of(context).textTheme.labelLarge, ), ], ), ], ), const SizedBox( height: 8, ), Text( '${AppStrings.deliveryAddress}: ${order.shippingInfo.address}'), const SizedBox( height: 8, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Status: PAID', style: Theme.of(context).textTheme.labelLarge!.copyWith( color: ColorManager.green, )), const SizedBox( width: 6, ), Text("Method: PAYMOB", style: Theme.of(context).textTheme.bodyMedium!) ], ), const Divider(), Text( 'Order Items:', style: Theme.of(context).textTheme.headline6, ), Expanded( child: ListView.separated( separatorBuilder: (context, index) => const Divider(), itemCount: order.orderItems.length, itemBuilder: (context, index) => OrderDetailsCard( order: order, index: index, )), ), ], ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/views/updatePass.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/routes.dart'; import '../../../../core/utilities/strings.dart'; import '../../../login/presentation/widgets/alert_snackbar.dart'; import '../../../login/presentation/widgets/mainbutton.dart'; import '../../../login/presentation/widgets/maintextformfield.dart'; import '../bloc/profile_bloc.dart'; import '../bloc/update_password_bloc.dart'; class UpdatePasswordView extends StatefulWidget { const UpdatePasswordView({super.key}); @override State<UpdatePasswordView> createState() => _UpdatePasswordViewState(); } class _UpdatePasswordViewState extends State<UpdatePasswordView> { final formKey = GlobalKey<FormState>(); final TextEditingController oldpassController = TextEditingController(); final TextEditingController newpassController = TextEditingController(); final TextEditingController repeatpassController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, leading: IconButton( onPressed: () { BlocProvider.of<ProfileBloc>(context).add(GetProfile()); Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios)), title: const Text( AppStrings.changePassword, style: TextStyle(color: ColorManager.dark), ), ), body: SingleChildScrollView( child: Form( key: formKey, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Column( children: [ SizedBox( height: kHeight(context) * .1, ), MainTFF( labelText: AppStrings.oldpassword, hintText: AppStrings.oldpassword, controller: oldpassController, validate: (value) { if (value!.isEmpty) { return AppStrings.oldpasswordEmpty; } else { if (value.length < 6) { return AppStrings.passwordError; } } return null; }, isPassword: false, borderRadius: 16, inputType: TextInputType.text), Align( alignment: Alignment.centerRight, child: TextButton( onPressed: () { Navigator.pushNamed( context, AppRoutes.forgotPassword); }, child: const Text(AppStrings.forgetPassword))), MainTFF( labelText: AppStrings.newpassword, hintText: AppStrings.newpassword, controller: newpassController, validate: (value) { if (value!.isEmpty) { return AppStrings.newpasswordEmpty; } else { if (value.length < 6) { return AppStrings.passwordError; } } return null; }, isPassword: false, borderRadius: 16, inputType: TextInputType.text), const SizedBox( height: 20, ), MainTFF( labelText: AppStrings.repeatpassword, hintText: AppStrings.repeatpassword, controller: repeatpassController, validate: (value) { if (value!.isEmpty) { return AppStrings.repeatpasswordEmpty; } else { if (value.length < 6) { return AppStrings.passwordError; } } return null; }, isPassword: false, borderRadius: 16, inputType: TextInputType.text), const SizedBox(height: 30), BlocConsumer<UpdatePasswordBloc, UpdatePasswordState>( listener: (context, state) { if (state is UpdatePasswordLoaded && state.data.success) { showSnackbar(AppStrings.updatepasssuccess, context, ColorManager.green); } else if (state is UpdatePasswordError) { showSnackbar(state.message, context, Colors.red); } else if (state is UpdatePasswordLoaded) { showSnackbar(state.data.message!, context, Colors.red); } }, builder: (context, state) { return state is UpdatePasswordLoading ? const CircularProgressIndicator() : MainButton( text: AppStrings.updatePass.toUpperCase(), height: 50, ontab: () { if (formKey.currentState!.validate()) { BlocProvider.of<UpdatePasswordBloc>(context) .add(UserUpdatePassword( oldpassController.text, newpassController.text, repeatpassController.text),); } }); }, ), ], ), ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/views/orders.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:lottie/lottie.dart'; import 'package:shopack_user/core/utilities/strings.dart'; import 'package:shopack_user/features/profile/presentation/widgets/order_card.dart'; import 'package:shopack_user/features/profile/presentation/widgets/order_cardpastOrders.dart'; import '../../../payment/presentation/bloc/order_bloc.dart'; class OrdersView extends StatelessWidget { const OrdersView({super.key}); @override Widget build(BuildContext context) { return DefaultTabController( initialIndex: 0, length: 2, child: Scaffold( appBar: AppBar( automaticallyImplyLeading: false, leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon(Icons.arrow_back_ios)), title: Text( AppStrings.myOrders, style: Theme.of(context).textTheme.headline6, ), bottom: const TabBar( tabs: [ Tab( text: AppStrings.activeOrders, ), Tab( text: AppStrings.deliveredOrders, ), ], ), ), body: TabBarView( children: <Widget>[ BlocBuilder<OrderBloc, OrderState>( builder: (context, state) { final bloc = BlocProvider.of<OrderBloc>(context); if (state is AllOrdersLoaded) { return bloc.activeOrders.isEmpty? LottieBuilder.asset('assets/images/empty.json') :ListView.builder( itemCount: bloc.activeOrders.length, itemBuilder: (context, index) => OrderCard(index: index) ); } else if (state is AllOrdersLoading) { return const Center( child: CircularProgressIndicator(), ); } else if (state is AllOrdersError) { return Text(state.message); } else { return const SizedBox(); } }, ), BlocBuilder<OrderBloc, OrderState>( builder: (context, state) { final bloc = BlocProvider.of<OrderBloc>(context); if (state is AllOrdersLoaded) { return bloc.pastOrders.isEmpty? LottieBuilder.asset('assets/images/empty.json') :ListView.builder( itemCount: bloc.pastOrders.length, itemBuilder: (context, index) => OrderCardPastOrders(index: index) ); } else if (state is AllOrdersLoading) { return const Center( child: CircularProgressIndicator(), ); } else if (state is AllOrdersError) { return Text(state.message); } else { return const SizedBox(); } }, ), ], ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/widgets/order_cardpastOrders.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/routes.dart'; import '../../../../core/utilities/strings.dart'; import '../../../payment/presentation/bloc/order_bloc.dart'; class OrderCardPastOrders extends StatelessWidget { final int index; const OrderCardPastOrders({super.key, required this.index}); @override Widget build(BuildContext context) { final bloc = BlocProvider.of<OrderBloc>(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: Container( width: kWidth(context), height: kHeight(context) / 6, decoration: BoxDecoration( color: ColorManager.white, boxShadow: kElevationToShadow[6], borderRadius: BorderRadius.circular(10)), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( DateFormat.yMMMEd().format(bloc.pastOrders[index].paidAt), style: Theme.of(context).textTheme.labelLarge, ), Text('${bloc.pastOrders[index].itemsPrice} \$') ], ), Text( "Order ID #${bloc.pastOrders[index].id}", style: Theme.of(context).textTheme.labelSmall, ), Text("Shipping To : ${bloc.pastOrders[index].shippingInfo.city}" .toUpperCase()), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ OutlinedButton( onPressed: () { Navigator.pushNamed(context, AppRoutes.orderDetails, arguments: bloc.pastOrders[index]); }, child: const Text(AppStrings.viewdetails), ), Row( children: [ const Icon( Icons.circle, color: ColorManager.green, size: 12, ), const SizedBox( width: 4, ), Text( "Delivered", style: Theme.of(context).textTheme.bodySmall, ) ], ) ], ) ], ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/widgets/order_details_card.dart
import 'package:flutter/material.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../payment/domain/entities/all_orders_entity.dart'; class OrderDetailsCard extends StatelessWidget { final int index; final AllOrderEntity order; const OrderDetailsCard({super.key, required this.index, required this.order}); @override Widget build(BuildContext context) { return SizedBox( width: kWidth(context), height: kHeight(context) / 8, child: Row( children: [ Container( width: kWidth(context) / 4, height: kHeight(context) / 9, decoration: BoxDecoration( color: ColorManager.white, borderRadius: BorderRadius.circular(15), image: DecorationImage( image: NetworkImage(order.orderItems[index].image))), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ SizedBox( width: kWidth(context) / 2, height: 30, child: Text( order.orderItems[index].name, overflow: TextOverflow.clip, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ SizedBox( width: kWidth(context) / 2.5, child: Text( '${order.orderItems[index].price} \$', overflow: TextOverflow.clip, ), ), SizedBox( child: FittedBox( child: Text( 'Quantity: ${order.orderItems[index].quantity} '))), ], ) ], ), ) ], ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/widgets/order_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; import 'package:shopack_user/core/utilities/routes.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; import '../../../../core/utilities/strings.dart'; import '../../../payment/presentation/bloc/order_bloc.dart'; class OrderCard extends StatelessWidget { final int index; const OrderCard({super.key, required this.index}); @override Widget build(BuildContext context) { final bloc = BlocProvider.of<OrderBloc>(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10), child: Container( width: kWidth(context), height:kHeight(context)>=800? kHeight(context) / 6: kHeight(context) / 3.5, decoration: BoxDecoration( color: ColorManager.white, boxShadow: kElevationToShadow[6], borderRadius: BorderRadius.circular(10)), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( DateFormat.yMMMEd().format(bloc.activeOrders[index].paidAt), style: Theme.of(context).textTheme.bodyMedium!.copyWith(color: ColorManager.dark,) ), Text('${bloc.activeOrders[index].itemsPrice} \$', style: Theme.of(context).textTheme.bodyMedium!.copyWith(color: ColorManager.dark,)) ], ), Text( "Order ID #${bloc.activeOrders[index].id}", style: Theme.of(context).textTheme.labelSmall!.copyWith(color: ColorManager.dark,), ), Text("Shipping To : ${bloc.activeOrders[index].shippingInfo.city}" .toUpperCase(), style: Theme.of(context).textTheme.bodyMedium!.copyWith(color: ColorManager.dark,)), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ OutlinedButton( onPressed: () { Navigator.pushNamed(context, AppRoutes.orderDetails, arguments: bloc.activeOrders[index]); }, child: const Text(AppStrings.viewdetails), ), Row( children: [ const Icon( Icons.circle, color: ColorManager.green, size: 12, ), const SizedBox( width: 4, ), Text( "Processing", style: Theme.of(context).textTheme.bodySmall!.copyWith(color: ColorManager.dark,) ) ], ) ], ) ], ), ), ), ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/widgets/listtile.dart
import 'package:flutter/material.dart'; import '../../../../core/colors/colors.dart'; import '../../../../core/utilities/mediaquery.dart'; class MYListTile extends StatelessWidget { final String title; final String? subtitle; final VoidCallback ontab; const MYListTile( {super.key, required this.title, this.subtitle, required this.ontab}); @override Widget build(BuildContext context) { return ListTile( onTap: ontab, title: Text( title, style: Theme.of(context) .textTheme .bodyLarge! , ), subtitle: SizedBox( width: kWidth(context) / 4, child: Text( subtitle!, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context) .textTheme .bodyMedium! .copyWith(color: ColorManager.grey,fontSize: 15), ), ), dense: true, trailing: const Icon( Icons.arrow_forward_ios, size: 15, ) ); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/bloc/update_password_state.dart
part of 'update_password_bloc.dart'; abstract class UpdatePasswordState extends Equatable { const UpdatePasswordState(); @override List<Object> get props => []; } class UpdatePasswordInitial extends UpdatePasswordState {} class UpdatePasswordLoading extends UpdatePasswordState {} class UpdatePasswordLoaded extends UpdatePasswordState { final ProfileEntity data; const UpdatePasswordLoaded(this.data); } class UpdatePasswordError extends UpdatePasswordState { final String message; const UpdatePasswordError(this.message); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/bloc/profile_state.dart
part of 'profile_bloc.dart'; abstract class ProfileState extends Equatable { const ProfileState(); @override List<Object> get props => []; } class ProfileInitial extends ProfileState {} class ProfileLoadingState extends ProfileState {} class ProfileLoadedState extends ProfileState { final ProfileEntity data; const ProfileLoadedState(this.data); } class ProfileErrorState extends ProfileState { final String message; const ProfileErrorState(this.message); } class UpdateProfileLoadingState extends ProfileState {} class UploadImagesLoadingState extends ProfileState { } class ProfileUpdateState extends ProfileState { final ProfileEntity data; const ProfileUpdateState(this.data); } class UpdateProfileErrorState extends ProfileState { final String message; const UpdateProfileErrorState(this.message); } class UploadImageState extends ProfileState { final CloudinaryResponse image; const UploadImageState(this.image); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/bloc/update_password_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import '../../domain/entities/profile_entity.dart'; import '../../domain/usecases/updatePassword.dart'; part 'update_password_event.dart'; part 'update_password_state.dart'; class UpdatePasswordBloc extends Bloc<UpdatePasswordEvent, UpdatePasswordState> { final UpdatePasswordUsecase updatePasswordUsecase; UpdatePasswordBloc(this.updatePasswordUsecase) : super(UpdatePasswordInitial()) { on<UserUpdatePassword>((event, emit) async { emit(UpdatePasswordLoading()); final failureOrSuccess = await updatePasswordUsecase( UpdatePasswordUsecaseParams( event.oldPassword, event.newPassword, event.confirmPassword)); failureOrSuccess.fold( (failure) => emit(UpdatePasswordError(failure.message)), (success) => emit(UpdatePasswordLoaded(success))); }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/bloc/profile_bloc.dart
import 'package:bloc/bloc.dart'; import 'package:cloudinary_sdk/cloudinary_sdk.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:image_picker/image_picker.dart'; import '../../../../core/usecase/usecase.dart'; import '../../domain/entities/profile_entity.dart'; import '../../domain/usecases/getUserDetail.dart'; import '../../domain/usecases/updateProfile.dart'; part 'profile_event.dart'; part 'profile_state.dart'; class ProfileBloc extends Bloc<ProfileEvent, ProfileState> { final ImagePicker imagePicker = ImagePicker(); String userName = ''; String userEmail = ''; final GetUserDetails getUserDetails; final UpdateUserDetailUsecase updataProfile; CloudinaryResponse? response; ProfileBloc(this.getUserDetails, this.updataProfile) : super(ProfileInitial()) { on<GetProfile>((event, emit) async { emit(ProfileLoadingState()); final failureOrSuccess = await getUserDetails(NoParams()); failureOrSuccess.fold( (failure) => emit(ProfileErrorState(failure.message)), (success) { userName = success.user!.name; userEmail = success.user!.email; emit(ProfileLoadedState(success)); }); }); on<UpdataProfileEvent>((event, emit) async { emit(UpdateProfileLoadingState()); final failureOrSuccess = await updataProfile( UpdateProfileUsecaseParams(event.name, event.email, event.avatar)); failureOrSuccess.fold( (failure) => emit(UpdateProfileErrorState(failure.message)), (success) { userName = success.user!.name; userEmail = success.user!.email; emit(ProfileUpdateState(success)); }); }); on<UploadImage>((event, emit) async { final XFile? selectedImage = await imagePicker.pickImage(source: ImageSource.gallery); emit(UploadImagesLoadingState()); final cloudinary = Cloudinary.full( apiKey: dotenv.env['CLOUDINARY_API_KEY']!, apiSecret: dotenv.env['CLOUDINARY_SECRET_KEY']!, cloudName: dotenv.env['CLOUDINARY_NAME']!); response = await cloudinary.uploadResource(CloudinaryUploadResource( filePath: selectedImage!.path, resourceType: CloudinaryResourceType.image, fileName: 'profile-avatar', )); emit(UploadImageState(response!)); }); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/bloc/profile_event.dart
part of 'profile_bloc.dart'; abstract class ProfileEvent extends Equatable { const ProfileEvent(); @override List<Object> get props => []; } class GetProfile extends ProfileEvent {} class UpdataProfileEvent extends ProfileEvent { final String name; final String email; final String avatar; const UpdataProfileEvent(this.name, this.email, this.avatar);} class UploadImage extends ProfileEvent { }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/presentation/bloc/update_password_event.dart
part of 'update_password_bloc.dart'; abstract class UpdatePasswordEvent extends Equatable { const UpdatePasswordEvent(); @override List<Object> get props => []; } class UserUpdatePassword extends UpdatePasswordEvent{ final String oldPassword; final String newPassword; final String confirmPassword; const UserUpdatePassword(this.oldPassword, this.newPassword, this.confirmPassword); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain/entities/profile_entity.dart
import 'package:equatable/equatable.dart'; import 'package:hive/hive.dart'; part 'profile_entity.g.dart'; @HiveType(typeId: 1) class ProfileEntity extends Equatable { @HiveField(0) final bool success; @HiveField(1) final UserEntity? user; @HiveField(2) final String? message; const ProfileEntity(this.success, this.user, this.message); @override List<Object?> get props => [success, user,message]; } @HiveType(typeId: 2) class UserEntity extends Equatable { @HiveField(0) final String id; @HiveField(1) final String name; @HiveField(2) final String email; @HiveField(3) final AvatarEntity ?avtar; const UserEntity(this.id, this.name, this.email, this.avtar); @override List<Object?> get props => [id, name, email, avtar]; } @HiveType(typeId: 3) class AvatarEntity extends Equatable { @HiveField(0) final String ?publicId; @HiveField(1) final String url; const AvatarEntity(this.publicId, this.url); @override List<Object?> get props => [publicId, url]; }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain/entities/profile_entity.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'profile_entity.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class ProfileEntityAdapter extends TypeAdapter<ProfileEntity> { @override final int typeId = 1; @override ProfileEntity read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return ProfileEntity( fields[0] as bool, fields[1] as UserEntity?, fields[2] as String?, ); } @override void write(BinaryWriter writer, ProfileEntity obj) { writer ..writeByte(3) ..writeByte(0) ..write(obj.success) ..writeByte(1) ..write(obj.user) ..writeByte(2) ..write(obj.message); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is ProfileEntityAdapter && runtimeType == other.runtimeType && typeId == other.typeId; } class UserEntityAdapter extends TypeAdapter<UserEntity> { @override final int typeId = 2; @override UserEntity read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return UserEntity( fields[0] as String, fields[1] as String, fields[2] as String, fields[3] as AvatarEntity?, ); } @override void write(BinaryWriter writer, UserEntity obj) { writer ..writeByte(4) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.name) ..writeByte(2) ..write(obj.email) ..writeByte(3) ..write(obj.avtar); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is UserEntityAdapter && runtimeType == other.runtimeType && typeId == other.typeId; } class AvatarEntityAdapter extends TypeAdapter<AvatarEntity> { @override final int typeId = 3; @override AvatarEntity read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return AvatarEntity( fields[0] as String?, fields[1] as String, ); } @override void write(BinaryWriter writer, AvatarEntity obj) { writer ..writeByte(2) ..writeByte(0) ..write(obj.publicId) ..writeByte(1) ..write(obj.url); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is AvatarEntityAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain/repositories/profile_repository.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../entities/profile_entity.dart'; abstract class ProfileRepository { Future<Either<Failure, ProfileEntity>> getUserDetail(); Future<Either<Failure, ProfileEntity>> updateProfile( UpdateProfileParams updateProfileParams); Future<Either<Failure, ProfileEntity>> updatePassword(UpdatePassParnms params); } class UpdateProfileParams { final String name; final String email; final String avatar; UpdateProfileParams(this.name, this.email, this.avatar); } class UpdatePassParnms { final String oldPassword; final String newPassword; final String confirmPassword; UpdatePassParnms(this.oldPassword, this.newPassword, this.confirmPassword); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain/usecases/updateProfile.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/profile_entity.dart'; import '../repositories/profile_repository.dart'; class UpdateUserDetailUsecase implements BaseUsecase<ProfileEntity, UpdateProfileUsecaseParams> { final ProfileRepository profileRepository; UpdateUserDetailUsecase(this.profileRepository); @override Future<Either<Failure, ProfileEntity>> call( UpdateProfileUsecaseParams params) async { return await profileRepository.updateProfile(UpdateProfileParams(params.name, params.email, params.avatar)); } } class UpdateProfileUsecaseParams { final String name; final String email; final String avatar; UpdateProfileUsecaseParams(this.name, this.email, this.avatar); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain/usecases/updatePassword.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/profile_entity.dart'; import '../repositories/profile_repository.dart'; class UpdatePasswordUsecase extends BaseUsecase<ProfileEntity, UpdatePasswordUsecaseParams> { final ProfileRepository profileRepository; UpdatePasswordUsecase(this.profileRepository); @override Future<Either<Failure, ProfileEntity>> call( UpdatePasswordUsecaseParams params) async { return await profileRepository.updatePassword(UpdatePassParnms(params.oldPassword, params.newPassword, params.confirmPassword)); } } class UpdatePasswordUsecaseParams { final String oldPassword; final String newPassword; final String confirmPassword; UpdatePasswordUsecaseParams( this.oldPassword, this.newPassword, this.confirmPassword); }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/profile/domain/usecases/getUserDetail.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/failure.dart'; import '../../../../core/usecase/usecase.dart'; import '../entities/profile_entity.dart'; import '../repositories/profile_repository.dart'; class GetUserDetails implements BaseUsecase<ProfileEntity, NoParams> { final ProfileRepository profileRepository; GetUserDetails(this.profileRepository); @override Future<Either<Failure, ProfileEntity>> call(NoParams params) async { return await profileRepository.getUserDetail(); } }
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/splash&onboarding/data
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/splash&onboarding/data/models/onboarding.dart
import 'package:shopack_user/core/utilities/strings.dart'; class OnBoardingContents { final String title; final String image; final String desc; OnBoardingContents({ required this.title, required this.image, required this.desc, }); } List<OnBoardingContents> contents = [ OnBoardingContents( title: AppStrings.onBoardingTitle1, image: "assets/images/1.png", desc: AppStrings.onBoardingSubTitle1, ), OnBoardingContents( title: AppStrings.onBoardingTitle2, image: "assets/images/sale.png", desc: AppStrings.onBoardingSubTitle2, ), OnBoardingContents( title: AppStrings.onBoardingTitle3, image: "assets/images/payment.png", desc: AppStrings.onBoardingSubTitle3, ), OnBoardingContents( title: AppStrings.onBoardingTitle4, image: "assets/images/delivery.png", desc: AppStrings.onBoardingSubTitle4, ), ];
0
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/splash&onboarding/presentation
mirrored_repositories/ShoPack-App-With-Clean-Architecture/lib/features/splash&onboarding/presentation/views/onBoarding.dart
import 'package:flutter/material.dart'; import 'package:shopack_user/core/colors/colors.dart'; import 'package:shopack_user/core/local/shared_preference.dart'; import 'package:shopack_user/core/utilities/mediaquery.dart'; import 'package:shopack_user/core/utilities/routes.dart'; import 'package:shopack_user/core/utilities/strings.dart'; import 'package:shopack_user/features/splash&onboarding/presentation/widgets/dots.dart'; import '../../data/models/onboarding.dart'; class OnBoardingView extends StatefulWidget { const OnBoardingView({Key? key}) : super(key: key); @override State<OnBoardingView> createState() => _OnBoardingViewState(); } class _OnBoardingViewState extends State<OnBoardingView> { late PageController controller; int currentPage = 0; @override void initState() { controller = PageController(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: ColorManager.onBoadingColor, body: SafeArea( child: Column( children: [ Expanded( flex: 3, child: PageView.builder( physics: const BouncingScrollPhysics(), controller: controller, onPageChanged: (value) => setState(() => currentPage = value), itemCount: contents.length, itemBuilder: (context, i) { return Padding( padding: const EdgeInsets.all(40.0), child: Column( children: [ const Spacer(), Image.asset( contents[i].image, height: kHeight(context) / 3, ), SizedBox( height: (kHeight(context) >= 840) ? 60 : 30, ), Text( contents[i].title, textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline5, ), const SizedBox(height: 20), Text( contents[i].desc, style: Theme.of(context).textTheme.titleMedium, textAlign: TextAlign.center, ) ], ), ); }, ), ), Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: List.generate( contents.length, (int index) => BulidDots( index: index, currentPage: currentPage, ), ), ), currentPage + 1 == contents.length ? Padding( padding: const EdgeInsets.all(30), child: ElevatedButton( onPressed: () { PreferenceHelper.saveDataInSharedPreference( key: "IsSkippedOnBoarding", value: true); Navigator.pushReplacementNamed( context, AppRoutes.splash); }, style: ElevatedButton.styleFrom( backgroundColor: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(50), ), padding: (kWidth(context) <= 550) ? const EdgeInsets.symmetric( horizontal: 100, vertical: 20) : EdgeInsets.symmetric( horizontal: kWidth(context) * 0.2, vertical: 25), textStyle: Theme.of(context).textTheme.bodyLarge, ), child: Text(AppStrings.start.toUpperCase()), ), ) : Padding( padding: const EdgeInsets.all(30), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ TextButton( onPressed: () { PreferenceHelper.saveDataInSharedPreference( key: "IsSkippedOnBoarding", value: true); Navigator.pushReplacementNamed( context, AppRoutes.splash); }, style: TextButton.styleFrom( elevation: 0, textStyle: TextStyle( fontWeight: FontWeight.w600, fontSize: (kWidth(context) <= 550) ? 13 : 17, ), ), child: Text( AppStrings.skip.toUpperCase(), style: const TextStyle(color: Colors.black), ), ), ElevatedButton( onPressed: () { controller.nextPage( duration: const Duration(milliseconds: 200), curve: Curves.easeIn, ); }, style: ElevatedButton.styleFrom( backgroundColor: ColorManager.dark, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(100), ), elevation: 0, padding: (kWidth(context) <= 550) ? const EdgeInsets.symmetric( horizontal: 30, vertical: 20) : const EdgeInsets.symmetric( horizontal: 30, vertical: 25), textStyle: TextStyle( fontSize: (kWidth(context) <= 550) ? 13 : 17), ), child: const Text(AppStrings.next), ), ], ), ), ], ), ), ], ), ), ); } }
0