PIbd-31_Belianin_N._N._PMD/lib/ProductCode.txt

69 lines
1.6 KiB
Plaintext
Raw Normal View History

2024-09-17 00:43:15 +04:00
// Classes +
// Methods +
// Enums +
// Loops +
// Generics (List<>) +
// Anonymous functions +
// Future +
// Extension +
enum Type { tools, electrics, materials, gas }
extension ProductEx on Product {
double get discountedPrice => price * 0.9;
String get fullname => '${name} - \$${price}';
}
class Product {
String name;
double price;
int quantity;
Type type;
// Конструктор
Product(this.name, this.price, this.quantity, this.type);
}
class Cart {
final List<Product> items = [];
void push(Product p) {
items.add(p);
}
double getTotalPrice() {
double price = 0;
for (int i = 0; i < items.length; i++) {
price += items[i].quantity * items[i].price;
}
return price;
}
int getItemsCount() {
return items.fold(0, (total, item) => total + item.quantity);
}
Future<List<Product>> getItemsAsync() async {
await Future.delayed(Duration(seconds: 3));
return items;
}
}
void main() {
Cart cart = Cart();
Product product = Product('hammer', 1000.0, 4, Type.tools);
cart.push(product);
cart.push(Product('brick', 500.0, 2, Type.materials));
print('Total price: \$${cart.getTotalPrice()}');
print('Total items count: ${cart.getItemsCount()}');
print('Product fullname: ${product.fullname}');
print('Product with discount: ${product.discountedPrice}');
Future.delayed(Duration(seconds: 5)).then((_) => print(product.name));
List<Product> products = await cart.getItemAsync();
print('Number elements from async method: ${products.length}');
}