提问人:KRAP 提问时间:10/4/2023 更新时间:10/4/2023 访问量:53
如何将班级中的数据发送到我的购物车
How can I get data from my class sent to my shopping cart
问:
我正在使用 Provider 为我的应用构建购物车。我现在可以使用列表索引将数据从我的购物车模型推送到我的购物车。但是,我想将我创建的类中的信息连接到购物车。我希望用户能够推送每个单独的产品,阅读有关细节的信息,然后选择添加到购物车。然后,能够返回到精心制作的 GridView 中显示的产品列表。
这是我的购物车模型:
class CartModel extends ChangeNotifier {
// list of items on sale
final List _shopItems = [
// [ title, productPrice ]
["Brazil", "15.00", "lib/assets/Brazil.png"],
["Colombia", "15.00", "lib/assets/Colombia.png"],
["Ethiopia", "15.00", "lib/assets/Ethiopia.png"],
["Indonesia", "15.00", "lib/assets/Indonesia.png"],
];
// list of cart items
final List _cartItems = [];
get cartItems => _cartItems;
get shopItems => _shopItems;
// add item to cart
void addItemToCart(int index) {
_cartItems.add(_shopItems[index]);
notifyListeners();
}
// remove item from cart
void removeItemFromCart(int index) {
_cartItems.removeAt(index);
notifyListeners();
}
// calculate total price
String calculateTotal() {
double totalPrice = 0;
for (int i = 0; i < cartItems.length; i++) {
totalPrice += double.parse(cartItems[i][1]);
}
return totalPrice.toStringAsFixed(2);
}
}
这是我的购物车屏幕:
Expanded(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView.builder(
itemCount: value.cartItems.length,
padding: const EdgeInsets.all(12),
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(12.0),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: ListTile(
leading: Image.asset(
value.cartItems[index][2],
height: 36,
),
title: Text(
value.cartItems[index][0],
style: const TextStyle(fontSize: 18),
),
subtitle: Text(
'\$' + value.cartItems[index][1],
style: const TextStyle(fontSize: 12),
),
trailing: IconButton(
icon: const Icon(Icons.cancel),
onPressed: () =>
Provider.of<CartModel>(context, listen: false)
.removeItemFromCart(index),
),
),
),
);
},
),
),
),
// total amount + pay now
Padding(
padding: const EdgeInsets.all(36.0),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.green,
),
padding: const EdgeInsets.all(24),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Total Price',
style: TextStyle(color: Colors.green[200]),
),
const SizedBox(height: 8),
// total price
Text(
'\$${value.calculateTotal()}',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
// pay now
Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.green.shade200),
borderRadius: BorderRadius.circular(28),
),
padding: const EdgeInsets.all(12),
child: Row(
children: const [
Text(
'Pay Now',
style: TextStyle(color: Colors.white),
),
Icon(
Icons.arrow_forward_ios,
size: 16,
color: Colors.white,
),
],
),
),
],
),
),
)
],
);
},
),
);
}
}
这是我想插入购物车模型的类:
class CoffeeItem {
const CoffeeItem(
{required this.id,
required this.title,
required this.image,
required this.description,
required this.image2,
required this.quantity,
required this.productPrice,
required this.unit});
final int id;
final String title;
final String image;
final String description;
final String image2;
final int productPrice;
final int quantity;
final String unit;
Map toJson() {
return {
'id': id,
'title': title,
'description': description,
'price': productPrice,
'image2': image2,
'image': image,
'quantity': quantity,
'unit': unit,
};
}
}
这是您按下“添加到购物车”按钮的屏幕,此处标记为“一次性购买”
class BeanScreen extends StatefulWidget {
const BeanScreen(this.coffeeItem, {Key? key}) : super(key: key);
final CoffeeItem coffeeItem;
@override
State<BeanScreen> createState() => _BeanScreen();
}
class _BeanScreen extends State<BeanScreen> {
/* DBHelper? dbHelper = DBHelper();
@override
void initState() {
super.initState();
context.read<CartProvider>().getData();
}
*/
@override
Widget build(BuildContext context) {
/* final cart = Provider.of<CartProvider>(context);
void saveData(int index) {
dbHelper!
.insert(
Cart(
id: widget.coffeeItem.id,
productId: index.toString(),
productName: widget.coffeeItem.title,
initialPrice: widget.coffeeItem.productPrice,
productPrice: widget.coffeeItem.productPrice,
quantity: ValueNotifier(1),
unitTag: widget.coffeeItem.unit,
image: widget.coffeeItem.image,
),
)
.then((value) {
cart.addTotalPrice(widget.coffeeItem.productPrice.toDouble());
cart.addCounter();
const snackBar = SnackBar(
backgroundColor: Color.fromARGB(255, 113, 52, 255),
content: Text('Item is added to cart'),
duration: Duration(seconds: 1),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}).onError((error, stackTrace) {
print(error.toString());
const snackBar = SnackBar(
backgroundColor: Color.fromARGB(255, 219, 56, 110),
content: Text('Item is all sold out!'),
duration: Duration(seconds: 1));
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
} */
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blueGrey,
title: const Text('Good Vibes Coffee Co.'),
centerTitle: true,
actions: [
InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const CartPage()));
},
child: Center(
child: Badge(
showBadge: true,
/* badgeContent: Consumer<CartProvider>(
builder: (context, value, child) {
return Text(value.getCounter().toString(),
style: const TextStyle(color: Colors.white));
},
), */
animationType: BadgeAnimationType.fade,
animationDuration: const Duration(milliseconds: 300),
child: const Icon(Icons.shopping_bag_outlined),
),
),
),
const SizedBox(width: 20.0)
],
),
body: Column(
children: [
Expanded(
child: Consumer<CartModel>(builder: (context, value, child) {
return ListView.builder(
itemCount: 1,
itemBuilder: (context, coffeeItem) {
return Column(
children: [
Card(
color: const Color.fromARGB(255, 255, 249, 193),
child: Stack(
alignment: Alignment.center,
children: [
ClipRRect(
borderRadius: const BorderRadius.all(
Radius.circular(10),
),
child: Image(
image: AssetImage(widget.coffeeItem.image2),
),
),
Center(
child: Text(
widget.coffeeItem.title,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.w900,
),
),
),
],
),
),
Row(
children: [
SizedBox(
width: MediaQuery.of(context).size.width,
child: Text(widget.coffeeItem.description,
overflow: TextOverflow.visible,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 18))),
],
),
Row(
children: const [
SizedBox(
height: 50,
),
],
),
Row(
children: [
const SizedBox(width: 40),
Consumer<CartModel>(
builder: (context, value, child) {
return ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(
const Color.fromARGB(
255, 36, 194, 141))),
onPressed: () {
Provider.of<CartModel>(context,
listen: false)
.addItemToCart(coffeeItem);
},
child: const Text('One-Time Purchase'),
);
},
),
const SizedBox(width: 75),
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(
255, 36, 194, 141))),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) =>
const Subscribe()),
));
},
child: const Text('Subscribe')),
],
),
Row(
children: const [
SizedBox(width: 80),
Text('\$15.00/12oz'),
SizedBox(width: 120),
Text('\$15.00/16oz')
],
),
Row(children: const [
SizedBox(height: 30),
]),
],
);
});
}),
),
],
),
);
}
}
我试过在字符串列表中只使用 etc.,但显然,你不能这样做。我还尝试将我的 CartModel 指向 CoffeeItem,然后告诉我的所有函数都指向那个地方,但它也不喜欢这样。coffeeItem.title
答:
0赞
Subrata Das
10/4/2023
#1
您可以获取您的提供商购物车数据,希望对您有所帮助
final po = Provider.of<CartModel>(context, listen: false);
List<CoffeeItem> cofeelist = [];
Map<String, CoffeeItem > _cart = po. _cartItems();
cofeelist = _cart.values.toList();
评论
0赞
KRAP
10/4/2023
这很漂亮。我该把它放在哪里?
0赞
Subrata Das
10/5/2023
你可以把小部件的开头 Buildcontext 放进去
评论