[英]how to use classes in flutter/dart
我創建了一個 class 產品。 然后我創建了一個名為購物車的空產品列表。 然后我嘗試將產品添加到此購物車並打印它,它在控制台上顯示產品實例。
class product {
late String name;
late int id,size,price;
product(String name,int id,int size,int price){
this.name=name;
this.size=size;
this.id=id;
this.price=price;
}
}
列出購物車=[];
願望清單頁面:
class wishlist extends StatefulWidget {
const wishlist({Key? key}) : super(key: key);
@override
State<wishlist> createState() => _wishlistState();
}
class _wishlistState extends State<wishlist> {
late String category;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: BackButton(
color: Colors.black,
),
backgroundColor: Color(0xFF45F1B9),
title: Center(
child: Text('Categories',
style: TextStyle(
color: Colors.black
),
),
),
),
backgroundColor: Colors.white,
body: ListView.builder(
itemCount: categories.length,
itemBuilder:(BuildContext context,int index){
return Card(child: ListTile(title: Text(categories[index].name,
),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => cpproducts1(categories[index].prod),),
);
},
),
);
},
),
);
}
}
第二頁'cproducts':
class cpproducts1 extends StatelessWidget {
late List<product> prod;
cpproducts1( this.prod, {Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ListView.builder(
itemCount:prod.length ,
itemBuilder:(BuildContext context,int index){
return Card(child: ListTile(title: Text(prod[index].name,),
trailing: Text('\$${prod[index].price}'),
onTap: (){
cart.add(prod[index]);
print(cart);
},
),
);
},
),
);
}
}
cart.add(prod[index]);
print(cart);
在這些行運行之后,它會顯示產品實例。
我需要將產品添加到購物車列表中,以便我可以使用它們
有沒有人知道這個問題的答案。
您可以以更簡單的方式創建構造函數,並且要知道實際值而不是 Class 的實例,您必須添加覆蓋toString
方法。
class Product {
const Product(this.name, this.id, this.size, this.price);
late final String name;
late final int id,size,price;
@override
String toString() => '$name, $id, $size, $price';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.