Files

874 lines
36 KiB
Dart

import 'dart:async';
import 'package:cherry_toast/cherry_toast.dart';
import 'package:cherry_toast/resources/arrays.dart';
import 'package:flutter/material.dart';
import 'package:initial_folder/helper/validator.dart';
import 'package:initial_folder/models/carts_model.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/screens/cart/components/cart_list.dart';
import 'package:initial_folder/screens/checkout/checkout_cart_page.dart';
import 'package:initial_folder/screens/checkout/components/field_kupon.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/login_regist/default_button.dart';
import 'package:provider/provider.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/providers/order_provider.dart' as orderProv;
import 'package:initial_folder/providers/radeem_voucher_provider.dart'
as radeemVoucher;
class CartPage extends StatefulWidget {
const CartPage({
Key? key,
this.idcourse,
this.cartsModel,
this.isiVoucher,
}) : super(key: key);
final String? idcourse;
final DataCartsModel? cartsModel;
final String? isiVoucher;
@override
State<CartPage> createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
Provider.of<CartsProvider>(context, listen: false).getCarts();
});
}
bool isChecked = true;
Set<int> selectedItems = {};
bool isMultiSelectionMode = false;
bool isToastShowing = false;
void _onItemLongPressed(int index) {
setState(() {
isMultiSelectionMode = true;
selectedItems.add(index);
});
}
void _onItemTapped(int index) {
// setState(() {
// if (selectedItems.contains(index)) {
// selectedItems.remove(index);
// if (selectedItems.isEmpty) {
// isMultiSelectionMode = false;
// }
// } else {
// selectedItems.add(index);
// }
// });
}
void _selectAllItems(bool selectAll, int itemCount) {
setState(() {
if (selectAll) {
for (int i = 0; i < itemCount; i++) {
selectedItems.add(i);
}
} else {
selectedItems.clear();
}
isChecked = selectAll;
});
}
void _showToast(String message) {
isToastShowing = true;
CherryToast.error(
title: Text(message),
animationDuration: Durations.medium1,
animationType: AnimationType.fromTop,
autoDismiss: true,
).show(context);
Timer(Duration(seconds: 2), () {
isToastShowing = false;
});
}
@override
Widget build(BuildContext context) {
List<String> idCarts = [];
Provider.of<orderProv.OrderProvider>(context, listen: false).clear();
TextEditingController kuponController = TextEditingController();
var kuponIsApplied = TextEditingController();
final selectedTotalPrice = Provider.of<TotalPriceProvider>(context);
Widget _validasiKupon() {
return Dialog(
elevation: 5.0,
child: Padding(
padding: const EdgeInsets.all(29),
child: Text(
'Kupon tidak valid atau sudah habis',
textAlign: TextAlign.center,
),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
);
}
Widget kupon(List<String> idKursus) {
Provider.of<orderProv.OrderProvider>(context).clear();
return Consumer<CartsProvider>(
builder: (context, state, _) {
var resultData = state.result!.data.length;
for (var i = 0; i <= resultData - 1; i++) {
if (state.result?.data[i].coupon != null) {
kuponIsApplied = TextEditingController(
text: state.result?.data[i].coupon?.codeCoupon ?? '');
return Column(
children: [
Row(
children: [
Expanded(
child: Container(
padding: EdgeInsets.only(
left: getProportionateScreenWidth(4),
top: getProportionateScreenHeight(14)),
child: FieldKupon(
prefix: IconButton(
onPressed: () async {
await Provider.of<
radeemVoucher
.RadeemVoucherProvider>(context,
listen: false)
.deleteCoupon(kuponIsApplied.text);
kuponIsApplied.text = '';
kuponIsApplied.clear();
Provider.of<orderProv.OrderProvider>(context,
listen: false)
.clear();
await Provider.of<CartsProvider>(context,
listen: false)
.getCarts();
},
icon: Icon(Icons.close),
iconSize: 15,
color: secondaryColor,
),
controler: kuponIsApplied,
),
),
),
SizedBox(width: getProportionateScreenWidth(13)),
Container(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(12),
vertical: getProportionateScreenHeight(8),
),
),
onPressed: () async {
final voucher = kuponIsApplied.text;
if (await Provider.of<
radeemVoucher.RadeemVoucherProvider>(
context,
listen: false)
.redeemVoucherCart(
idKursus,
voucher,
)) {
kuponIsApplied = TextEditingController(
text: state
.result?.data.last.coupon?.codeCoupon);
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => CartPage(),
),
);
} else {
showDialog(
barrierColor: Color.fromARGB(70, 24, 24, 24),
context: context,
builder: (context) {
return _validasiKupon();
},
);
}
},
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
'Gunakan',
textAlign: TextAlign.start,
style: thirdTextStyle.copyWith(
color: baruTextutih,
fontSize: getProportionateScreenWidth(13),
fontWeight: reguler,
),
),
SizedBox(width: getProportionateScreenWidth(8)),
Image.asset(
"assets/icons/cart_gunakan.png",
color: baruTextutih,
width: getProportionateScreenWidth(16),
),
],
),
),
),
],
),
],
);
}
}
return Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Container(
padding: EdgeInsets.only(
left: getProportionateScreenWidth(4),
top: getProportionateScreenHeight(14)),
child: FieldKupon(
controler: kuponController,
),
),
),
SizedBox(width: 14),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: primaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(12),
vertical: getProportionateScreenHeight(8),
),
),
onPressed: () async {
final voucher = kuponController.text;
if (await Provider.of<
radeemVoucher.RadeemVoucherProvider>(context,
listen: false)
.redeemVoucherCart(idKursus, voucher)) {
Provider.of<CartsProvider>(context, listen: false)
.getCarts();
kuponController.clear();
} else {
showDialog(
barrierColor: Color.fromARGB(70, 24, 24, 24),
context: context,
builder: (context) {
return _validasiKupon();
},
);
}
},
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
'Gunakan',
textAlign: TextAlign.start,
style: thirdTextStyle.copyWith(
color: baruTextutih,
fontSize: getProportionateScreenWidth(13),
fontWeight: reguler,
),
),
SizedBox(width: getProportionateScreenWidth(8)),
Image.asset(
"assets/icons/cart_gunakan.png",
width: getProportionateScreenWidth(16),
color: baruTextutih,
),
],
),
),
],
)
],
);
},
);
}
Widget custombottomCart(
String price, String total, List<String> coursesId) {
return SingleChildScrollView(
child: Container(
color: Theme.of(context).brightness == Brightness.dark
? seventeenColor.withOpacity(0.9)
: baruTextutih.withOpacity(0.3),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(
left: getProportionateScreenWidth(16),
right: getProportionateScreenWidth(16),
top: getProportionateScreenHeight(12),
),
child: Row(
children: [
Text(
'Subtotal Harga Kursus',
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3,
),
),
Spacer(),
SizedBox(width: getProportionateScreenWidth(8)),
if (int.parse(price) < 50000)
RichText(
text: TextSpan(
children: [
TextSpan(
text: numberFormat(total),
style: primaryTextStyle.copyWith(
letterSpacing: 0.5,
decoration: TextDecoration.lineThrough,
color: fourthColor,
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 2.8,
),
),
WidgetSpan(
child: SizedBox(
width: getProportionateScreenWidth(8))),
TextSpan(
text: numberFormat(int.parse(price) < 50000
? (int.parse(price) - 5000).toString()
: price),
style: thirdTextStyle.copyWith(
letterSpacing: 0.23,
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 2.8,
color: Theme.of(context).colorScheme.onPrimary,
),
),
],
),
)
else
RichText(
text: TextSpan(
children: [
TextSpan(
text: "",
style: primaryTextStyle.copyWith(
letterSpacing: 0.5,
decoration: TextDecoration.lineThrough,
color: fourthColor,
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 2.8,
),
),
WidgetSpan(
child: SizedBox(
width: getProportionateScreenWidth(8))),
TextSpan(
text: numberFormat(price),
style: thirdTextStyle.copyWith(
letterSpacing: 0.23,
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 2.8,
color: Theme.of(context).colorScheme.onPrimary,
),
)
],
),
),
],
),
),
SizedBox(height: getProportionateScreenHeight(3)),
Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(16)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Biaya Layanan',
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3,
),
),
Text(
numberFormat(int.parse(price) < 50000 ? "5000" : "0"),
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3,
),
),
],
),
),
SizedBox(height: getProportionateScreenHeight(3)),
Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(16)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Potongan Kupon',
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3,
),
),
Text(
numberFormat("0"),
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3,
),
),
],
),
),
SizedBox(height: getProportionateScreenHeight(16)),
Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(16)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Total Bayar',
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3.2,
),
),
Text(
numberFormat(price),
style: thirdTextStyle.copyWith(
fontWeight: bold,
fontSize: SizeConfig.blockHorizontal! * 3.2,
),
),
],
),
),
SizedBox(height: getProportionateScreenHeight(12)),
Consumer<CartsProvider>(
builder: (context, state, _) {
int _hasil = 0;
var priceDiscount = state.result!.data
.map((e) => int.parse(e.discountPrice ?? '0'))
.toList();
var diskonHarga = 0;
for (var i = 0; i < state.data.length; i++) {
diskonHarga += priceDiscount[i];
}
var potonganKupon = state.result!.potonganKupon;
return Container(
color: Theme.of(context).colorScheme.primaryContainer,
height: getProportionateScreenHeight(52),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(16)),
child: Row(
children: [
// GestureDetector(
// onTap: () {
// _selectAllItems(
// !isChecked, state.result!.data.length);
// },
// child: Container(
// decoration: BoxDecoration(
// color: isChecked
// ? (Theme.of(context).brightness ==
// Brightness.light
// ? baruTexthitam
// : baruTextutih)
// : Theme.of(context).brightness ==
// Brightness.light
// ? baruTextutih
// : seventeenColor,
// shape: BoxShape.rectangle,
// border: Border.all(
// color: isChecked
// ? Theme.of(context).brightness ==
// Brightness.light
// ? baruTexthitam
// : baruTextutih
// : (Theme.of(context).brightness ==
// Brightness.light
// ? baruTexthitam.withOpacity(0.7)
// : Colors.grey),
// width: getProportionateScreenWidth(3),
// ),
// borderRadius: BorderRadius.circular(6),
// ),
// width: getProportionateScreenWidth(18),
// height: getProportionateScreenHeight(16),
// child: isChecked
// ? Icon(
// Icons.check,
// size: getProportionateScreenWidth(13),
// color: Theme.of(context)
// .colorScheme
// .background,
// )
// : null,
// ),
// ),
SizedBox(width: getProportionateScreenWidth(5)),
// Text(
// 'Semua',
// style: thirdTextStyle.copyWith(
// fontWeight: reguler,
// fontSize: SizeConfig.blockHorizontal! * 3,
// ),
// ),
SizedBox(width: getProportionateScreenWidth(13)),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Total',
style: thirdTextStyle.copyWith(
fontWeight: reguler,
fontSize: SizeConfig.blockHorizontal! * 3.4,
),
),
Text(
numberFormat(price),
style: thirdTextStyle.copyWith(
fontWeight: bold,
fontSize: SizeConfig.blockHorizontal! * 3.8,
),
),
],
),
Spacer(),
Container(
child: DefaultButton(
isCart: true,
text: 'Checkout (${selectedItems.length})',
press: () {
if (!isToastShowing) {
if (selectedItems.isEmpty) {
_showToast("Anda belum memilih kursus!");
} else {
selectedTotalPrice.selectedTotalPrice =
int.parse(price);
setState(() {
if (potonganKupon != null) {
_hasil = potonganKupon;
}
});
Navigator.of(context).push(
CustomNavigator(
child: CheckoutCartPage(
idCart: idCarts,
potonganKupon: _hasil,
discountHarga: diskonHarga,
isCart: true,
),
),
);
}
}
},
),
),
],
),
),
);
},
),
],
),
),
);
}
return Scaffold(
resizeToAvoidBottomInset: true,
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.background,
centerTitle: true,
title: Text(
'Keranjang',
style: thirdTextStyle.copyWith(
letterSpacing: 1,
fontWeight: semiBold,
fontSize: getProportionateScreenWidth(14),
),
),
),
body: Consumer<CartsProvider>(
builder: (context, state, _) {
if (state.state == ResultState.Loading) {
return Center(
child: CircularProgressIndicator(
color: primaryColor,
strokeWidth: 2,
),
);
} else if (state.state == ResultState.HasData) {
List<String> coursesId = [];
var carts = state.result!.data;
for (int i = 0; i < carts.length; i++) {
idCarts.add(carts[i].cartId!);
}
for (int i = 0; i < carts.length; i++) {
coursesId.add(carts[i].courseId!);
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (state.result != null && selectedItems.isEmpty) {
_selectAllItems(true, state.result!.data.length);
}
});
return Stack(
children: [
SingleChildScrollView(
child: Container(
margin:
EdgeInsets.only(left: getProportionateScreenWidth(16)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${state.result?.data.length} Kursus di Keranjang ',
style: thirdTextStyle.copyWith(
letterSpacing: 1,
fontWeight: semiBold,
fontSize: getProportionateScreenWidth(14),
),
),
SizedBox(height: getProportionateScreenHeight(13)),
ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: state.result!.data.length,
itemBuilder: (context, index) {
var carts = state.result!.data[index];
Provider.of<orderProv.OrderProvider>(context)
.addOrder(
id: carts.courseId,
title: carts.title,
price: carts.price,
imageUrl: carts.thumbnail ??
'https://vocasia.id/uploads/thumbnails/course_thumbnails/course_thumbnail_default_63.jpg',
discountPrice: carts.finalPrice,
instructor: carts.instructor!,
);
bool isSelected = selectedItems.contains(index);
return GestureDetector(
onTap: () => _onItemTapped(index),
child: CartList(
idCourse: carts.courseId ?? '0',
id: carts.cartId ?? '',
image: carts.thumbnail ??
'https://vocasia.id/uploads/thumbnails/course_thumbnails/course_thumbnail_default_63.jpg',
title: carts.title ?? '',
instruktur: carts.instructor ?? '',
price: carts.price ?? '',
discountPrice: carts.finalPrice ?? '',
isSelected: isSelected,
),
);
},
),
SizedBox(height: 90),
],
),
),
),
],
);
} else if (state.state == ResultState.NoData) {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(height: 48),
Container(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(16)),
child: Center(
child: Column(
children: [
Container(
width: getProportionateScreenWidth(100),
height: getProportionateScreenHeight(100),
child: ColorFiltered(
colorFilter: ColorFilter.mode(
Theme.of(context).colorScheme.onPrimary,
BlendMode.srcATop,
),
child: Image.asset('assets/images/search.png'),
),
),
SizedBox(height: 16),
Text(
"Keranjang Kosong",
style: thirdTextStyle.copyWith(
letterSpacing: 1,
fontWeight: semiBold,
fontSize: getProportionateScreenWidth(14),
color: Theme.of(context).colorScheme.onPrimary,
),
),
SizedBox(height: 4),
Text(
"Keranjang kamu kosong, tetap berbelanja dan cari kursus",
textAlign: TextAlign.center,
style: thirdTextStyle.copyWith(
letterSpacing: 0.5,
fontWeight: reguler,
fontSize: getProportionateScreenWidth(12),
color: Theme.of(context).colorScheme.onPrimary,
),
),
SizedBox(height: 16),
Container(
margin: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(78),
vertical: getProportionateScreenHeight(10)),
child: DefaultButton(
weight: reguler,
text: 'Belanja Kursus',
press: () {
Navigator.of(context).pop();
},
),
),
],
),
),
),
],
),
);
} else if (state.state == ResultState.Error) {
return AlertDialog(
title: const Text('Koneksi Internet'),
content: const Text('Terjadi Kesalahan'),
actions: <Widget>[
TextButton(
onPressed: () => Navigator.pop(context, 'Cancel'),
child: const Text('Cancel'),
),
],
);
} else {
return Center(child: Text(''));
}
},
),
bottomNavigationBar: Consumer<CartsProvider>(
builder: (context, state, _) {
if (state.state == ResultState.Loading) {
return Container(
width: double.infinity,
height: getProportionateScreenHeight(121),
child: Center(
child: CircularProgressIndicator(
color: primaryColor,
strokeWidth: 2,
),
),
);
} else if (state.state == ResultState.HasData) {
var total = state.result!.data.map((e) {
if (e.price != null && e.discountPrice != null) {
return int.parse(e.discountPrice!) == 0
? 0
: int.parse(e.price!);
} else {
return 0;
}
}).toList();
var result = 0;
for (var i = 0; i < total.length; i++) {
result += total[i];
}
Provider.of<orderProv.OrderProvider>(context)
.getTotalPrice((state.result?.totalPayment.toString() ?? '0'));
var carts = state.result!.data;
List<String> coursesId = [];
for (int i = 0; i < carts.length; i++) {
coursesId.add(carts[i].courseId!);
}
selectedTotalPrice.selectedSubTotal = result.toString();
return custombottomCart(
state.result?.totalPayment.toString() ?? '0',
result.toString(),
coursesId,
);
} else if (state.state == ResultState.NoData) {
return Text(
"",
style: secondaryTextStyle.copyWith(
letterSpacing: 1,
fontWeight: semiBold,
fontSize: getProportionateScreenWidth(14),
color: tenthColor,
),
);
} else if (state.state == ResultState.Error) {
return Text('');
} else {
return Center(child: Text(''));
}
},
),
);
}
}
// Align(
// alignment: Alignment.bottomCenter,
// child: SingleChildScrollView(
// child: Container(
// padding: EdgeInsets.symmetric(
// horizontal: getProportionateScreenWidth(16)),
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Text(
// "Promotions",
// style: thirdTextStyle.copyWith(
// fontWeight: semiBold,
// letterSpacing: 1,
// fontSize: SizeConfig.blockHorizontal! * 3.4,
// ),
// ),
// kupon(coursesId),
// ],
// ),
// ),
// ),
// ),