【问题标题】:How do I get the total price of all the items in the basket?如何获得购物篮中所有商品的总价?
【发布时间】:2020-12-03 14:00:47
【问题描述】:

如何获得购物篮中所有商品的总价?

我想在购物车中添加商品后获取购物车中所有商品的总价。当每件商品的数量增加时,价格也应该增加,当数量减少时,价格也会下降。请帮我解决这个问题,

购物车类的代码如下。

购物车类

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dish_object.dart';

class Cart extends StatefulWidget {
  final List<Dish> _cart;
  Cart(this._cart);

  @override
  _CartState createState() => _CartState(this._cart);
}

class _CartState extends State<Cart> {
  _CartState(this._cart);

  List<Dish> _cart;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Cart'),
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.send_rounded),
              tooltip: "Confirm Order",
              onPressed: () {
                if (_cart.isNotEmpty) {
                  setState(() {
                    Fluttertoast.showToast(
                        msg: "Order Confirmed",
                        toastLength: Toast.LENGTH_LONG,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIosWeb: 1,
                        backgroundColor: Colors.grey,
                        textColor: Colors.white,
                        fontSize: 16.0);
                  });
                }
                if (_cart.isEmpty) {
                  setState(() {
                    Fluttertoast.showToast(
                        msg: "Cart Empty",
                        toastLength: Toast.LENGTH_LONG,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIosWeb: 1,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                        fontSize: 16.0);
                  });
                }
              }),
          if (_cart.length > 0)
            Padding(
              padding: const EdgeInsets.only(left: 0.0),
              child: CircleAvatar(
                radius: 10.0,
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
                child: Text(
                  _cart.length.toString(),
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 12.0,
                  ),
                ),
              ),
            ),
        ],
      ),
      body: ListView.builder(
        itemCount: _cart.length,
        itemBuilder: (context, index) {
          var item = _cart[index];
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
            child: Card(
              elevation: 4.0,
              child: ListTile(
                //Leading
                leading:
                    Text(item.category + "\n" + "R" + item.price.toString()),

                //Title
                title: Text(item.brandName +
                    "\n" +
                    "(" +
                    item.counter.toString() +
                    ")"),
                //Subtitle
                subtitle: GestureDetector(
                  child: Icon(
                    Icons.add,
                    color: Colors.green,
                  ),
                  onTap: () {
                    setState(() {
                      item.incrementCounter();
                    });
                  },
                ),

                //Trailing
                trailing: GestureDetector(
                  child: Icon(
                    Icons.remove_circle,
                    color: Colors.red,
                  ),
                  onTap: () {
                    setState(() {
                      item.decrementCounter();
                    });
                  },
                ),
                isThreeLine: true,
              ),
            ),
          );
        },
      ),
    );
  }
}

【问题讨论】:

  • 您的textField 总共在哪里?

标签: flutter dart


【解决方案1】:

在你的 Dish 类中添加价格计算方法

class Dish{
  int count;
  double price;

  double totalPrice(){
    // add your price calculation logic
    return price * count;
  }
}

在您的购物车小部件中添加以下方法

double cartTotalPrice(){
  double total=0;
  _cart.forEach((item) { total += item.totalPrice(); });
  return total;
}

或者使用单行解决方案

double total = _cart.map<double>((item) => item.count*item.price).reduce((value1, value2) => value1+value2);

【讨论】:

  • 变量total抛出错误,读取getter 'total' is not defined for type disc
  • 你可以在这里https://dartpad.dev查看工作代码。确保您没有覆盖变量名总计
  • cart 类的 total 方法中的 _cart.map 现在会抛出一个错误,提示 无法在初始化程序中访问实例成员 '_cart'。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2011-09-24
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
相关资源
最近更新 更多