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

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

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

cart 类中的总变量输出 null

购物车类

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;

  double totalPrice = 0;

  double getTotalPrice() {
    double total = 0;
    _cart.forEach((item) {
      total += item.totalPrice;
    });
    setState(() {
      totalPrice = total;
    });
  }

  @override
  void initState() {
    super.initState();
    getTotalPrice();
  }

  @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.totalPrice.toString() +
                    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,
              ),
            ),
          );
        },
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以尝试添加一个变量 _totalPrice 并访问它

        double _totalPrice = 0;
    

    可以通过一个通用函数来改变:

    double getTotalPrice() {
        double total = 0;
        _cart.forEach((item) {
          total+= item.totalPrice;
        });
        setState(() {
            _totalPrice = total;
           });
      }
     
    

    将 getTotalPrice() 添加到您的 initState() 函数中,以便在安装屏幕或代码中的其他位置时调用它。

    每次添加/删除产品时增加/减少总价值

      _addPrice(double price) {
           setState(() {
            _totalPrice += price;
           });
        }
    
    _subtractPrice(double price) {
           setState(() {
            _totalPrice -= price;
           });
        }
    

    -- 编辑:并确保将变量插入到视图中要显示的任何位置

    【讨论】:

    • 我在哪里声明 _totalPrice 变量?
    • 在您的其他变量声明下方,在本例中位于 List _cart;
    • 在 Dish 课上有什么我应该做的吗?
    • 我认为没有必要。您是否尝试过在您想要显示的代码中添加 _totalPrice,并在您的 initState() 方法中添加我上面提到的 getTotalPrice() 方法?
    • 是的,我在总变量上收到未定义名称的错误
    【解决方案2】:

    cartTotalPrice() 除了在本地保持总价格外,并没有做太多的事情。它从来没有被调用过。在外部声明总变量并将每个主体包装在setState() 中,或者只是从方法中返回它。在将新商品添加到 _cart 后不要忘记重置总变量,或者只是将新商品的价格添加到总计中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-09
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      相关资源
      最近更新 更多